From 242e2b0001095524382183b771aa444310900942 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Wed, 14 Oct 2026 07:52:14 +0800 Subject: [PATCH 1/9] fix(ghidra): preserve function facet and call coverage (#3002) * fix(ghidra): preserve observed function facet and call coverage Declare successful query availability in the Java producer, including explicit unavailable pseudocode reasons. Carry observed static call-set coverage through the parsed provider result and Evidence without inventing facts for legacy omissions. Use Ghidra indexed comment addresses over the function body and entry, retaining cancellation checks and sparse collection. Closes #2951 Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> * fix(ghidra): retain unresolved call coverage in observations Share decoded unresolved-call facts between dossiers, callee coverage and reference observations. Combine terminal and unresolved observations in one instruction traversal and retain site records only when requested. Keep missing procedure identities incomplete and validate unresolved locations at the provider boundary. Bind snapshots to the corrected call coverage profile so older complete claims cannot replay under the new semantics. Add real public MCP callback trace/comparison regressions. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> * fix(ghidra): separate reference targets from callee coverage Reuse containing-function ownership for resolved reference identities and independently compare those identities with the actual returned callee set. Keep known interior routes out of unresolved site records while retaining partial inventory coverage. Advance the coverage profile to v3 and reject interim v2 cache bindings. Add a real Ghidra producer regression with restored reference metadata; the previous bridge fails the known-route assertion. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> * fix(ghidra): measure incoming call coverage across function bodies Compare incoming reference source identities across the owned function body and entry with the actual returned caller set. Stream caller-only checks and reuse dossier reference observations. Combine caller/callee coverage from observed counts without reinterpreting serialized metadata, and share the body scope owner with comments and references. Bind snapshots to function-body coverage semantics v4 and preserve the real off-entry caller regression. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> * fix(ghidra): preserve whole-scope directional call coverage Check body-and-entry call references independently of decoded instruction flow. Reuse collected dossier references and stream inventory-only coverage checks. Keep caller-only gaps distinct from incomplete outgoing coverage in offline path reconstruction, and invalidate prior snapshot profiles. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> * fix(mcp): retain compact Evidence field types Share optional diagnostics across the three tagged relationship coverage states instead of advertising duplicate branches. Preserve coverage validation while keeping compact Evidence properties within the existing reference expansion budget. Verify invalid direction cardinalities against the actual SDK-advertised schema. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> --------- Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- bridge/ghidra/ReaGhidraBridge.java | 379 +++++++++++++----- scripts/lib/native-value-e2e.mjs | 82 ++++ scripts/lib/real-ghidra-boundaries.mjs | 2 +- src/domain/callPath.test.ts | 36 ++ src/domain/callPath.ts | 4 +- src/domain/functionCallCoverage.test.ts | 40 +- src/domain/functionCallCoverage.ts | 37 +- src/domain/relationshipCoverage.ts | 23 +- src/ghidra/GhidraAnalysisProfile.ts | 6 +- src/ghidra/GhidraFunctionValues.test.ts | 113 ++++++ src/ghidra/GhidraFunctionValues.ts | 17 +- src/ghidra/GhidraProvider.behavior.test.ts | 13 +- src/ghidra/GhidraProviderCapabilities.ts | 17 - src/ghidra/GhidraProviderClient.ts | 7 +- src/ghidra/GhidraSnapshotCache.test.ts | 158 ++++++-- .../mcp/functionCallDirectionsMcp.test.ts | 138 +++++++ tests/boundary/mcp/ghidraEvidenceMcp.test.ts | 32 +- .../conformance/ghidra/ReaNoReturnProbe.java | 115 ++++++ 18 files changed, 1024 insertions(+), 195 deletions(-) create mode 100644 tests/boundary/mcp/functionCallDirectionsMcp.test.ts diff --git a/bridge/ghidra/ReaGhidraBridge.java b/bridge/ghidra/ReaGhidraBridge.java index f91f003e4..e184dc206 100644 --- a/bridge/ghidra/ReaGhidraBridge.java +++ b/bridge/ghidra/ReaGhidraBridge.java @@ -81,6 +81,7 @@ import ghidra.program.model.listing.Function; import ghidra.program.model.listing.FunctionIterator; import ghidra.program.model.listing.Instruction; import ghidra.program.model.listing.InstructionIterator; +import ghidra.program.model.listing.Listing; import ghidra.program.model.listing.Variable; import ghidra.program.model.mem.MemoryBlock; import ghidra.program.model.mem.MemoryBlockSourceInfo; @@ -405,7 +406,9 @@ public final class ReaGhidraBridge extends HeadlessScript { case "xrefs" -> xrefs(request.params); case "analyze_function" -> { FunctionAnalysisObservation observation = analyzeFunctionObservation(request.params); - yield functionObservation(observation.dossier(), observation.limitations()); + JsonObject result = functionObservation(observation.dossier(), observation.limitations()); + result.add("relationship_coverage", observation.relationshipCoverage()); + yield result; } case "set_address_name", "set_addresses_names" -> { if (!descriptor.transport.equals("unix-socket")) @@ -1016,12 +1019,19 @@ public final class ReaGhidraBridge extends HeadlessScript { for (Function item : ordered) { result.add(canonicalAddress(item.getEntryPoint())); } - return functionObservation( - result, - noReturnCallLimitations( + if (callers) { + JsonObject observation = functionObservation(result, noReturnCallLimitations( currentProgram.getListing().getInstructions(function.getBody(), true) - ) + )); + observation.add("relationship_coverage", callRelationshipCoverage(null, + unrepresentedIncomingCalls(function, observed))); + monitor.checkCancelled(); + return observation; + } + CallBoundaryObservation calls = callBoundaryObservation( + function, currentProgram.getListing().getInstructions(function.getBody(), true), observed, false, null ); + return callRelationshipObservation(result, calls); } private JsonObject procedureInfo(JsonObject params) throws Exception { @@ -1071,18 +1081,10 @@ public final class ReaGhidraBridge extends HeadlessScript { result.addProperty("direction", direction); result.add("references", edges); result.addProperty("reference_kinds_available", true); - JsonArray unresolvedCalls = new JsonArray(); - if (direction.equals("outgoing")) for (Instruction instruction : scanInstructions(function, Integer.MAX_VALUE).instructions) { - if (!instruction.getFlowType().isCall()) continue; - boolean resolved = false; - for (Reference reference : instruction.getReferencesFrom()) if (reference.getReferenceType().isCall()) resolved = true; - if (!resolved) { - JsonObject site = new JsonObject(); - site.addProperty("address", canonicalAddress(instruction.getAddress())); - site.addProperty("reason", "Instruction decoder identifies a call but ReferenceManager supplies no call destination"); - unresolvedCalls.add(site); - } - } + JsonArray unresolvedCalls = direction.equals("outgoing") + ? callBoundaryObservation( + function, currentProgram.getListing().getInstructions(function.getBody(), true), null, true, references + ).unresolvedCalls() : new JsonArray(); result.add("unresolved_calls", unresolvedCalls); return result; } @@ -1490,16 +1492,28 @@ public final class ReaGhidraBridge extends HeadlessScript { InstructionScan scan = scanInstructions(function, Integer.MAX_VALUE); DecompileResults decompilation = decompile(function); String pseudocode = decompiledText(decompilation); - List incomingReferences = collectReferences(function, "incoming") - .stream() + JsonObject availability = new JsonObject(); + availability.add("pseudocode", facetAvailability( + pseudocode != null, + function.isExternal() ? "Ghidra does not decompile external functions." + : function.getBody().isEmpty() ? "Ghidra has no function body to decompile." + : "Ghidra completed decompilation without returning pseudocode." + )); + if (pseudocode == null) { + pseudocode = ""; + } + List bodyIncoming = collectReferences(function, "incoming"); + List incomingReferences = bodyIncoming.stream() .filter(reference -> !function.getBody().contains(reference.getFromAddress())) .toList(); List outgoingReferences = collectReferences(function, "outgoing"); JsonArray incoming = referenceEdges(incomingReferences); JsonArray outgoing = referenceEdges(outgoingReferences); - JsonArray comments = comments(scan.instructions); - JsonArray callers = procedureIdentities(function.getCallingFunctions(monitor)); - JsonArray callees = procedureIdentities(function.getCalledFunctions(monitor)); + JsonArray comments = comments(function); + Set callerFunctions = function.getCallingFunctions(monitor); + JsonArray callers = procedureIdentities(callerFunctions); + Set calleeFunctions = function.getCalledFunctions(monitor); + JsonArray callees = procedureIdentities(calleeFunctions); JsonArray referencedStrings = referencedStrings(outgoingReferences); JsonArray referencedNames = referencedNames(outgoingReferences); JsonArray blocks = basicBlockValues(function); @@ -1511,7 +1525,7 @@ public final class ReaGhidraBridge extends HeadlessScript { procedure.add("locals", functionLocals(function)); JsonObject result = new JsonObject(); result.add("procedure", procedure); - result.addProperty("pseudocode", pseudocode == null ? "" : pseudocode); + result.addProperty("pseudocode", pseudocode); result.add("assembly", assembly); result.add("comments", comments); result.add("callers", callers); @@ -1520,20 +1534,6 @@ public final class ReaGhidraBridge extends HeadlessScript { result.add("outgoing_references", outgoing); result.add("referenced_strings", referencedStrings); result.add("referenced_names", referencedNames); - JsonObject facets = new JsonObject(); - JsonObject pseudocodeAvailability = new JsonObject(); - pseudocodeAvailability.addProperty("available", pseudocode != null); - if (pseudocode == null) { - pseudocodeAvailability.addProperty("reason", "Ghidra did not supply pseudocode."); - } - facets.add("pseudocode", pseudocodeAvailability); - for (String facet : List.of("assembly", "comments", "callers", "callees", - "references", "strings_names", "cfg")) { - JsonObject available = new JsonObject(); - available.addProperty("available", true); - facets.add(facet, available); - } - result.add("facet_availability", facets); boolean swift = swiftProgram(); boolean aarch64 = currentProgram.getLanguageID().getIdAsString().startsWith("AARCH64:"); SwiftStringLiteralDecode swiftLiterals = swift && aarch64 ? swiftStringLiterals(function) : null; @@ -1547,6 +1547,15 @@ public final class ReaGhidraBridge extends HeadlessScript { nativeApiBoundary(function, decompilation) ); result.add("native_value_flow", nativeValueFlow(decompilation)); + // Successful full queries distinguish collected empty sets from missing facts. + // Availability does not claim that Ghidra resolved every runtime relationship. + for (String facet : List.of("comments", "callers", "callees", "references", "strings_names", "cfg")) { + availability.add(facet, facetAvailability(true, null)); + } + availability.add("assembly", facetAvailability( + !scan.truncated(), "The function instruction scan was truncated." + )); + result.add("facet_availability", availability); JsonArray limitations = new JsonArray(); limitations.add( "Unresolved computed or indirect flows without target addresses are not represented as reference edges." @@ -1574,8 +1583,10 @@ public final class ReaGhidraBridge extends HeadlessScript { "Swift String literal decoding is implemented for AArch64 register pairs only; no Swift literals were decoded for this architecture." ); } - List boundaryLimitations = noReturnCallLimitations(scan.instructions); - for (String limitation : boundaryLimitations) { + CallBoundaryObservation calls = callBoundaryObservation( + function, scan.instructions, calleeFunctions, true, outgoingReferences); + result.add("unresolved_calls", calls.unresolvedCalls()); + for (String limitation : calls.limitations()) { limitations.add(limitation); } if (decompilation != null && decompilation.getErrorMessage() != null && @@ -1583,7 +1594,14 @@ public final class ReaGhidraBridge extends HeadlessScript { limitations.add("Ghidra decompiler diagnostic: " + decompilation.getErrorMessage()); } result.add("limitations", limitations); - return new FunctionAnalysisObservation(result, boundaryLimitations); + monitor.checkCancelled(); + int missingCallers = 0; + for (Reference reference : bodyIncoming) { + monitor.checkCancelled(); + if (unrepresentedCaller(reference, callerFunctions)) missingCallers++; + } + return new FunctionAnalysisObservation(result, calls.limitations(), + callRelationshipCoverage(calls, missingCallers)); } private JsonObject nativeValueFlow(DecompileResults decompilation) throws Exception { @@ -3287,54 +3305,202 @@ public final class ReaGhidraBridge extends HeadlessScript { return result; } + private static JsonObject facetAvailability(boolean available, String reason) { + JsonObject result = new JsonObject(); + result.addProperty("available", available); + if (!available) result.addProperty("reason", reason); + return result; + } + + private JsonObject callRelationshipObservation(JsonElement value, CallBoundaryObservation calls) + throws Exception { + monitor.checkCancelled(); + JsonObject result = functionObservation(value, calls.limitations()); + result.add("relationship_coverage", callRelationshipCoverage(calls, null)); + return result; + } + + private static JsonObject callRelationshipCoverage( + CallBoundaryObservation calls, Integer missingCallers) { + JsonObject coverage = completeResolvedCallCoverage(); + Integer omitted = calls == null ? null : calls.unrepresentedCalleeCalls(); + JsonArray directions = new JsonArray(); + if (missingCallers != null && missingCallers > 0) directions.add("callers"); + String callerLimitation = missingCallers != null && missingCallers > 0 + ? "Ghidra's caller inventory omits sources of " + missingCallers + + " call reference(s) into this function's body." : null; + if ((calls != null && omitted == null) || (calls == null && missingCallers == null)) { + coverage.addProperty("status", "unknown"); + String reason = calls == null ? "No call inventory was examined." + : "The callee inventory was not examined alongside decoded call targets."; + coverage.addProperty("reason", reason + (callerLimitation == null ? "" : " " + callerLimitation)); + if (calls == null && missingCallers == null) directions.add("callers"); + directions.add("callees"); + coverage.add("limited_directions", directions); + return coverage; + } + JsonArray limitations = new JsonArray(); + if (callerLimitation != null) limitations.add(callerLimitation); + if (omitted != null && omitted > 0) { + limitations.add("Ghidra's callee inventory omits targets of " + omitted + + " call reference(s) or decoded call(s) without destinations."); + directions.add("callees"); + } + if (!limitations.isEmpty()) { + coverage.addProperty("status", "partial"); + coverage.add("limitations", limitations); + coverage.add("limited_directions", directions); + } + return coverage; + } + + private static JsonObject completeResolvedCallCoverage() { + JsonObject coverage = new JsonObject(); + coverage.addProperty("status", "complete"); + JsonArray diagnostics = new JsonArray(); + diagnostics.add( + "Only resolved Ghidra call references are returned; unresolved computed or indirect calls remain unknown, while function classifications distinguish thunks and externals." + ); + coverage.add("diagnostics", diagnostics); + return coverage; + } + + private boolean unrepresentedCaller(Reference reference, Set callers) { + if (!reference.getReferenceType().isCall()) return false; + Function caller = containingFunction(reference.getFromAddress()); + return caller == null || !callers.contains(caller); + } + + private int unrepresentedIncomingCalls(Function function, Set callers) + throws Exception { + int[] omitted = { 0 }; + visitReferences(function, "incoming", reference -> { + if (unrepresentedCaller(reference, callers)) omitted[0]++; + }); + return omitted[0]; + } + private List noReturnCallLimitations(Iterable instructions) throws Exception { List limitations = new ArrayList<>(); for (Instruction instruction : instructions) { monitor.checkCancelled(); - if (!instruction.getFlowType().isCall() || !instruction.getFlowType().isTerminal()) { - continue; - } - Address[] destinations = instruction.getFlows(); - StringBuilder limitation = new StringBuilder(); - limitation.append("Ghidra Listing reports a terminal call at ") - .append(canonicalAddress(instruction.getAddress())); - if (destinations.length == 0) { - limitation.append(" with no resolved callee; its no-return basis is unknown."); - } - else { - limitation.append(" to "); - for (int index = 0; index < destinations.length; index++) { - if (index > 0) limitation.append(", "); - Address destination = destinations[index]; - limitation.append(canonicalAddress(destination)); - Function target = currentProgram.getFunctionManager().getFunctionAt(destination); - if (target == null) { - limitation.append(" (callee identity unknown)"); - } - else { - limitation.append(" ").append(procedureName(target)); - limitation.append(" (external=").append(target.isExternal()); - limitation.append(", thunk=").append(target.isThunk()); - limitation.append(", hasNoReturn=").append(target.hasNoReturn()).append(")"); - } - } - limitation.append("; fallthrough is excluded by Ghidra's flow model."); - Function target = destinations.length == 1 - ? currentProgram.getFunctionManager().getFunctionAt(destinations[0]) - : null; - if (target != null && target.hasNoReturn()) { - limitation.append(" This records Ghidra's FunctionManager flag, not an independent verification that the callee cannot return."); - } - else { - limitation.append(" The reason for the terminal flow is not established by this observation."); - } - } - limitations.add(limitation.toString()); + String limitation = terminalCallLimitation(instruction); + if (limitation != null) limitations.add(limitation); } return limitations; } + private CallBoundaryObservation callBoundaryObservation( + Function function, Iterable instructions, Set returnedCallees, + boolean includeUnresolvedSites, List observedReferences) + throws Exception { + List limitations = new ArrayList<>(); + CallBoundaryReferences calls = new CallBoundaryReferences(returnedCallees, includeUnresolvedSites); + if (observedReferences == null) visitReferences(function, "outgoing", calls::observe); + else for (Reference reference : observedReferences) { + monitor.checkCancelled(); + calls.observe(reference); + } + for (Instruction instruction : instructions) { + monitor.checkCancelled(); + String limitation = terminalCallLimitation(instruction); + if (limitation != null) limitations.add(limitation); + if (!instruction.getFlowType().isCall()) continue; + boolean destination = false; + for (Reference reference : instruction.getReferencesFrom()) { + if (!reference.getReferenceType().isCall()) continue; + destination = true; + break; + } + if (!destination) { + calls.unrepresented++; + calls.unresolved(instruction.getAddress(), + "Instruction decoder identifies a call but ReferenceManager supplies no call destination"); + } + } + return new CallBoundaryObservation(List.copyOf(limitations), + returnedCallees == null ? null : calls.unrepresented, calls.unresolvedCalls()); + } + + private final class CallBoundaryReferences { + private final Set returnedCallees; + private final TreeMap unresolved; + private int unrepresented; + + CallBoundaryReferences(Set returnedCallees, boolean includeUnresolvedSites) { + this.returnedCallees = returnedCallees; + unresolved = includeUnresolvedSites ? new TreeMap<>() : null; + } + + void observe(Reference reference) { + if (!reference.getReferenceType().isCall()) return; + // Reference identity follows the same containing-function owner as referenceEdge. + Function target = containingFunction(reference.getToAddress()); + if (returnedCallees != null && (target == null || !returnedCallees.contains(target))) + unrepresented++; + if (target == null) unresolved(reference.getFromAddress(), + "A call destination has no known containing Ghidra procedure"); + } + + void unresolved(Address address, String reason) { + if (unresolved != null) unresolved.put(address, reason); + } + + JsonArray unresolvedCalls() { + if (unresolved == null) return null; + JsonArray result = new JsonArray(); + for (var item : unresolved.entrySet()) { + JsonObject site = new JsonObject(); + site.addProperty("address", canonicalAddress(item.getKey())); + site.addProperty("reason", item.getValue()); + result.add(site); + } + return result; + } + } + + private String terminalCallLimitation(Instruction instruction) { + if (!instruction.getFlowType().isCall() || !instruction.getFlowType().isTerminal()) + return null; + Address[] destinations = instruction.getFlows(); + StringBuilder limitation = new StringBuilder(); + limitation.append("Ghidra Listing reports a terminal call at ") + .append(canonicalAddress(instruction.getAddress())); + if (destinations.length == 0) { + limitation.append(" with no resolved callee; its no-return basis is unknown."); + } + else { + limitation.append(" to "); + for (int index = 0; index < destinations.length; index++) { + if (index > 0) limitation.append(", "); + Address destination = destinations[index]; + limitation.append(canonicalAddress(destination)); + Function target = currentProgram.getFunctionManager().getFunctionAt(destination); + if (target == null) { + limitation.append(" (callee identity unknown)"); + } + else { + limitation.append(" ").append(procedureName(target)); + limitation.append(" (external=").append(target.isExternal()); + limitation.append(", thunk=").append(target.isThunk()); + limitation.append(", hasNoReturn=").append(target.hasNoReturn()).append(")"); + } + } + limitation.append("; fallthrough is excluded by Ghidra's flow model."); + Function target = destinations.length == 1 + ? currentProgram.getFunctionManager().getFunctionAt(destinations[0]) + : null; + if (target != null && target.hasNoReturn()) { + limitation.append(" This records Ghidra's FunctionManager flag, not an independent verification that the callee cannot return."); + } + else { + limitation.append(" The reason for the terminal flow is not established by this observation."); + } + } + return limitation.toString(); + } + private static String renderAssembly(List instructions) { return String.join("\n", renderAssemblyLines(instructions)); } @@ -3358,15 +3524,27 @@ public final class ReaGhidraBridge extends HeadlessScript { private List collectReferences( Function function, String direction) throws Exception { + TreeMap observed = new TreeMap<>(); + visitReferences(function, direction, reference -> addReference(observed, reference)); + List result = new ArrayList<>(observed.values()); + result.sort(REFERENCE_ORDER); + return result; + } + + @FunctionalInterface + private interface ReferenceVisitor { + void accept(Reference reference) throws Exception; + } + + private void visitReferences(Function function, String direction, ReferenceVisitor visitor) + throws Exception { // References can target instruction interiors or originate in embedded // data. Use actual body ownership, including an external's exact entry. - AddressSet scope = new AddressSet(function.getBody()); - scope.add(function.getEntryPoint()); + AddressSet scope = functionObservationScope(function); boolean outgoing = direction.equals("outgoing"); AddressIterator addresses = outgoing ? currentProgram.getReferenceManager().getReferenceSourceIterator(scope, true) : currentProgram.getReferenceManager().getReferenceDestinationIterator(scope, true); - TreeMap observed = new TreeMap<>(); while (addresses.hasNext()) { monitor.checkCancelled(); Address address = addresses.next(); @@ -3374,7 +3552,7 @@ public final class ReaGhidraBridge extends HeadlessScript { for (Reference reference : currentProgram.getReferenceManager() .getReferencesFrom(address)) { monitor.checkCancelled(); - addReference(observed, reference); + if (!reference.isEntryPointReference()) visitor.accept(reference); } } else { @@ -3382,19 +3560,14 @@ public final class ReaGhidraBridge extends HeadlessScript { .getReferencesTo(address); while (iterator.hasNext()) { monitor.checkCancelled(); - addReference(observed, iterator.next()); + Reference reference = iterator.next(); + if (!reference.isEntryPointReference()) visitor.accept(reference); } } } - List result = new ArrayList<>(observed.values()); - result.sort(REFERENCE_ORDER); - return result; } private static void addReference(TreeMap observed, Reference reference) { - if (reference.isEntryPointReference()) { - return; - } String key = canonicalAddress(reference.getFromAddress()) + "\u0000" + canonicalAddress(reference.getToAddress()) + "\u0000" + reference.getReferenceType().getName() + "\u0000" + @@ -3403,6 +3576,12 @@ public final class ReaGhidraBridge extends HeadlessScript { observed.putIfAbsent(key, reference); } + private static AddressSet functionObservationScope(Function function) { + AddressSet scope = new AddressSet(function.getBody()); + scope.add(function.getEntryPoint()); + return scope; + } + private JsonArray referenceEdges(List references) { JsonArray result = new JsonArray(); for (Reference reference : references) { @@ -3556,23 +3735,28 @@ public final class ReaGhidraBridge extends HeadlessScript { return result; } - private static JsonArray comments(List instructions) { + private JsonArray comments(Function function) throws Exception { + Listing listing = currentProgram.getListing(); + AddressSet scope = functionObservationScope(function); + AddressIterator addresses = listing.getCommentAddressIterator(scope, true); TreeMap observed = new TreeMap<>(); - for (Instruction instruction : instructions) { + while (addresses.hasNext()) { + monitor.checkCancelled(); + Address address = addresses.next(); for (CommentType type : CommentType.values()) { - String text = instruction.getComment(type); + String text = listing.getComment(type, address); if (text == null || text.isEmpty()) { continue; } String kind = type == CommentType.EOL ? "inline" : "comment"; JsonObject item = new JsonObject(); - item.addProperty("address", canonicalAddress(instruction.getAddress())); + item.addProperty("address", canonicalAddress(address)); item.addProperty("kind", kind); item.addProperty("text", text); - String key = canonicalAddress(instruction.getAddress()) + "\u0000" + + String key = canonicalAddress(address) + "\u0000" + kind + "\u0000" + type.name() + "\u0000" + text; observed.put(key, item); - } + } } JsonArray result = new JsonArray(); observed.values().forEach(result::add); @@ -4508,7 +4692,8 @@ public final class ReaGhidraBridge extends HeadlessScript { private record InventoryItem(Address address, String value, JsonObject facts) {} private record AddressNameRequest(String inputAddress, Address address, String name) {} private record FunctionEntry(Function function, InventoryItem item) {} - private record FunctionAnalysisObservation(JsonObject dossier, List limitations) {} + private record FunctionAnalysisObservation(JsonObject dossier, List limitations, JsonObject relationshipCoverage) {} + private record CallBoundaryObservation(List limitations, Integer unrepresentedCalleeCalls, JsonArray unresolvedCalls) {} private record SwiftStringLiteralDecode(JsonArray literals, JsonArray omissions) {} private record SwiftLiteralLayout( String representation, diff --git a/scripts/lib/native-value-e2e.mjs b/scripts/lib/native-value-e2e.mjs index d329bc822..916533a87 100644 --- a/scripts/lib/native-value-e2e.mjs +++ b/scripts/lib/native-value-e2e.mjs @@ -215,6 +215,27 @@ async function verifyNativeValueAdapters( const functionEvidence = parseEvidence(analyzed.structuredContent); assert.equal(functionEvidence.operation, "analyze_function"); assert.equal(functionEvidence.provider.id, "ghidra"); + assert.deepEqual( + functionEvidence.normalized_result.facet_availability, + Object.fromEntries( + [ + "pseudocode", + "assembly", + "comments", + "callers", + "callees", + "references", + "strings_names", + "cfg", + ].map((facet) => [facet, { available: true }]), + ), + ); + assert.equal(functionEvidence.relationship_coverage?.status, "complete"); + assert.ok( + functionEvidence.relationship_coverage.diagnostics.some((diagnostic) => + diagnostic.includes("indirect calls remain unknown"), + ), + ); const functionProfile = analysisProfileSchema.parse( functionEvidence.analysis_profile, ); @@ -247,6 +268,7 @@ async function verifyNativeValueAdapters( assert.ok( comparisonEvidence.evidence_links.includes(functionEvidence.evidence_id), ); + await verifyUnresolvedCallEvidence(client); const bundle = await client.callTool({ name: "get_evidence_bundle", arguments: {}, @@ -307,3 +329,63 @@ async function verifyNativeValueAdapters( unknowns: cliGraph.unknowns.length, }; } + +async function verifyUnresolvedCallEvidence(client) { + const inventory = await client.callTool({ + name: "list_procedures", + arguments: {}, + }); + assert.notEqual(inventory.isError, true, JSON.stringify(inventory)); + const procedures = parseEvidence( + inventory.structuredContent, + ).normalized_result; + const indirect = procedures.find((item) => + item.value.endsWith("rea_ghidra_inventory_indirect"), + ); + const leaf = procedures.find((item) => + item.value.endsWith("rea_ghidra_inventory_leaf"), + ); + assert.ok( + indirect && leaf, + "Source fixture lacks the unresolved callback and its possible target", + ); + const analyzed = await client.callTool( + { name: "analyze_function", arguments: { procedure: indirect.address } }, + { timeout: 180000 }, + ); + assert.notEqual(analyzed.isError, true, JSON.stringify(analyzed)); + const evidence = parseEvidence(analyzed.structuredContent); + assert.equal(evidence.relationship_coverage?.status, "partial"); + assert.ok(evidence.normalized_result.unresolved_calls.length > 0); + const traced = await client.callTool( + { + name: "trace_call_path", + arguments: { + start: indirect.address, + goal: leaf.address, + direction: "forward", + }, + }, + { timeout: 180000 }, + ); + assert.notEqual(traced.isError, true, JSON.stringify(traced)); + const trace = parseEvidence(traced.structuredContent).normalized_result; + assert.equal(trace.goal_status, "unknown"); + assert.equal(trace.truncated, true); + assert.ok(trace.residual_unknowns.length > 0); + const compared = await client.callTool( + { + name: "compare_functions", + arguments: { + left: analyzed.structuredContent, + right: analyzed.structuredContent, + }, + }, + { timeout: 180000 }, + ); + assert.notEqual(compared.isError, true, JSON.stringify(compared)); + assert.equal( + parseEvidence(compared.structuredContent).normalized_result.status, + "unknown", + ); +} diff --git a/scripts/lib/real-ghidra-boundaries.mjs b/scripts/lib/real-ghidra-boundaries.mjs index c2347dde1..54376c389 100644 --- a/scripts/lib/real-ghidra-boundaries.mjs +++ b/scripts/lib/real-ghidra-boundaries.mjs @@ -136,7 +136,7 @@ export async function verifyGhidraBoundaries( assert.deepEqual(externalDossier.callees, []); assert.deepEqual(externalDossier.facet_availability.pseudocode, { available: false, - reason: "Ghidra did not supply pseudocode.", + reason: "Ghidra does not decompile external functions.", }); for (const facet of [ "assembly", diff --git a/src/domain/callPath.test.ts b/src/domain/callPath.test.ts index 80a260ac3..048cb63b4 100644 --- a/src/domain/callPath.test.ts +++ b/src/domain/callPath.test.ts @@ -337,6 +337,42 @@ describe("call path topology and capacity", () => { }); }); +describe("directional call relationship coverage", () => { + it.each([ + { + directions: ["callers"] as ["callers"], + status: "not_found", + exhaustive: true, + }, + { + directions: ["callees"] as ["callees"], + status: "unknown", + exhaustive: false, + }, + { + directions: ["callers", "callees"] as ["callers", "callees"], + status: "unknown", + exhaustive: false, + }, + ])( + "uses $directions coverage for the forward search", + ({ directions, status, exhaustive }) => { + const limitation = "The inventory omitted a reference."; + const relationshipCoverage: RelationshipCoverage = { + status: "partial", + limitations: [limitation], + limited_directions: directions, + }; + const result = run([ + observe("0x1000", ["0x2000"], "rea-workflow", { relationshipCoverage }), + observe("0x2000", [], "rea-workflow", { relationshipCoverage }), + ]); + expect(result).toMatchObject({ status, search_scope: { exhaustive } }); + expect(result.limitations).toContain(limitation); + }, + ); +}); + describe("explicit call relationship coverage", () => { it("accumulates 150,000 partial reasons without argument-stack exhaustion", () => { const result = run([ diff --git a/src/domain/callPath.ts b/src/domain/callPath.ts index 3ffbc2356..65524fbc2 100644 --- a/src/domain/callPath.ts +++ b/src/domain/callPath.ts @@ -10,7 +10,7 @@ import { parseFunctionEvidence, type FunctionSnapshot, } from "./functionDossierEvidence.js"; -import { isCallerOnlyUnknownCoverage } from "./functionCallCoverage.js"; +import { isCallerOnlyIncompleteCoverage } from "./functionCallCoverage.js"; import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; /** Minimal directed caller-to-callee adjacency for call-path search. */ @@ -268,7 +268,7 @@ const inspectSearch = ({ coverage === null ? snapshot.limitations.length > 0 : coverage.status !== "complete" && - !isCallerOnlyUnknownCoverage(coverage) + !isCallerOnlyIncompleteCoverage(coverage) ) incompleteExpandedCoverage = true; } else if (node === goal) { diff --git a/src/domain/functionCallCoverage.test.ts b/src/domain/functionCallCoverage.test.ts index 6fd3fb045..543f6ca92 100644 --- a/src/domain/functionCallCoverage.test.ts +++ b/src/domain/functionCallCoverage.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { combineFunctionRelationshipCoverage, - isCallerOnlyUnknownCoverage, + isCallerOnlyIncompleteCoverage, } from "./functionCallCoverage.js"; import type { RelationshipCoverage } from "./relationshipCoverage.js"; @@ -22,14 +22,14 @@ const cappedCallees: RelationshipCoverage = { }; const complete: RelationshipCoverage = { status: "complete" }; -describe("isCallerOnlyUnknownCoverage", () => { +describe("isCallerOnlyIncompleteCoverage", () => { it("detects unknown callers beside complete callees", () => { const combined = combineFunctionRelationshipCoverage( unknownCallers, complete, ); expect(combined.status).toBe("unknown"); - expect(isCallerOnlyUnknownCoverage(combined)).toBe(true); + expect(isCallerOnlyIncompleteCoverage(combined)).toBe(true); }); it("rejects unknown callees beside complete callers", () => { @@ -37,7 +37,7 @@ describe("isCallerOnlyUnknownCoverage", () => { complete, unknownCallees, ); - expect(isCallerOnlyUnknownCoverage(combined)).toBe(false); + expect(isCallerOnlyIncompleteCoverage(combined)).toBe(false); }); it("rejects unknown coverage on both sides", () => { @@ -45,7 +45,7 @@ describe("isCallerOnlyUnknownCoverage", () => { unknownCallers, unknownCallees, ); - expect(isCallerOnlyUnknownCoverage(combined)).toBe(false); + expect(isCallerOnlyIncompleteCoverage(combined)).toBe(false); }); it("rejects unknown callers beside IDA-capped callees", () => { @@ -54,11 +54,37 @@ describe("isCallerOnlyUnknownCoverage", () => { cappedCallees, ); expect(combined.status).toBe("unknown"); - expect(isCallerOnlyUnknownCoverage(combined)).toBe(false); + expect(isCallerOnlyIncompleteCoverage(combined)).toBe(false); }); it("rejects complete coverage", () => { const combined = combineFunctionRelationshipCoverage(complete, complete); - expect(isCallerOnlyUnknownCoverage(combined)).toBe(false); + expect(isCallerOnlyIncompleteCoverage(combined)).toBe(false); + }); + + it("retains caller-only partial coverage without relying on limitation wording", () => { + const combined = combineFunctionRelationshipCoverage( + { status: "partial", limitations: ["Missing incoming references."] }, + complete, + ); + expect(combined).toMatchObject({ limited_directions: ["callers"] }); + expect(isCallerOnlyIncompleteCoverage(combined)).toBe(true); + }); + + it("uses explicit directions even when explanation text contains direction labels", () => { + expect( + isCallerOnlyIncompleteCoverage({ + status: "unknown", + reason: "Callers: unavailable. Callees: diagnostic text.", + limited_directions: ["callers"], + }), + ).toBe(true); + expect( + isCallerOnlyIncompleteCoverage({ + status: "unknown", + reason: "Callers: unavailable.", + limited_directions: ["callees"], + }), + ).toBe(false); }); }); diff --git a/src/domain/functionCallCoverage.ts b/src/domain/functionCallCoverage.ts index b64e78cd6..ce3798c4f 100644 --- a/src/domain/functionCallCoverage.ts +++ b/src/domain/functionCallCoverage.ts @@ -22,6 +22,16 @@ export const combineFunctionRelationshipCoverage = ( ), ); const details = diagnostics.length > 0 ? { diagnostics } : {}; + const callersLimited = callers?.status !== "complete"; + const calleesLimited = callees?.status !== "complete"; + const limited_directions: Extract< + RelationshipCoverage, + { status: "partial" } + >["limited_directions"] = callersLimited + ? calleesLimited + ? ["callers", "callees"] + : ["callers"] + : ["callees"]; const reasons = reads.flatMap(({ direction, coverage }) => { const label = direction === "callers" ? callerCoveragePrefix : calleeCoveragePrefix; @@ -43,30 +53,37 @@ export const combineFunctionRelationshipCoverage = ( return { status: "unknown", reason: uniqueSorted(reasons).join(" "), + limited_directions, ...details, }; if (reasons.length > 0) return { status: "partial", limitations: uniqueSorted(reasons), + limited_directions, ...details, }; return { status: "complete", ...details }; }; /** - * Whether combined relationship coverage is unknown only on the caller side. - * The combine helper above prefixes each direction's reasons, so a reason - * that carries the caller prefix and no callee prefix records observed - * callees with unobservable callers. Forward (callee-edge) searches stay - * exhaustive under that caveat; the caller reason remains a limitation. + * Forward searches depend on callee coverage. Preserve the historical + * unknown-reason encoding when reading observations without explicit directions. */ -export const isCallerOnlyUnknownCoverage = ( +export const isCallerOnlyIncompleteCoverage = ( coverage: RelationshipCoverage, -): boolean => - coverage.status === "unknown" && - coverage.reason.startsWith(callerCoveragePrefix) && - !coverage.reason.includes(calleeCoveragePrefix); +): boolean => { + if (coverage.status === "complete") return false; + if (coverage.limited_directions !== undefined) + return !coverage.limited_directions.some( + (direction) => direction === "callees", + ); + return ( + coverage.status === "unknown" && + coverage.reason.startsWith(callerCoveragePrefix) && + !coverage.reason.includes(calleeCoveragePrefix) + ); +}; /** Explain why two resolved call sets cannot establish call-set equality. */ export const functionCallCoverageLimitations = ( diff --git a/src/domain/relationshipCoverage.ts b/src/domain/relationshipCoverage.ts index 1de973669..4dd4e0c40 100644 --- a/src/domain/relationshipCoverage.ts +++ b/src/domain/relationshipCoverage.ts @@ -1,24 +1,35 @@ import { z } from "zod"; -const diagnostics = z.array(z.string().min(1)).min(1); -const completeCoverage = z.strictObject({ status: z.literal("complete") }); +const diagnostics = z.array(z.string().min(1)).min(1).exactOptional(); +const completeCoverage = z.strictObject({ + status: z.literal("complete"), + diagnostics, +}); +const limitedDirections = z.union([ + z.tuple([z.literal("callers")]).check(z.minLength(1), z.maxLength(1)), + z.tuple([z.literal("callees")]).check(z.minLength(1), z.maxLength(1)), + z + .tuple([z.literal("callers"), z.literal("callees")]) + .check(z.minLength(2), z.maxLength(2)), +]); const partialCoverage = z.strictObject({ status: z.literal("partial"), limitations: z.array(z.string().min(1)).min(1), + limited_directions: limitedDirections.exactOptional(), + diagnostics, }); const unknownCoverage = z.strictObject({ status: z.literal("unknown"), reason: z.string().min(1), + limited_directions: limitedDirections.exactOptional(), + diagnostics, }); /** Explicit coverage state for a provider's observed caller/callee set. */ -export const relationshipCoverageSchema = z.union([ +export const relationshipCoverageSchema = z.discriminatedUnion("status", [ completeCoverage, - completeCoverage.extend({ diagnostics }), partialCoverage, - partialCoverage.extend({ diagnostics }), unknownCoverage, - unknownCoverage.extend({ diagnostics }), ]); export type RelationshipCoverage = z.infer; diff --git a/src/ghidra/GhidraAnalysisProfile.ts b/src/ghidra/GhidraAnalysisProfile.ts index da39ce53c..cc1d5eefb 100644 --- a/src/ghidra/GhidraAnalysisProfile.ts +++ b/src/ghidra/GhidraAnalysisProfile.ts @@ -40,6 +40,8 @@ import { NATIVE_AOT_PROFILE_CONTRACT_REVISION, } from "../domain/native/nativeAotPe.js"; +const callRelationshipCoverage = "function-body-call-coverage-v5"; + /** * The processor language REA pins for this target, or undefined when Ghidra may * select from the header. The committed profile and the session readback both @@ -125,7 +127,7 @@ export const resolveGhidraAnalysisProfile = async ( load_image_observations: "source-mappings-entry-context-v2", function_body_evidence: "complete-inclusive-ranges-v1", function_references: "complete-body-and-entry-reference-manager-v2", - call_relationship_coverage: "resolved-call-reference-diagnostics-v1", + call_relationship_coverage: callRelationshipCoverage, function_dossier_coverage: "observed-facets-and-call-relationships-v1", string_inventory_evidence: "defined-data-coverage-v1", @@ -222,7 +224,7 @@ export const resolveGhidraAnalysisProfile = async ( load_image_observations: "source-mappings-entry-context-v2", function_body_evidence: "complete-inclusive-ranges-v1", function_references: "complete-body-and-entry-reference-manager-v2", - call_relationship_coverage: "resolved-call-reference-diagnostics-v1", + call_relationship_coverage: callRelationshipCoverage, function_dossier_coverage: "observed-facets-and-call-relationships-v1", string_inventory_evidence: "defined-data-coverage-v1", location_resolution: "explicit-address-exact-entry-symbol-first-v3", diff --git a/src/ghidra/GhidraFunctionValues.test.ts b/src/ghidra/GhidraFunctionValues.test.ts index e7e5d8e9d..6ec7ad34e 100644 --- a/src/ghidra/GhidraFunctionValues.test.ts +++ b/src/ghidra/GhidraFunctionValues.test.ts @@ -43,7 +43,120 @@ const parseFunctionValueFixture = ( return parsed.ok ? { ok: true as const, value: parsed.value.value } : parsed; }; +describe("Ghidra unresolved call locations", () => { + it("rejects a noncanonical unresolved call site rather than retaining unverifiable location evidence", () => { + expect( + parseGhidraFunctionResult("analyze_function", { + value: { + ...functionDossierSchema.parse(ghidraFunctionDossier()), + unresolved_calls: [ + { address: "not-an-address", reason: "No call destination." }, + ], + }, + limitations: [], + relationship_coverage: { + status: "partial", + limitations: ["An unresolved call remains."], + }, + }), + ).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } }); + }); +}); + describe("Ghidra function-analysis result values", () => { + it("retains unavailable pseudocode instead of treating its empty representation as observed source", () => { + const availability = { + pseudocode: { + available: false, + reason: "Ghidra does not decompile external functions.", + }, + comments: { available: true }, + }; + const parsed = parseGhidraFunctionResult("analyze_function", { + value: { + ...functionDossierSchema.parse(ghidraFunctionDossier()), + pseudocode: "", + facet_availability: availability, + }, + limitations: [], + }); + expect(parsed).toMatchObject({ + ok: true, + value: { value: { pseudocode: "", facet_availability: availability } }, + }); + }); + it.each([ + { status: "complete", diagnostics: ["Resolved static references only."] }, + { + status: "partial", + limitations: ["Only the first instruction range was examined."], + }, + { status: "unknown", reason: "Relationship inventory was unavailable." }, + { + status: "partial", + limitations: ["Missing callers."], + limited_directions: ["callers"], + }, + { + status: "unknown", + reason: "Missing callees.", + limited_directions: ["callees"], + }, + ])("preserves observed $status relationship coverage", (coverage) => { + const parsed = parseGhidraFunctionResult("analyze_function", { + value: ghidraFunctionDossier(), + limitations: [], + relationship_coverage: coverage, + }); + expect(parsed).toMatchObject({ + ok: true, + value: { relationshipCoverage: coverage }, + }); + }); + + it("preserves omitted relationship coverage for legacy observations", () => { + const parsed = parseGhidraFunctionResult("analyze_function", { + value: ghidraFunctionDossier(), + limitations: [], + }); + if (!parsed.ok) throw parsed.error; + expect(parsed.value).not.toHaveProperty("relationshipCoverage"); + }); +}); + +describe("Ghidra relationship metadata validation", () => { + it.each([ + { status: "partial", limitations: [] }, + { status: "unknown", reason: "" }, + { status: "complete", limitations: ["Truncated."] }, + { status: "partial", limitations: ["Truncated."], limited_directions: [] }, + { + status: "partial", + limitations: ["Truncated."], + limited_directions: ["callers", "callers"], + }, + { status: "unknown", reason: "Missing.", limited_directions: ["incoming"] }, + { status: "complete", limited_directions: ["callers"] }, + ])("rejects malformed relationship coverage %j", (coverage) => { + expect( + parseGhidraFunctionResult("analyze_function", { + value: ghidraFunctionDossier(), + limitations: [], + relationship_coverage: coverage, + }), + ).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } }); + }); + + it("rejects relationship metadata on unrelated function operations", () => { + expect( + parseGhidraFunctionResult("procedure_assembly", { + value: "ret", + limitations: [], + relationship_coverage: { status: "complete" }, + }), + ).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } }); + }); + it("preserves file-offset resolution in Evidence locations and rejects inexact offsets", () => { const selection = { file_offset: 0x210, diff --git a/src/ghidra/GhidraFunctionValues.ts b/src/ghidra/GhidraFunctionValues.ts index a6e62c93c..d038ac82e 100644 --- a/src/ghidra/GhidraFunctionValues.ts +++ b/src/ghidra/GhidraFunctionValues.ts @@ -27,6 +27,10 @@ import { import { nativeApiBoundarySchema } from "../domain/native/nativeApiBoundary.js"; import { nativeValueFlowSchema } from "../domain/native/nativeValueFlow.js"; import type { EvidenceLocation } from "../domain/evidence.js"; +import { + relationshipCoverageSchema, + type RelationshipCoverage, +} from "../domain/relationshipCoverage.js"; import { err, ok, type Result } from "../domain/result.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import { @@ -307,6 +311,7 @@ const ghidraFunctionDossier = functionDossierSchema ...value.comments.map(({ address }) => address), ...value.callers.map(({ address }) => address), ...value.callees.map(({ address }) => address), + ...(value.unresolved_calls ?? []).map(({ address }) => address), ...value.incoming_references.flatMap(referenceAddresses), ...value.outgoing_references.flatMap(referenceAddresses), ...value.referenced_strings.flatMap(({ address, source_address }) => [ @@ -419,6 +424,7 @@ const functionBoundaryObservationOperations: ReadonlySet["selection"]; @@ -450,13 +458,17 @@ export const parseGhidraFunctionResult = ( const envelope = functionObservationEnvelope.safeParse(value); if ( !envelope.success || + (operation !== "analyze_function" && + operation !== "procedure_callers" && + operation !== "procedure_callees" && + envelope.data.relationship_coverage !== undefined) || (operation !== "procedure_pseudo_code" && envelope.data.selection !== undefined) ) return err( new AnalysisOutputError( operation, - "Ghidra bridge omitted the function observation envelope", + "Ghidra bridge returned an invalid function observation envelope for this operation", envelope.success ? undefined : { cause: envelope.error }, ), ); @@ -469,6 +481,9 @@ export const parseGhidraFunctionResult = ( ? ok({ value: jsonValueSchema.parse(parsed.data), limitations: observation.limitations, + ...(observation.relationship_coverage === undefined + ? {} + : { relationshipCoverage: observation.relationship_coverage }), ...(observation.selection === undefined ? {} : { diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index c69c83bd9..018116b82 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -633,7 +633,7 @@ describe("Ghidra client projection", () => { expect(resolved.value.profile.parameters).toMatchObject({ language_id: "auto-from-header", compiler_spec_id: "auto-default", - call_relationship_coverage: "resolved-call-reference-diagnostics-v1", + call_relationship_coverage: "function-body-call-coverage-v5", function_dossier_coverage: "observed-facets-and-call-relationships-v1", }); @@ -870,7 +870,16 @@ describe("Ghidra relationship coverage", () => { Promise.resolve( ok( operation === "procedure_callees" - ? { value: ["0x2000"], limitations: [] } + ? { + value: ["0x2000"], + limitations: [], + relationship_coverage: { + status: "complete", + diagnostics: [ + "Only resolved Ghidra call references are returned; unresolved computed or indirect calls remain unknown, while function classifications distinguish thunks and externals.", + ], + }, + } : { value: [], limitations: [] }, ), ), diff --git a/src/ghidra/GhidraProviderCapabilities.ts b/src/ghidra/GhidraProviderCapabilities.ts index f4bff8d9c..909fbcea3 100644 --- a/src/ghidra/GhidraProviderCapabilities.ts +++ b/src/ghidra/GhidraProviderCapabilities.ts @@ -2,7 +2,6 @@ import type { CapabilityDescriptor, ProviderIdentity, } from "../application/AnalysisProvider.js"; -import type { RelationshipCoverage } from "../domain/relationshipCoverage.js"; import { hasWindowsNativeAuthority, windowsNativeAuthorityUnavailableReason, @@ -44,22 +43,6 @@ const stringInventoryLimitation = const searchLimitation = "Regex mode uses Java Pattern semantics. Matcher or compiler stack exhaustion returns a resource constraint without closing the session; literal mode avoids regex recursion and returns complete matching values."; -const resolvedCallReferenceLimitation = - "Only resolved Ghidra call references are returned; unresolved computed or indirect calls remain unknown, while function classifications distinguish thunks and externals."; - -/** Relationship-only caveats belong to each observed caller/callee result. */ -export const relationshipCoverageFor = ( - operation: string, -): RelationshipCoverage | undefined => - operation === "procedure_callers" || - operation === "procedure_callees" || - operation === "analyze_function" - ? { - status: "complete", - diagnostics: [resolvedCallReferenceLimitation], - } - : undefined; - /** Limitation text for one admitted operation, including the common base. */ export const limitationsFor = (operation: string): readonly string[] => { const common = [ diff --git a/src/ghidra/GhidraProviderClient.ts b/src/ghidra/GhidraProviderClient.ts index 9db1b0c5f..dd95849c8 100644 --- a/src/ghidra/GhidraProviderClient.ts +++ b/src/ghidra/GhidraProviderClient.ts @@ -34,6 +34,7 @@ import { } from "../domain/analysisErrorCore.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import type { EvidenceLocation } from "../domain/evidence.js"; +import type { RelationshipCoverage } from "../domain/relationshipCoverage.js"; import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -86,7 +87,6 @@ import { healthLimitations, windowsP0Limitations, limitationsFor, - relationshipCoverageFor, } from "./GhidraProviderCapabilities.js"; import type { GhidraSessionError } from "./GhidraSessionError.js"; import { @@ -733,8 +733,8 @@ export const createGhidraProviderClient = (input: { rawResult: JsonValue, observationLimitations: readonly string[] = [], locations: readonly EvidenceLocation[] = [], + relationshipCoverage?: RelationshipCoverage, ) => { - const relationshipCoverage = relationshipCoverageFor(operation); return createAnalysisExecution(normalized, committedProfile.provider, { rawResult, locations, @@ -838,12 +838,14 @@ export const createGhidraProviderClient = (input: { let normalized: JsonValue; let observationLimitations: readonly string[] = []; let observationLocations: readonly EvidenceLocation[] = []; + let relationshipCoverage: RelationshipCoverage | undefined; if (isGhidraFunctionOperation(operation)) { const result = parseGhidraFunctionResult(operation, called.value); if (!result.ok) return result; normalized = result.value.value; observationLimitations = result.value.limitations; observationLocations = result.value.locations ?? []; + relationshipCoverage = result.value.relationshipCoverage; } else { const result = parseGhidraInventoryResult(operation, called.value); if (!result.ok) return result; @@ -939,6 +941,7 @@ export const createGhidraProviderClient = (input: { called.value, observationLimitations, observationLocations, + relationshipCoverage, ), ); }, diff --git a/src/ghidra/GhidraSnapshotCache.test.ts b/src/ghidra/GhidraSnapshotCache.test.ts index 83d293aa2..fa7b35c22 100644 --- a/src/ghidra/GhidraSnapshotCache.test.ts +++ b/src/ghidra/GhidraSnapshotCache.test.ts @@ -11,6 +11,7 @@ import { silentLogger } from "../logger.js"; import { GhidraProvider } from "./GhidraProvider.js"; import { GhidraSessionError } from "./GhidraSessionError.js"; import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js"; +import type { RelationshipCoverage } from "../domain/relationshipCoverage.js"; const TARGET: BinaryTarget = { path: "/tmp/ghidra-cache-fixture", @@ -23,7 +24,7 @@ const TARGET: BinaryTarget = { // Exercise the real provider descriptors, profile, input/output projection and // session cache; only the installed Ghidra process is replaced at its seam. -const fixture = (version = "12.1.4") => { +const fixture = (version = "12.1.4", coverage?: RelationshipCoverage) => { const config = parseConfig({ GHIDRA_INSTALL_DIR: "/opt/ghidra" }); if (!config.ok) throw config.error; const calls: string[] = []; @@ -113,7 +114,13 @@ const fixture = (version = "12.1.4") => { return ok( operation === "procedure_pseudo_code" || operation === "analyze_function" - ? { value, limitations: [] } + ? { + value, + limitations: [], + ...(operation === "analyze_function" && coverage !== undefined + ? { relationship_coverage: coverage } + : {}), + } : value, ); }, @@ -133,42 +140,119 @@ const open = async (session: ReturnType["session"]) => { expect((await session.openResolvedTarget(preview.value)).ok).toBe(true); }; -describe("Ghidra snapshot cache", () => { - it("refuses snapshots whose profile predates typed incoming references", async () => { - const initial = fixture(); - await open(initial.session); - const snapshot = initial.session.exportAnalysisSnapshot(); - if (!snapshot.ok) throw snapshot.error; - await initial.session.close(); - const profile = snapshot.value.binding.analysis_profile; - expect(profile.parameters.instruction_references).toBe( - "exact-address-incoming-v1", - ); - const legacy = { - ...snapshot.value, - binding: { - ...snapshot.value.binding, - analysis_profile: createAnalysisProfile( - profile.provider, - Object.fromEntries( - Object.entries(profile.parameters).filter( - ([key]) => key !== "instruction_references", - ), - ), - ), - }, - }; - const replay = fixture(); - const imported = replay.session.importAnalysisSnapshot(legacy); - if (!imported.ok) throw imported.error; - expect(await replay.session.previewTarget(TARGET)).toMatchObject({ - ok: false, - error: { _tag: "EvidenceIntegrityError" }, - }); - expect(replay.calls).toEqual([]); - await replay.session.close(); - }); +describe("Ghidra relationship coverage replay", () => { + it.each([ + undefined, + { status: "complete", diagnostics: ["Resolved static references only."] }, + { status: "partial", limitations: ["Instruction coverage was truncated."] }, + { status: "unknown", reason: "Relationship inventory was unavailable." }, + { + status: "partial", + limitations: ["Missing callers."], + limited_directions: ["callers"], + }, + ] satisfies (RelationshipCoverage | undefined)[])( + "preserves relationship coverage %j through live execution, cache and snapshot replay", + async (coverage) => { + const initial = fixture("12.1.4", coverage); + await open(initial.session); + const parameters = { procedure: "0x1000" }; + for (let i = 0; i < 2; i++) { + const execution = await initial.session.execute( + "analyze_function", + parameters, + ); + if (!execution.ok) throw execution.error; + expect(execution.value.relationshipCoverage).toEqual(coverage); + } + expect(initial.calls).toEqual(["analyze_function"]); + const snapshot = initial.session.exportAnalysisSnapshot(); + if (!snapshot.ok) throw snapshot.error; + await initial.session.close(); + const replay = fixture(); + expect(replay.session.importAnalysisSnapshot(snapshot.value).ok).toBe( + true, + ); + await open(replay.session); + const execution = await replay.session.execute( + "analyze_function", + parameters, + ); + if (!execution.ok) throw execution.error; + expect(execution.value.relationshipCoverage ?? undefined).toEqual( + coverage, + ); + expect(replay.calls).toEqual([]); + await replay.session.close(); + }, + ); +}); +describe("Ghidra snapshot profile admission", () => { + it.each([ + { + parameter: "instruction_references", + current: "exact-address-incoming-v1", + legacy: undefined, + }, + { + parameter: "call_relationship_coverage", + current: "function-body-call-coverage-v5", + legacy: "resolved-call-reference-diagnostics-v1", + }, + { + parameter: "call_relationship_coverage", + current: "function-body-call-coverage-v5", + legacy: "decoded-call-target-coverage-v2", + }, + { + parameter: "call_relationship_coverage", + current: "function-body-call-coverage-v5", + legacy: "decoded-call-target-coverage-v3", + }, + { + parameter: "call_relationship_coverage", + current: "function-body-call-coverage-v5", + legacy: "function-body-call-coverage-v4", + }, + ])( + "refuses snapshots with outdated $parameter semantics", + async ({ parameter, current, legacy: prior }) => { + const initial = fixture(); + await open(initial.session); + const snapshot = initial.session.exportAnalysisSnapshot(); + if (!snapshot.ok) throw snapshot.error; + await initial.session.close(); + const profile = snapshot.value.binding.analysis_profile; + expect(profile.parameters[parameter]).toBe(current); + const legacy = { + ...snapshot.value, + binding: { + ...snapshot.value.binding, + analysis_profile: createAnalysisProfile(profile.provider, { + ...Object.fromEntries( + Object.entries(profile.parameters).filter( + ([key]) => key !== parameter, + ), + ), + ...(prior === undefined ? {} : { [parameter]: prior }), + }), + }, + }; + const replay = fixture(); + const imported = replay.session.importAnalysisSnapshot(legacy); + if (!imported.ok) throw imported.error; + expect(await replay.session.previewTarget(TARGET)).toMatchObject({ + ok: false, + error: { _tag: "EvidenceIntegrityError" }, + }); + expect(replay.calls).toEqual([]); + await replay.session.close(); + }, + ); +}); + +describe("Ghidra snapshot cache", () => { it.each([ { operation: "analyze_function", parameters: { procedure: "0x1000" } }, { diff --git a/tests/boundary/mcp/functionCallDirectionsMcp.test.ts b/tests/boundary/mcp/functionCallDirectionsMcp.test.ts new file mode 100644 index 000000000..b4034d036 --- /dev/null +++ b/tests/boundary/mcp/functionCallDirectionsMcp.test.ts @@ -0,0 +1,138 @@ +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { Ajv2020 } from "ajv/dist/2020.js"; +import { expect, it } from "vitest"; + +import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js"; +import { createEvidence } from "../../../src/domain/evidence.js"; +import { functionDossierSchema } from "../../../src/domain/hopperValues.js"; +import type { RelationshipCoverage } from "../../../src/domain/relationshipCoverage.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; + +const observe = (relationshipCoverage: RelationshipCoverage) => { + const template = FUNCTION_COMPARISON_EXAMPLE.left; + if (template.subject === null) + throw new Error("Expected artifact-bound fixture"); + const dossier = functionDossierSchema.parse(template.normalized_result); + return createEvidence( + { + path: template.subject.local_path, + sha256: template.subject.digest.sha256, + format: template.subject.format, + }, + template.provider, + { + operation: "analyze_function", + parameters: template.parameters, + result: { ...dossier, callees: [], unresolved_calls: [] }, + confidence: template.confidence, + authority: template.authority, + relationshipCoverage, + }, + ); +}; + +it("preserves directional gaps through advertised schemas and public path reconstruction", async () => { + const session = createTestBinarySession(() => { + throw new Error("Offline call paths must not launch a provider"); + }); + const server = createServer({ kind: "session", session }); + const client = new Client({ name: "function-call-directions", version: "1" }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + try { + await server.connect(serverTransport); + await client.connect(clientTransport); + const advertised = (await client.listTools()).tools.find( + ({ name }) => name === "build_call_path", + ); + if (advertised === undefined) + throw new Error("Missing build_call_path contract"); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + expect(ajv.validateSchema(advertised.inputSchema)).toBe(true); + const validate = ajv.compile(advertised.inputSchema); + for (const { directions, status, exhaustive } of [ + { + directions: ["callers"] as ["callers"], + status: "not_found", + exhaustive: true, + }, + { + directions: ["callees"] as ["callees"], + status: "unknown", + exhaustive: false, + }, + { + directions: ["callers", "callees"] as ["callers", "callees"], + status: "unknown", + exhaustive: false, + }, + ]) { + const limitation = + "An observed call reference is absent from the inventory."; + const coverage: RelationshipCoverage = { + status: "partial", + limitations: [limitation], + limited_directions: directions, + }; + const observation = observe(coverage); + expect(session.recordEvidence(observation).ok).toBe(true); + const input = { + functions: [observation], + start: { address: "0x1000" }, + goal: { address: "0x9999" }, + }; + expect(validate(input), JSON.stringify(validate.errors)).toBe(true); + for (const limited_directions of [ + [], + ["callers", "callers"], + ["callees", "callees"], + ["callers", "callees", "callers"], + ["incoming"], + ]) + expect( + validate({ + ...input, + functions: [ + { + ...observation, + relationship_coverage: { + ...coverage, + limited_directions, + }, + }, + ], + }), + ).toBe(false); + const result = await client.callTool({ + name: "build_call_path", + arguments: input, + }); + if (result.isError) throw new Error(JSON.stringify(result)); + expect(result.structuredContent).toMatchObject({ + normalized_result: { + status, + search_scope: { exhaustive }, + limitations: expect.arrayContaining([limitation]), + }, + }); + const comparison = await client.callTool({ + name: "compare_functions", + arguments: { left: observation, right: observation }, + }); + if (comparison.isError) throw new Error(JSON.stringify(comparison)); + expect(comparison.structuredContent).toMatchObject({ + normalized_result: { + dimensions: expect.arrayContaining([ + expect.objectContaining({ dimension: "calls", status: "unknown" }), + ]), + }, + }); + // Each scenario owns its Evidence and residual-unknown ledger. + const closed = await session.close(); + if (!closed.ok) throw closed.error; + } + } finally { + await Promise.allSettled([session.close(), client.close(), server.close()]); + } +}); diff --git a/tests/boundary/mcp/ghidraEvidenceMcp.test.ts b/tests/boundary/mcp/ghidraEvidenceMcp.test.ts index e786fc3cc..e0ceeeda3 100644 --- a/tests/boundary/mcp/ghidraEvidenceMcp.test.ts +++ b/tests/boundary/mcp/ghidraEvidenceMcp.test.ts @@ -15,9 +15,17 @@ import { type GhidraFunctionOperation, } from "../../../src/ghidra/GhidraFunctionValues.js"; -it.each([true, false])( - "compares observed empty Ghidra facets while preserving pseudocode availability (%s)", - async (pseudocodeAvailable) => { +it.each([ + { pseudocodeAvailable: true, reportsCoverage: true }, + { pseudocodeAvailable: false, reportsCoverage: true }, + { pseudocodeAvailable: true, reportsCoverage: false }, + { pseudocodeAvailable: false, reportsCoverage: false }, +])( + "compares observed empty Ghidra facets with pseudocode=$pseudocodeAvailable and coverage=$reportsCoverage", + async ({ pseudocodeAvailable, reportsCoverage }) => { + const coverage = reportsCoverage + ? { status: "complete" as const } + : undefined; const dossier = functionDossierSchema.parse(ghidraFunctionDossier()); Object.assign(dossier, { comments: [], @@ -47,7 +55,13 @@ it.each([true, false])( if (operation !== "analyze_function") throw new Error(`Unexpected operation: ${operation}`); return Promise.resolve( - ok({ value: jsonValueSchema.parse(dossier), limitations: [] }), + ok({ + value: jsonValueSchema.parse(dossier), + limitations: [], + ...(coverage === undefined + ? {} + : { relationship_coverage: coverage }), + }), ); }, ); @@ -61,9 +75,7 @@ it.each([true, false])( harness.session, analyzed.structuredContent, ); - expect(evidence.relationship_coverage).toMatchObject({ - status: "complete", - }); + expect(evidence.relationship_coverage).toEqual(coverage ?? null); expect(evidence.normalized_result).toEqual(dossier); const reply = await harness.mcp.callTool({ name: "compare_functions", @@ -86,7 +98,7 @@ it.each([true, false])( pseudocode: pseudocodeAvailable ? "unchanged" : "unknown", assembly: "unchanged", comments: "unchanged", - calls: "unchanged", + calls: reportsCoverage ? "unchanged" : "unknown", references: "unchanged", strings_names: "unchanged", cfg: "unchanged", @@ -96,9 +108,7 @@ it.each([true, false])( evidence.parameters, ); if (!replay.ok) throw replay.error; - expect(replay.value.relationshipCoverage).toEqual( - evidence.relationship_coverage, - ); + expect(replay.value.relationshipCoverage).toEqual(coverage); expect(harness.calls).toEqual(["analyze_function"]); } finally { await harness.close(); diff --git a/tests/conformance/ghidra/ReaNoReturnProbe.java b/tests/conformance/ghidra/ReaNoReturnProbe.java index b13c2b5e9..19f98f346 100644 --- a/tests/conformance/ghidra/ReaNoReturnProbe.java +++ b/tests/conformance/ghidra/ReaNoReturnProbe.java @@ -12,6 +12,8 @@ import ghidra.program.model.listing.FlowOverride; import ghidra.program.model.listing.Function; import ghidra.program.model.listing.Instruction; import ghidra.program.model.symbol.SourceType; +import ghidra.program.model.symbol.Reference; +import ghidra.program.model.symbol.RefType; import java.io.File; import java.lang.reflect.Method; import java.nio.file.Files; @@ -20,9 +22,12 @@ import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.ArrayList; /** Injects reported analysis flags into imported ELF/Mach-O functions; never executes target code. */ public class ReaNoReturnProbe extends GhidraScript { + private record MemoryCallReference(Address source, Address target, RefType type, + SourceType sourceType, int operandIndex, boolean primary) {} private final JsonArray checks = new JsonArray(); private final Map originalEnds = new LinkedHashMap<>(); private final Map originalSignatures = new LinkedHashMap<>(); @@ -85,6 +90,114 @@ public class ReaNoReturnProbe extends GhidraScript { return instance; } + private void knownInteriorCall(GhidraScript bridge) throws Exception { + Function caller = function("rea_tls_chain"); + Function target = function("rea_tls"); + Address interior = target.getEntryPoint().add(1); + require("interior_target_is_owned", currentProgram.getFunctionManager().getFunctionAt(interior) == null && + target.equals(currentProgram.getFunctionManager().getFunctionContaining(interior))); + Instruction call = null; + for (Instruction instruction : currentProgram.getListing().getInstructions(caller.getBody(), true)) { + if (instruction.getFlowType().isCall()) { call = instruction; break; } + } + if (call == null) throw new IllegalStateException("Missing real call instruction"); + var references = currentProgram.getReferenceManager(); + List originals = new ArrayList<>(); + List saved = new ArrayList<>(); + for (Reference reference : call.getReferencesFrom()) { + if (!reference.getReferenceType().isCall()) continue; + originals.add(reference); + saved.add(new MemoryCallReference(reference.getFromAddress(), reference.getToAddress(), + reference.getReferenceType(), reference.getSource(), reference.getOperandIndex(), reference.isPrimary())); + } + require("original_call_reference_present", !originals.isEmpty()); + Reference changed = null; + try { + for (Reference reference : originals) references.delete(reference); + changed = references.addMemoryReference(call.getAddress(), interior, + RefType.UNCONDITIONAL_CALL, SourceType.USER_DEFINED, 0); + require("interior_target_omitted_by_callee_getter", !caller.getCalledFunctions(monitor).contains(target)); + JsonObject query = new JsonObject(); + query.addProperty("document", currentProgram.getName()); + query.addProperty("procedure", caller.getName()); + query.addProperty("direction", "outgoing"); + Method read = bridge.getClass().getDeclaredMethod("procedureReferences", JsonObject.class); + read.setAccessible(true); + JsonObject output = (JsonObject) read.invoke(bridge, query); + require("interior_reference_keeps_known_procedure", output.getAsJsonArray("references").asList().stream().anyMatch( + edge -> !edge.getAsJsonObject().get("target_procedure").isJsonNull() && + edge.getAsJsonObject().getAsJsonObject("target_procedure").get("name").getAsString().equals(target.getName()))); + require("known_reference_is_not_also_unresolved", output.getAsJsonArray("unresolved_calls").isEmpty()); + query.remove("direction"); + Method callees = bridge.getClass().getDeclaredMethod("procedureCalls", JsonObject.class, boolean.class); + callees.setAccessible(true); + JsonObject inventory = (JsonObject) callees.invoke(bridge, query, false); + require("omitted_callee_inventory_stays_partial", inventory.getAsJsonObject("relationship_coverage").get("status").getAsString().equals("partial")); + require("omitted_callee_direction_is_explicit", + inventory.getAsJsonObject("relationship_coverage").getAsJsonArray("limited_directions").toString().equals("[\"callees\"]")); + require("interior_caller_omitted_by_entry_getter", !target.getCallingFunctions(monitor).contains(caller)); + query.addProperty("procedure", target.getName()); + JsonObject incoming = (JsonObject) callees.invoke(bridge, query, true); + require("off_entry_caller_inventory_stays_partial", + incoming.getAsJsonObject("relationship_coverage").get("status").getAsString().equals("partial")); + require("off_entry_caller_direction_is_explicit", + incoming.getAsJsonObject("relationship_coverage").getAsJsonArray("limited_directions").toString().equals("[\"callers\"]")); + JsonObject dossierQuery = new JsonObject(); + dossierQuery.addProperty("procedure", target.getName()); + Method analyze = bridge.getClass().getDeclaredMethod("analyzeFunctionObservation", JsonObject.class); + analyze.setAccessible(true); + Object observation = analyze.invoke(bridge, dossierQuery); + Method coverage = observation.getClass().getDeclaredMethod("relationshipCoverage"); + coverage.setAccessible(true); + require("dossier_preserves_caller_only_gap", + ((JsonObject) coverage.invoke(observation)).getAsJsonArray("limited_directions").toString().equals("[\"callers\"]")); + } finally { + if (changed != null) references.delete(changed); + for (MemoryCallReference reference : saved) { + Reference restored = references.addMemoryReference(reference.source(), reference.target(), + reference.type(), reference.sourceType(), reference.operandIndex()); + references.setPrimary(restored, reference.primary()); + } + } + } + + private void nonCallInstructionReference(GhidraScript bridge) throws Exception { + Function caller = function("rea_tls_chain"); + Function target = function("rea_memcpy"); + Instruction source = null; + for (Instruction instruction : currentProgram.getListing().getInstructions(caller.getBody(), true)) { + if (!instruction.getFlowType().isCall()) { source = instruction; break; } + } + if (source == null) throw new IllegalStateException("Missing non-call instruction"); + var references = currentProgram.getReferenceManager(); + Reference added = references.addMemoryReference(source.getAddress(), target.getEntryPoint().add(1), + RefType.UNCONDITIONAL_CALL, SourceType.USER_DEFINED, -1); + try { + require("non_call_reference_target_omitted", !caller.getCalledFunctions(monitor).contains(target)); + JsonObject query = new JsonObject(); + query.addProperty("document", currentProgram.getName()); + query.addProperty("procedure", caller.getName()); + Method read = bridge.getClass().getDeclaredMethod("procedureCalls", JsonObject.class, boolean.class); + read.setAccessible(true); + JsonObject output = (JsonObject) read.invoke(bridge, query, false); + require("non_call_instruction_reference_stays_partial", + output.getAsJsonObject("relationship_coverage").get("status").getAsString().equals("partial")); + query.addProperty("direction", "outgoing"); + Method edges = bridge.getClass().getDeclaredMethod("procedureReferences", JsonObject.class); + edges.setAccessible(true); + JsonObject known = (JsonObject) edges.invoke(bridge, query); + require("non_call_known_reference_is_not_unresolved", known.getAsJsonArray("unresolved_calls").isEmpty()); + references.delete(added); + Address unknown = currentProgram.getMemory().getMaxAddress().add(0x1000); + added = references.addMemoryReference(source.getAddress(), unknown, + RefType.UNCONDITIONAL_CALL, SourceType.USER_DEFINED, -1); + JsonObject unresolved = (JsonObject) edges.invoke(bridge, query); + require("non_call_unknown_reference_keeps_site", unresolved.getAsJsonArray("unresolved_calls").size() == 1); + } finally { + references.delete(added); + } + } + @Override public void run() throws Exception { String[] args = getScriptArgs(); @@ -164,6 +277,8 @@ public class ReaNoReturnProbe extends GhidraScript { Object output = pseudocode.invoke(bridge, query); require("recovered_pseudocode", output instanceof JsonObject value && value.get("value").getAsString().contains("rea_after_call")); + nonCallInstructionReference(bridge); + knownInteriorCall(bridge); } finally { ((ghidra.app.decompiler.DecompInterface) field.get(bridge)).dispose(); } From bbf0638e884d29cac21cb1f51fa0d41dce36d3a1 Mon Sep 17 00:00:00 2001 From: xpeng5278-web Date: Wed, 14 Oct 2026 08:10:04 +0800 Subject: [PATCH 2/9] fix(javascript): report EventSource and sendBeacon URLs as network endpoints (#3044) Co-authored-by: xpeng5278-web <330743750+xpeng5278-web@users.noreply.github.com> --- ...ascriptStaticAnalysis.event_source.test.ts | 40 +++++++++++++++++++ ...vascriptStaticAnalysis.send_beacon.test.ts | 34 ++++++++++++++++ .../javascriptStaticAnalysisHelpers.ts | 11 ++++- 3 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 src/domain/javascript/javascriptStaticAnalysis.event_source.test.ts create mode 100644 src/domain/javascript/javascriptStaticAnalysis.send_beacon.test.ts diff --git a/src/domain/javascript/javascriptStaticAnalysis.event_source.test.ts b/src/domain/javascript/javascriptStaticAnalysis.event_source.test.ts new file mode 100644 index 000000000..0fa5d6543 --- /dev/null +++ b/src/domain/javascript/javascriptStaticAnalysis.event_source.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; + +import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js"; + +const endpoints = (source: string) => + analyzeJavaScriptStaticSource(source).endpoints.map( + ({ kind, value, mechanism }) => ({ kind, value, mechanism }), + ); + +describe("server-sent event endpoints", () => { + it("reports EventSource URLs like WebSocket URLs", () => { + expect( + endpoints(` + new WebSocket("wss://chat.example/ws"); + new EventSource("/api/chat/stream"); + new window.EventSource("https://chat.example/events", { withCredentials: true }); + `), + ).toEqual([ + { + kind: "network", + value: "wss://chat.example/ws", + mechanism: "call:WebSocket", + }, + { + kind: "network", + value: "/api/chat/stream", + mechanism: "call:EventSource", + }, + { + kind: "network", + value: "https://chat.example/events", + mechanism: "call:window.EventSource", + }, + ]); + }); + + it("keeps a dynamic EventSource URL unreported", () => { + expect(endpoints("new EventSource(url);")).toEqual([]); + }); +}); diff --git a/src/domain/javascript/javascriptStaticAnalysis.send_beacon.test.ts b/src/domain/javascript/javascriptStaticAnalysis.send_beacon.test.ts new file mode 100644 index 000000000..fd26b88b5 --- /dev/null +++ b/src/domain/javascript/javascriptStaticAnalysis.send_beacon.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; + +import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js"; + +const endpoints = (source: string) => + analyzeJavaScriptStaticSource(source).endpoints.map( + ({ kind, value, mechanism }) => ({ kind, value, mechanism }), + ); + +describe("beacon endpoints", () => { + it("reports navigator.sendBeacon URLs", () => { + expect( + endpoints(` + navigator.sendBeacon("/api/telemetry", payload); + window.navigator.sendBeacon("https://metrics.example/collect"); + `), + ).toEqual([ + { + kind: "network", + value: "/api/telemetry", + mechanism: "call:navigator.sendBeacon", + }, + { + kind: "network", + value: "https://metrics.example/collect", + mechanism: "call:window.navigator.sendBeacon", + }, + ]); + }); + + it("keeps a dynamic beacon URL unreported", () => { + expect(endpoints("navigator.sendBeacon(url, payload);")).toEqual([]); + }); +}); diff --git a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts index e2cc73f20..14827e1c2 100644 --- a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts +++ b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts @@ -554,7 +554,13 @@ export const endpointArgument = ( receiverFact?: JavaScriptOpenReceiverFact, ): string | undefined => { if (receiverFact === "window") return undefined; - if (name === "fetch" || name.endsWith(".fetch") || name === "WebSocket") + if ( + name === "fetch" || + name.endsWith(".fetch") || + name === "WebSocket" || + name === "EventSource" || + name.endsWith(".EventSource") + ) return stringValue(args[0]); if (name.endsWith(".open")) return xhrOpenUrl(name, args[0], args[1], receiverFact); @@ -574,6 +580,9 @@ export const endpointArgument = ( ? undefined : value; } + // navigator.sendBeacon(url, data) queues a POST to its first argument. + if (name === "sendBeacon" || name.endsWith(".sendBeacon")) + return stringValue(args[0]); if (name.endsWith("loadURL")) return stringValue(args[0]); return undefined; }; From e049ef70f71aeb9965e9d75d4d4a84ea02eaee11 Mon Sep 17 00:00:00 2001 From: Xiangfang Chen <565499699@qq.com> Date: Wed, 14 Oct 2026 08:12:33 +0800 Subject: [PATCH 3/9] feat(setup): add WorkBuddy client support (#3041) * feat(setup): add WorkBuddy client support Register rea in the global ~/.workbuddy/mcp.json through a new workbuddy entry in SUPPORTED_CLIENT_DEFINITIONS (json dialect, ~/.workbuddy marker, ~/.workbuddy/skills skill directory; WorkBuddy AI shares the file). Document the client, extend the unreleased-client note, and cover registration and uninstall with boundary tests. * docs(setup): record verified WorkBuddy tool calls Real-client verification completed: WorkBuddy loads the registration and real REA tool calls execute through the registered server. --- docs/client-configuration.md | 15 ++ docs/installation.md | 5 +- src/application/SupportedClients.ts | 8 + .../filesystem/clientLifecycle.test.ts | 1 + .../workbuddyClientConfiguration.test.ts | 159 ++++++++++++++++++ 5 files changed, 186 insertions(+), 2 deletions(-) create mode 100644 tests/boundary/filesystem/workbuddyClientConfiguration.test.ts diff --git a/docs/client-configuration.md b/docs/client-configuration.md index 409bc7f19..d03984ec8 100644 --- a/docs/client-configuration.md +++ b/docs/client-configuration.md @@ -265,6 +265,21 @@ The user-level MCP paths follow the editor's VS Code layout. Trae's official documentation describes the raw JSON editor without specifying those paths; loading this registration in Trae remains unverified. +## WorkBuddy + +For [WorkBuddy](https://www.workbuddy.cn/docs/workbuddy/From-Beginner-to-Expert-Guide/Function-Description/MCP-Guide), setup writes `mcpServers.rea` into the +global `~/.workbuddy/mcp.json` (a standard `mcpServers` JSON file at the user +home root on every platform). Entries carry `command`, `args`, and `env`; +stdio is the default transport. WorkBuddy discovers personal skills from +`~/.workbuddy/skills` (`%userprofile%\.workbuddy\skills` on Windows), so +setup installs its skill copy there. + +The global MCP path is a plain JSON file; setup preserves every other server +and top-level key when it upserts `rea`. WorkBuddy also reads a project-level +`/.workbuddy/mcp.json`, which setup does not touch: it registers the +user-level file only. Loading this registration and real REA tool calls +through WorkBuddy are verified. + ## ZCode For [ZCode](https://zcode.z.ai/en/docs/mcp-services), setup registers `rea` in the nested `mcp.servers` table of the diff --git a/docs/installation.md b/docs/installation.md index 39584b51d..38c4d7966 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -288,11 +288,12 @@ hosted connector; see [its configuration](client-configuration.md#other-client-s | Qoder | `qoder` | | Factory Droid | `droid` | | Trae | `trae` | +| WorkBuddy | `workbuddy` | | ZCode | `zcode` | | DeepSeek Harness | `dsh` | -`dsh` and `kimi` require a release containing them. The registry check above does -not cover them. +`dsh`, `kimi`, and `workbuddy` require a release containing them. The registry +check above does not cover them. See [client configuration and troubleshooting](client-configuration.md) for configuration paths, profiles, trust policies, and schema-limit workarounds. diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts index 55a651a52..20ab3ed29 100644 --- a/src/application/SupportedClients.ts +++ b/src/application/SupportedClients.ts @@ -606,6 +606,14 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [ markerPath: traeUserDirectory, format: "json", }, + { + name: "workbuddy", + displayName: "WorkBuddy", + skillPath: [".workbuddy", "skills"], + configPath: [".workbuddy", "mcp.json"], + markerPath: [".workbuddy"], + format: "json", + }, { name: "grok_build", displayName: "Grok Build", diff --git a/tests/boundary/filesystem/clientLifecycle.test.ts b/tests/boundary/filesystem/clientLifecycle.test.ts index 0e4054ae6..877ae92e8 100644 --- a/tests/boundary/filesystem/clientLifecycle.test.ts +++ b/tests/boundary/filesystem/clientLifecycle.test.ts @@ -67,6 +67,7 @@ describe("client configuration filesystem lifecycle", () => { "kimi", "vscode", "trae", + "workbuddy", "grok_build", "omp", "pi", diff --git a/tests/boundary/filesystem/workbuddyClientConfiguration.test.ts b/tests/boundary/filesystem/workbuddyClientConfiguration.test.ts new file mode 100644 index 000000000..b6aac6577 --- /dev/null +++ b/tests/boundary/filesystem/workbuddyClientConfiguration.test.ts @@ -0,0 +1,159 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; +import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; +import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js"; +import { skillDestinations } from "../../../src/application/SetupSkill.js"; +import { supportedClients } from "../../../src/application/SupportedClients.js"; +import { systemUninstallHost } from "../../../src/application/Uninstall.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js"; + +/** + * The registration command setup writes on the host running the tests. Windows + * wraps it in `cmd.exe /d /c`, so the expected entry follows the host too. + */ +const command = npxRegistrationCommand(process.platform); + +beforeEach(clearClientLocationEnvironment); +afterEach(() => vi.unstubAllEnvs()); + +const workbuddyPath = ( + home: string, + platform: NodeJS.Platform = process.platform, + env: Parameters[2] = {}, +) => + supportedClients(home, platform, env).find( + ({ name }) => name === "workbuddy", + ); + +describe("WorkBuddy configuration paths", () => { + it("resolves the global mcp.json under the home root", () => { + expect(workbuddyPath("/home/a")?.configPath).toBe( + join("/home/a", ".workbuddy", "mcp.json"), + ); + expect(workbuddyPath("/Users/a")?.markerPath).toBe( + join("/Users/a", ".workbuddy"), + ); + expect(workbuddyPath("C:\\Users\\a", "win32")?.configPath).toBe( + join("C:\\Users\\a", ".workbuddy", "mcp.json"), + ); + }); + + it("resolves the registration format as the plain mcpServers JSON dialect", () => { + expect(workbuddyPath("/home/a")?.format).toBe("json"); + }); + + it("resolves the personal skills directory under the home root", () => { + expect( + skillDestinations("/home/a", ["workbuddy"]).map(({ path }) => path), + ).toEqual([ + join("/home/a", ".workbuddy", "skills", "reverse-engineer-anything"), + ]); + expect( + skillDestinations("C:\\Users\\a", ["workbuddy"], {}, "win32").map( + ({ path }) => path, + ), + ).toEqual([ + join("C:\\Users\\a", ".workbuddy", "skills", "reverse-engineer-anything"), + ]); + }); +}); + +describe("WorkBuddy JSON registration", () => { + const workbuddyClient = async () => { + const home = await createTestTempDirectory("rea-workbuddy-"); + const client = workbuddyPath(home, process.platform); + if (client?.markerPath === undefined) + throw new Error("missing WorkBuddy client"); + await mkdir(client.markerPath, { recursive: true }); + return { home, client }; + }; + + it("upserts rea into mcpServers while preserving unrelated settings", async () => { + const { home, client } = await workbuddyClient(); + await writeFile( + client.configPath, + `{ + "mcpServers": { + "other": { "command": "other-server" } + } +}`, + ); + + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("configured"); + const parsed = JSON.parse(await readFile(client.configPath, "utf8")); + expect(parsed.mcpServers.other).toEqual({ command: "other-server" }); + expect(parsed.mcpServers.rea).toEqual({ + command: command[0], + args: command.slice(1), + }); + + expect(await configureClientConfiguration(client, {}, command)).toEqual({ + status: "unchanged", + }); + expect( + ( + await readClientRegistrationStatuses(home, undefined, { + platform: process.platform, + environment: {}, + }) + ).find(({ client }) => client === "workbuddy"), + ).toMatchObject({ state: "aligned", command }); + }); + + it("creates the mcpServers table in an existing mcp.json without servers", async () => { + const { client } = await workbuddyClient(); + await writeFile( + client.configPath, + JSON.stringify({ unrelated: { setting: true } }, null, 2), + ); + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("configured"); + const parsed = JSON.parse(await readFile(client.configPath, "utf8")); + expect(parsed.unrelated).toEqual({ setting: true }); + expect(parsed.mcpServers.rea).toEqual({ + command: command[0], + args: command.slice(1), + }); + }); + + it("registers into an empty mcp.json", async () => { + const { client } = await workbuddyClient(); + await writeFile(client.configPath, ""); + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("configured"); + const parsed = JSON.parse(await readFile(client.configPath, "utf8")); + expect(parsed.mcpServers.rea).toEqual({ + command: command[0], + args: command.slice(1), + }); + }); + + it("removes only the rea entry on uninstall", async () => { + const { home, client } = await workbuddyClient(); + await writeFile( + client.configPath, + JSON.stringify( + { mcpServers: { other: { command: "other-server" } } }, + null, + 2, + ), + ); + await configureClientConfiguration(client, {}, command); + + expect((await systemUninstallHost(home).removeClient(client)).status).toBe( + "removed", + ); + const parsed = JSON.parse(await readFile(client.configPath, "utf8")); + expect(parsed.mcpServers.other).toEqual({ command: "other-server" }); + expect(parsed.mcpServers.rea).toBeUndefined(); + }); +}); From 30128a03cff3289479f78df09b3aacf62382d4c2 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:22:07 +0800 Subject: [PATCH 4/9] refactor(domain): centralize relationship coverage interpretation --- src/domain/callPath.ts | 14 ++++------ src/domain/functionCallCoverage.ts | 44 ++++++++---------------------- src/domain/relationshipCoverage.ts | 16 +++++++++++ 3 files changed, 34 insertions(+), 40 deletions(-) diff --git a/src/domain/callPath.ts b/src/domain/callPath.ts index 65524fbc2..3b8bd1cfe 100644 --- a/src/domain/callPath.ts +++ b/src/domain/callPath.ts @@ -1,3 +1,4 @@ +import { relationshipCoverageLimitations } from "./relationshipCoverage.js"; import { callPathInputSchema, callPathResultSchema, @@ -240,15 +241,12 @@ const inspectSearch = ({ const coverage = snapshot.evidence.relationship_coverage; for (const limitation of snapshot.limitations) limitations.push(limitation); - if (coverage?.status === "partial") - for (const limitation of coverage.limitations) + if (coverage !== null) { + for (const limitation of relationshipCoverageLimitations(coverage)) limitations.push(limitation); - else if (coverage?.status === "unknown") - limitations.push(coverage.reason); - for (const diagnostic of coverage !== null && "diagnostics" in coverage - ? coverage.diagnostics - : []) - limitations.push(diagnostic); + for (const diagnostic of coverage.diagnostics ?? []) + limitations.push(diagnostic); + } // The requested goal is a terminal for this search. Its outgoing edges // cannot add a path to the goal, so its dossier limits are contextual // but do not make the searched start-to-goal closure incomplete. diff --git a/src/domain/functionCallCoverage.ts b/src/domain/functionCallCoverage.ts index ce3798c4f..06fc06fe5 100644 --- a/src/domain/functionCallCoverage.ts +++ b/src/domain/functionCallCoverage.ts @@ -1,4 +1,7 @@ -import type { RelationshipCoverage } from "./relationshipCoverage.js"; +import { + relationshipCoverageLimitations, + type RelationshipCoverage, +} from "./relationshipCoverage.js"; import type { FunctionDossier } from "./hopperValues.js"; import { uniqueSorted } from "./canonicalOrdering.js"; @@ -15,11 +18,7 @@ export const combineFunctionRelationshipCoverage = ( { direction: "callees" as const, coverage: callees }, ]; const diagnostics = uniqueSorted( - reads.flatMap(({ coverage }) => - coverage !== undefined && "diagnostics" in coverage - ? coverage.diagnostics - : [], - ), + reads.flatMap(({ coverage }) => coverage?.diagnostics ?? []), ); const details = diagnostics.length > 0 ? { diagnostics } : {}; const callersLimited = callers?.status !== "complete"; @@ -35,15 +34,9 @@ export const combineFunctionRelationshipCoverage = ( const reasons = reads.flatMap(({ direction, coverage }) => { const label = direction === "callers" ? callerCoveragePrefix : calleeCoveragePrefix; - const limitations = - coverage === undefined - ? ["Provider did not report relationship coverage."] - : coverage.status === "unknown" - ? [coverage.reason] - : coverage.status === "partial" - ? coverage.limitations - : []; - return limitations.map((reason) => `${label}${reason}`); + return relationshipCoverageLimitations(coverage).map( + (reason) => `${label}${reason}`, + ); }); if ( reads.some( @@ -90,24 +83,11 @@ export const functionCallCoverageLimitations = ( coverage: RelationshipCoverage | null, dossier: Pick, ): string[] => { - const limitations = - coverage === null - ? ["Provider did not report relationship coverage."] - : coverage.status === "unknown" - ? [ - coverage.reason, - ...("diagnostics" in coverage ? coverage.diagnostics : []), - ] - : coverage.status === "partial" - ? [ - ...coverage.limitations, - ...("diagnostics" in coverage ? coverage.diagnostics : []), - ] - : []; - limitations.push( + return uniqueSorted([ + ...relationshipCoverageLimitations(coverage), + ...(coverage?.status === "complete" ? [] : (coverage?.diagnostics ?? [])), ...(dossier.unresolved_calls ?? []).map( ({ address, reason }) => `Unresolved call at ${address}: ${reason}`, ), - ); - return uniqueSorted(limitations); + ]); }; diff --git a/src/domain/relationshipCoverage.ts b/src/domain/relationshipCoverage.ts index 4dd4e0c40..f241206a0 100644 --- a/src/domain/relationshipCoverage.ts +++ b/src/domain/relationshipCoverage.ts @@ -33,3 +33,19 @@ export const relationshipCoverageSchema = z.discriminatedUnion("status", [ ]); export type RelationshipCoverage = z.infer; + +/** Reasons the observed relationship inventory cannot establish completeness. */ +export const relationshipCoverageLimitations = ( + coverage: RelationshipCoverage | null | undefined, +): readonly string[] => { + switch (coverage?.status) { + case undefined: + return ["Provider did not report relationship coverage."]; + case "complete": + return []; + case "partial": + return coverage.limitations; + case "unknown": + return [coverage.reason]; + } +}; From 2dc89f81be807de88b7b19b5f4ffcc7bff171068 Mon Sep 17 00:00:00 2001 From: JANG BYUNGKUN Date: Wed, 14 Oct 2026 09:27:37 +0900 Subject: [PATCH 5/9] docs(readme): sync Korean README with the English README (#3046) --- docs/readme/README_ko.md | 47 +++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/docs/readme/README_ko.md b/docs/readme/README_ko.md index 1c1133254..e6affdb19 100644 --- a/docs/readme/README_ko.md +++ b/docs/readme/README_ko.md @@ -20,7 +20,7 @@ **[웹사이트](https://rea.tools/ko/) · [가이드](https://rea.tools/ko/guides/) · [사례](https://rea.tools/ko/showcase/)** -[빠른 시작](#빠른-시작) · [REA의 작동 방식](#rea의-작동-방식) · [분석할 수 있는 대상](#분석할-수-있는-대상) · [사례](#사례) · [자주 묻는 질문](#자주-묻는-질문) · [GNU objdump 및 Rizin 도구](../reverse-engineering-tools.md) · [문서](#문서) +[빠른 시작](#빠른-시작) · [REA의 작동 방식](#rea의-작동-방식) · [분석할 수 있는 대상](#분석할-수-있는-대상) · [사례](#사례) · [자주 묻는 질문](#자주-묻는-질문) · [문서](#문서) npx rea-agents setup @@ -56,7 +56,7 @@ REA는 에이전트를 분석 도구에 연결해 네이티브 바이너리, JavaScript와 Electron 앱, .NET 어셈블리, 웹사이트를 검사할 수 있게 합니다. 터미널에서도 같은 도구를 사용할 수 있습니다. 분석은 로컬에서 실행되며, 결과에는 각 결론의 근거와 한계가 포함됩니다. -설정 과정은 에이전트에 REA를 등록하고 해당 버전에 맞는 워크플로 지침을 설치합니다. 네이티브 분석에는 기존 Hopper 또는 Ghidra 설치를 사용할 수 있습니다. 승인하면 설정 과정에서 Hopper를 설치할 수도 있습니다. 정적 JavaScript 분석에는 두 엔진 모두 필요하지 않습니다. +설정 과정은 에이전트에 REA를 등록하고 해당 버전에 맞는 워크플로 지침을 설치합니다. 네이티브 분석에는 기존 Hopper, Ghidra 또는 IDA 설치를 사용할 수 있습니다. 승인하면 설정 과정에서 Hopper를 설치할 수도 있습니다. 정적 JavaScript 분석에는 네이티브 분석 엔진이 필요하지 않습니다. > **[REA 웹사이트](https://rea.tools/ko/)**에서 설정 방법, 그림으로 설명한 가이드, 실제 사례를 확인하세요. @@ -105,12 +105,14 @@ rea --help REA는 빠르게 바뀌며 새 릴리스에는 버그 수정이 자주 포함됩니다. 설치된 버전을 최신으로 유지하세요. -npm으로 설치한 CLI에서는 다음 명령을 사용합니다. +`npm install --global` 또는 `bun add --global`로 설치한 CLI에서는 다음 명령을 사용합니다. ```bash rea update ``` +Bun 전역 업데이트에는 Bun 1.2.17 이상이 필요합니다. 이전 버전의 Bun을 사용한다면 `rea update`를 실행하기 전에 Bun을 직접 업그레이드하세요. + 에이전트 등록과 스킬을 갱신하려면 업데이트 과정에서 출력된 설정 명령을 실행하세요. `npx`를 사용한다면 다음 명령으로 에이전트 설정을 갱신하세요. @@ -119,7 +121,7 @@ rea update npx rea-agents@latest setup ``` -설정 변경 사항을 검토하고 에이전트를 다시 시작하세요. 일회성 CLI 작업에는 `npx rea-agents@latest` 뒤에 필요한 명령을 붙여 실행하세요. +설정 변경 사항을 검토하고 에이전트를 다시 시작하세요. 일회성 CLI 작업에는 `npx rea-agents@latest` 뒤에 필요한 명령을 붙여 실행하세요. Bun을 사용한다면 위 명령의 `npx rea-agents@latest`를 `bunx rea-agents@latest`로 바꿔 실행하세요. ## REA의 작동 방식 @@ -139,14 +141,16 @@ REA에는 Node.js 22.x(>=22.19), 24.x(>=24.11) 또는 26+와 npm이 필요합니 | --------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | 네이티브 바이너리 | 의사 코드, 어셈블리, 문자열, 심볼, 호출, 참조 | Hopper, Ghidra 또는 IDA; [네이티브 분석](https://rea.tools/ko/guides/native/) | | 오프라인 ELF 레이아웃 | 섹션, 세그먼트, 원본 심볼/재배치 정보, 정적 분석으로 얻은 보안 완화 기법 후보 | Linux x64에서 호출자가 제공하는 pwntools; [바이너리 진단](../binary-diagnostics.md) | +| Go 바이너리 | 내장된 컴파일러 버전, 모듈, `replace` 지시어, 빌드 설정 | REA 내장 ELF/PE/thin Mach-O 정적 검사; Go 설치 불필요 | +| Rust 바이너리 | cargo-auditable이 내장한 크레이트 이름, 버전, 소스, 의존성 관계 | REA 내장 ELF/PE/thin Mach-O 정적 검사; [Rust 바이너리](../rust-binaries.md) | +| WASM 아티팩트 | 유효성 검사, 섹션, import/export의 정확한 WAT 형식, 디코딩된 WAT | 호출자 제공 WABT 1.0.42; `inspect_wasm_artifact` | | EVM 바이트코드 | 디스패치 선택자, 바이트 오프셋, 추론한 인자와 상태 변경 가능 여부 | Linux x64의 로컬 원시 바이트/16진수 입력 파일; [오프라인 EVM 가이드](../evm-bytecode.md) | -| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) | +| SQLite 데이터베이스 | 테이블, 열, 인덱스, 뷰, 트리거, 선택한 일반 테이블의 행 | 로컬 데이터베이스/WAL 스냅샷; Node.js 24.15 이상의 24.x 또는 26 이상(네이티브 SQLite 한도 적용) | | 기록된 Linux 크래시 | 원시 note 레코드, 기록된 모든 스레드의 레지스터/시그널, 선택적 매핑 후보 | Linux x64에서 호출자가 제공하는 pwntools; GDB/pwndbg는 선택 사항; [기록된 크래시](../recorded-crashes.md) | | JavaScript / Electron | 모듈, 임포트, 소스 맵, 라우트, IPC, 네이티브 애드온 관계 | Node.js와 npm; [애플리케이션 분석](https://rea.tools/ko/guides/javascript/) | | 웹사이트 | 페이지 구조, 스크립트, 네트워크 관찰 결과, 요청한 스크린샷 | Chrome 계열 브라우저; [브라우저 분석](https://rea.tools/ko/guides/browser/) | -| 저장된 네트워크 캡처 | 요청, 응답, 접근 가능한 페이로드, 소스 위치 | HAR; mitmproxy 네이티브 캡처에는 Linux의 mitmdump; [캡처 가이드](../web-network-captures.md) | -| 패킷 캡처 | 엔드포인트, DNS, TLS SNI, 프로토콜 분포, HTTP 요청 | 호출자 제공 tshark 및 capinfos; [pcap 가이드](../pcap-analysis.md) | -| .NET 어셈블리 | 메타데이터, CIL 명령, 선언된 네이티브 의존성, 빌드 비교 | 정적 검사; [관리 코드 가이드](../managed-code-analysis.md) | +| 저장된 네트워크 캡처 | 요청, 응답, 접근 가능한 페이로드, 소스 위치 | HAR 또는 Fiddler Everywhere SAZ; mitmproxy 네이티브 캡처에는 Linux의 mitmdump; [캡처 가이드](../web-network-captures.md) | +| .NET 어셈블리 | 메타데이터, CIL 명령, 선언된 네이티브 의존성, 빌드 비교 | 별도 도구 불필요(정적 검사만); [관리 코드 가이드](../managed-code-analysis.md) | | Android APK | 매니페스트 선언, 클래스, 디컴파일된 메서드, 참조 | Linux/macOS/Windows x64의 헤드리스 JADX와 전체 JDK; [Android 가이드](../android-analysis.md) | | Android 기기 | 기기, 패키지, 프로세스, 로그, 덤프, 화면 캡처, APK/파일 전송 | 호출자 제공 adb(에뮬레이터 또는 실제 기기); [ADB 가이드](../adb-device-analysis.md) | | JEB 프로젝트 | 엔진 기반 프로젝트 유닛, 아티팩트 해시, 타입/메서드 의사코드 | 호출자가 시작하고 MCP를 제공하는 JEB 클라이언트(REA_JEB_MCP_URL로 선택); [JEB 가이드](../jeb-analysis.md) | @@ -154,15 +158,18 @@ REA에는 Node.js 22.x(>=22.19), 24.x(>=24.11) 또는 26+와 npm이 필요합니 | Flutter 앱 | Dart 스냅샷 해시, ABI별 라이브러리 해시, 엔진 빌드 출처 | 없음 (정적 APK 파싱); [Flutter 가이드](../flutter-analysis.md) | | 펌웨어 | 영역, 추출 결과, 네이티브 분석으로 전달할 정보 | Linux의 Binwalk / Unblob; [펌웨어 가이드](../firmware-analysis.md) | | 기록된 패킷 | 선택 필드, 반복 값, 필터 및 디코딩 규칙 | Linux: TShark 4.x + prlimit; [캡처 가이드](../packet-captures.md) | +| 패킷 요약 | 엔드포인트, DNS, TLS SNI, 프로토콜 분포, HTTP 요청 | 호출자 제공 tshark 및 capinfos(Linux에서 검증됨); [pcap 가이드](../pcap-analysis.md) | | 기록된 논리 신호 | 디코더 주석, 샘플 범위, 진단 정보 | Linux: sigrok-cli 0.7.2 + prlimit; [신호 기록 가이드](../signal-recordings.md) | | 패키지 및 리소스 | 파일 목록, 다이제스트, plist, Apple 번들 구조, 추출한 리소스 | [아티팩트 및 JavaScript 가이드](../javascript-artifact-reconstruction.md), [Apple 애플리케이션](../apple-application-analysis.md) | | 프로세스 동작 | 터미널 출력, 상호작용, 종료 및 파일 시스템 관찰 결과, 실행 비교 | 네이티브 PTY를 지원하는 Linux/macOS; [프로세스 캡처](../process-capture.md) | 정적 JavaScript 및 .NET 검사는 제공된 파일을 읽으며 애플리케이션을 실행하지 않습니다. 런타임 캡처는 사용자의 권한으로 선택한 대상을 실행하거나 대상과 상호작용합니다. 각 런타임 가이드에서 그 영향을 설명합니다. +오프라인 네이티브 바이너리 검사에는 호출자가 제공하는 GNU objdump와 Rizin도 사용할 수 있습니다. 제공자 설정, CLI 명령, Evidence의 한계는 [리버스 엔지니어링 도구 가이드](../reverse-engineering-tools.md)를 참고하세요. REA는 objdump와 Rizin을 설치하거나 업데이트하지 않습니다. + -지원하는 네이티브 형식과 호스트는 제공자마다 다릅니다. [Hopper 및 Ghidra 설정](../installation.md#hopper), [IDA 가이드](../ida-provider.md), [실험적 Windows Ghidra 지원](../windows-ghidra-p0.md)을 참고하세요. Ghidra는 [16비트 DOS 분석](../ghidra-dos.md)도 지원합니다. 제공자 선택은 [CLI 가이드](../cli.md#choose-a-provider)를 참고하세요. 최신 npm 릴리스 이후 추가된 기능은 [릴리스에서의 사용 가능 여부](../installation.md#released-package-and-main)를 확인하세요. +지원하는 네이티브 형식과 호스트는 제공자마다 다릅니다. [Hopper 및 Ghidra 설정](../installation.md#hopper), [IDA 가이드](../ida-provider.md)(선택 사항인 네이티브 MCP 브리지 포함), [실험적 Windows Ghidra 지원](../windows-ghidra-p0.md)을 참고하세요. Ghidra는 [16비트 DOS 분석](../ghidra-dos.md)도 지원합니다. 큰 바이너리를 분석할 때는 `REA_GHIDRA_STARTUP_TIMEOUT_MS` 또는 `REA_HOPPER_STARTUP_TIMEOUT_MS`로 제공자의 시작 제한 시간을 늘리세요. 제공자 선택은 [CLI 가이드](../cli.md#choose-a-provider)를 참고하세요. 최신 npm 릴리스 이후 추가된 기능은 [릴리스에서의 사용 가능 여부](../installation.md#released-package-and-main)를 확인하세요. ## 사례 @@ -209,7 +216,7 @@ REA로 흥미로운 대상을 분석했다면 알려 주세요. [issue](https://
Hopper를 먼저 실행해야 하나요? -REA는 작업에 필요할 때 Hopper를 실행합니다. macOS에서는 처음 실행할 때 데모 모드를 선택하거나 라이선스를 활성화하라는 대화 상자가 나타날 수 있습니다. [Hopper 실행 및 문제 해결](../installation.md#launcher-paths-and-troubleshooting)을 참고하세요. +REA는 작업에 필요할 때 Hopper를 실행합니다. macOS에서는 처음 실행할 때 데모 모드를 선택하거나 라이선스를 활성화하라는 대화 상자가 나타날 수 있습니다. 첫 CLI/MCP 작업이나 무인 작업을 실행하기 전에 같은 사용자 세션에서 이 대화 상자를 완료하세요. 필요하면 Hopper를 직접 여세요. [Hopper 실행 및 문제 해결](../installation.md#launcher-paths-and-troubleshooting)을 참고하세요.
@@ -239,7 +246,7 @@ REA는 대상을 로컬에서 분석합니다. 에이전트는 도구 결과를 먼저 업데이트하세요. 최근 릴리스에서 이미 수정되었을 수 있습니다. -npm으로 설치한 CLI에서는 다음 명령을 사용합니다. +`npm install --global` 또는 `bun add --global`로 설치한 CLI에서는 다음 명령을 사용합니다. ```bash rea update @@ -286,11 +293,9 @@ REA를 사용하고, 버그를 보고하고, 기능을 요청하고, 빌드를 책임 있는 사용에 관한 안내는 [DISCLAIMER.md](../../DISCLAIMER.md)를 참고하세요. -REA는 법을 준수하는 연구, 교육, 상호운용성 확보, 소프트웨어 보존, 그리고 본인이 소유하거나 조사 권한을 가진 소프트웨어의 분석을 위한 도구입니다. +불법적이거나 허가되지 않은 사용에 대한 프로젝트의 입장은 모든 REA 버전, 배포 채널, 플랫폼에 적용되며, 각 사본에는 해당 라이선스가 그대로 유지됩니다. -The project's position on illegal or unauthorized use covers all REA -versions, distribution channels, and platforms; each copy retains its -applicable licenses. +REA는 법을 준수하는 연구, 교육, 상호운용성 확보, 소프트웨어 보존, 그리고 본인이 소유하거나 조사 권한을 가진 소프트웨어의 분석을 위한 도구입니다. ## 기여 @@ -302,14 +307,6 @@ REA에 도움을 보태 주세요! [issue를 등록](https://github.com/morluto/ [MIT](../../LICENSE) -REA-authored code is licensed under MIT. Third-party material retains its own -licenses and copyright notices; see [Third-party notices](../../THIRD_PARTY_NOTICES.md) -for the dependency inventory, preserved license texts, and external-tool terms. +REA가 작성한 코드는 MIT 라이선스를 따릅니다. 제3자 자료에는 각자의 라이선스와 저작권 고지가 그대로 유지됩니다. 의존성 목록, 보존된 라이선스 원문, 외부 도구 약관은 [제3자 고지](../../THIRD_PARTY_NOTICES.md)를 참고하세요. -**You must legally obtain and be authorized to use commercial tools**, including -IDA Pro / Hex-Rays decompilers, Hopper, and JEB, under their applicable licenses. -REA grants no tool license, key, or activation entitlement. Trials and demos -remain subject to vendor terms, including user, feature, automation, and output -sharing restrictions. Cracked copies, stolen keys, unauthorized key sharing, -and bypassing license restrictions are not authorized. This guidance does not -amend MIT or third-party licenses. +IDA Pro / Hex-Rays 디컴파일러, Hopper, JEB 등 상용 도구는 해당 라이선스에 따라 **합법적으로 취득하고 사용 권한을 갖춰야 합니다.** REA는 어떤 도구의 라이선스, 키, 활성화 권한도 부여하지 않습니다. 체험판과 데모는 사용자, 기능, 자동화, 출력 공유 제한을 포함한 공급업체 약관을 따릅니다. 크랙 버전, 도난 키, 무단 키 공유, 라이선스 제한 우회는 허용되지 않습니다. 이 안내는 MIT 라이선스나 제3자 라이선스를 변경하지 않습니다. From d82ad1faf0b2774c56a10d8a81b09defacd99c7b Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:28:23 +0800 Subject: [PATCH 6/9] test(android): preserve malformed DEX prototype rejection (#2917) Preserve malformed DEX parameter/return rejection with tagged producer errors and exact issue paths. The equivalent portable descriptor fix is already on main via #2910. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> --- tests/boundary/android/JadxAnalysis.test.ts | 62 +++++++++++++-------- 1 file changed, 40 insertions(+), 22 deletions(-) diff --git a/tests/boundary/android/JadxAnalysis.test.ts b/tests/boundary/android/JadxAnalysis.test.ts index 36b0ab9d9..ad7d0d614 100644 --- a/tests/boundary/android/JadxAnalysis.test.ts +++ b/tests/boundary/android/JadxAnalysis.test.ts @@ -279,26 +279,44 @@ it("preserves bounded instruction coverage separately from using-node coverage", }); }); -it("rejects malformed method descriptors at the Android adapter boundary", async () => { - const invalidSummary = { - ...summary, - methods: summary.methods.map((method) => ({ - ...method, - dex_descriptor: "not-a-dex-descriptor", - })), - }; - await expect( - analyzeJadxRequest( - { - json: () => Promise.resolve(invalidSummary), - text: () => Promise.reject(new Error("unexpected text call")), +it.each([ + "not-a-dex-descriptor", + "(Lbad(name;)V", + "(Lbad)name;)V", + "()Lbad(name;", + "()Lbad)name;", +])( + "rejects malformed DEX prototype %s at the adapter boundary", + async (descriptor) => { + const invalidSummary = { + ...summary, + methods: summary.methods.map((method) => ({ + ...method, + dex_descriptor: descriptor, + })), + }; + await expect( + analyzeJadxRequest( + { + json: () => Promise.resolve(invalidSummary), + text: () => Promise.reject(new Error("unexpected text call")), + }, + { + operation: "inspect_android_class", + input: { path: "/fixture.apk", class_name: "fixture.Target" }, + }, + {} as never, + engine, + ), + ).rejects.toMatchObject({ + _tag: "AnalysisOutputError", + cause: { + issues: expect.arrayContaining([ + expect.objectContaining({ + path: ["methods", 0, "dex_descriptor"], + }), + ]), }, - { - operation: "inspect_android_class", - input: { path: "/fixture.apk", class_name: "fixture.Target" }, - }, - {} as never, - engine, - ), - ).rejects.toThrow(); -}); + }); + }, +); From a6c3d3a365fae5fd41455f1a6eaad041caddfa50 Mon Sep 17 00:00:00 2001 From: Danish Rafie Ekaputra <155859586+0xRafie@users.noreply.github.com> Date: Wed, 14 Oct 2026 07:31:16 +0700 Subject: [PATCH 7/9] docs(skill): route browser actions to scenario capture Route user browser actions to passive observation and agent actions to declared scenarios. Clarify requested artifacts, step outcomes, connect navigation and cleanup, and the limits of listener and request-initiator evidence. Distinguish discarded raw headers from retained response metadata. Update the bundled skill to version 42 with matching package metadata. Validation on the synchronized revision: docs (5 tests), typecheck/lint, formatting, 61 focused tests, and real Linux Chromium launch/connect and passive CLI probes. Verified declared steps, requested artifacts, digests, external page preservation, temporary form reset and cleanup. Native Windows/macOS and separate follow-up tools were not rerun. Package install/update and CLI/MCP verification passed earlier on 738d02a, before this main sync. Co-authored-by: 0xRafie <155859586+0xRafie@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- .../skills/reverse-engineer-anything/SKILL.md | 9 +++- .../references/runtime-observation.md | 45 ++++++++++++++++--- src/generatedPackageMetadata.ts | 2 +- 3 files changed, 47 insertions(+), 9 deletions(-) diff --git a/.agents/skills/reverse-engineer-anything/SKILL.md b/.agents/skills/reverse-engineer-anything/SKILL.md index f7e44e17a..b0b5b8b33 100644 --- a/.agents/skills/reverse-engineer-anything/SKILL.md +++ b/.agents/skills/reverse-engineer-anything/SKILL.md @@ -2,7 +2,7 @@ name: reverse-engineer-anything description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. metadata: - version: "41" + version: "42" --- # REA @@ -104,6 +104,10 @@ explicit path or endpoint and do not need it. consult the NativeAOT workflow in `references/native-and-artifacts.md` for optional metadata recovery and its supported host/layout boundary. - User-owned browser page already open: `list_browser_targets`. +- Browser action the agent must perform (click, type, navigate): + `capture_browser_scenario` with declared actions. See + [runtime observation](references/runtime-observation.md) for connect/launch + and the focused follow-up browser tools. - Fiddler Everywhere traffic or a native `.saz` capture: read the [Fiddler workflow](references/runtime-observation.md#fiddler-everywhere-traffic-debugging). Inspect saved SAZ with `inspect_web_network_capture` and `format: "saz"`; @@ -323,7 +327,8 @@ as complete while required questions remain open. [references/javascript-applications.md](references/javascript-applications.md) - Android APK declarations, classes, methods, and static references: [references/android-applications.md](references/android-applications.md) -- Passive browser/Electron observation and static/runtime reconciliation: +- Browser/Electron observation (passive and scenario) and static/runtime + reconciliation: [references/runtime-observation.md](references/runtime-observation.md) - Evidence paging, comparisons, residual unknowns, and verification: [references/evidence-workflows.md](references/evidence-workflows.md) diff --git a/.agents/skills/reverse-engineer-anything/references/runtime-observation.md b/.agents/skills/reverse-engineer-anything/references/runtime-observation.md index 2d660d675..ba197ecb8 100644 --- a/.agents/skills/reverse-engineer-anything/references/runtime-observation.md +++ b/.agents/skills/reverse-engineer-anything/references/runtime-observation.md @@ -1,4 +1,4 @@ -# Passive browser and Electron observation +# Browser and Electron runtime observation Supply the existing browser or Electron instance's literal-port loopback CDP endpoint in the request. No separate permission configuration or per-call @@ -7,13 +7,14 @@ approval flag is needed. Browser discovery lists eligible HTTP(S) pages; selected page's current origin. Electron discovery lists eligible local `file://` targets without a configured file-root allowlist. -Start browser work with `list_browser_targets`; start Electron runtime work with +Start passive browser work with `list_browser_targets`; start Electron runtime work with `list_electron_targets`. Inspect the target selected for the user's task. Observation -is passive: never claim REA clicked, navigated, evaluated page JavaScript, -invoked IPC, captured prior activity, or contained the page's network. +with these tools is passive: never claim REA clicked, navigated, evaluated page JavaScript, +invoked IPC, or captured prior activity. REA does not contain the page's network. -Credentials, cookies, authorization headers, storage values, and raw -WebSocket/JSON bodies are deliberately absent. Local URLs retain ordinary query +Passive captures omit raw header collections, credential header values, storage +values, and raw WebSocket/JSON bodies. Selected response metadata, including +content encoding, policy values, and Link URLs, is retained. Local URLs retain ordinary query values and fragments; userinfo credentials are removed. Browser accessibility text, console primitives, value-free shapes, script sources, source maps, and storage key names have request-specific capture options. Electron script @@ -21,6 +22,38 @@ sources are also optional. Use `capture_web_screenshot` when pixels are needed. Treat scope filtering, truncation, and attach-window coverage as limitations. Page-declared WebMCP tools are untrusted inventory and are never invoked by REA. +## Who performs the action + +- The user performs it: `list_browser_targets`, then `inspect_web_page` or + `observe_web_session` on the selected target. +- The agent must perform it: one `capture_browser_scenario` with declared + actions. Use connect mode with the loopback CDP endpoint and `target_id` for + an existing browser, or launch mode with a caller-selected executable for a + temporary profile. Connect mode first navigates the selected page to + `start_url`, which can clear unsaved form values and other temporary state. + Recreate the state needed for the investigation in the declared actions. + Connect mode leaves the external browser open; launch mode owns a temporary + browser and profile. Check `browser.cleanup` for the outcome. + Request only the DOM, accessibility, or network details needed for the question. + The default final capture contains the URL; step outcomes are reported separately. + Add a wait action for the expected page state before capturing it. Report that + REA performed the declared actions. + +Scenario network records have no request initiator stacks. For that evidence, +use passive capture while the user performs the action. Listener source locations +identify candidate handlers; they do not establish which script sent a particular +request. Avoid overlapping passive capture and scenario actions on the same target. + +Focused follow-up tools: + +- `observe_web_execution`: execution coverage during a window; it resets + counters and temporarily disables optimization. +- `inspect_web_event_listeners`: source locations for listeners registered + directly on the first CSS match, without dispatching an event. +- `compare_web_captures`: two normalized passive captures or recorded scenarios. +- `discover_webmcp_tools`: inspect page-declared WebMCP inventory; never invoke + the discovered tools. + Use `reconcile_javascript_runtime` only after static application Evidence and passive browser/Electron Evidence exist. Prefer captured-source digest identity; report path/digest disagreement as a mismatch and preserve ambiguity. Explicit diff --git a/src/generatedPackageMetadata.ts b/src/generatedPackageMetadata.ts index bada60663..081e22d5a 100644 --- a/src/generatedPackageMetadata.ts +++ b/src/generatedPackageMetadata.ts @@ -5,5 +5,5 @@ export const PACKAGE_METADATA = { serverSdkVersion: "2.3.1", clientSdkVersion: "2.3.1", coreSdkVersion: "2.3.1", - skillVersion: "41", + skillVersion: "42", } as const; From 679658b28748729c9b881497e680c811a708f5f3 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:33:09 -0700 Subject: [PATCH 8/9] fix(reference): report entries beyond the path limit as I/O failures (#2716) * fix(reference): report entries beyond the path limit as I/O failures Reference-source traversal joins each child onto the root path. A valid tree whose nested entries exceed the platform's absolute path limit (PATH_MAX 1024 on macOS) makes lstat fail with ENAMETOOLONG. The reader's filesystem error allow-list lacked that code, so filesystemFailureDetail returned undefined and the native rejection escaped both readReferenceSource and importReferenceSource instead of becoming the existing failed `io` entry. Add ENAMETOOLONG to the allow-list, matching the JavaScript application reader's list. Readable siblings stay in the graph and the unreachable entry is recorded with its OS message. Fixes #2652 Co-Authored-By: Claude Opus 5.5 * test(reference): assert the imported graph keeps readable and failed entries Co-Authored-By: Claude Opus 5.5 * fix(process): report no remaining time after a provider deadline fires Node timers can fire while performance.now() is still a fraction of a millisecond short of the monotonic deadline. ProviderStartupDeadline then reported interruption "timeout" and an aborted signal while remainingMs() returned ceil(0.x) = 1, so polling loops guarded by remainingMs() > 0 (Hopper and Ghidra startup) could run past an elapsed deadline, and the real-timer test "aborts a bounded wait when its real monotonic deadline expires" failed intermittently in CI (expected 1 to be 0). Once the deadline's own timer has classified a timeout, report zero remaining time. A deterministic regression test fires the timer with the monotonic clock 0.4 ms short of the deadline. Co-Authored-By: Claude Opus 5.5 * fix(reference): preserve path limit entry uncertainty * fix(reference): preserve unknown entry failures and identity * fix(reference): type unknown-kind exclusions and keep them out of symlink counts The metadata-failure path offers "unknown" to exclusion predicates, but the predicate type only admitted concrete kinds, which broke the build. Directory-only secret and ignore rules now also match an unknown-kind entry (it may be a directory), and the summary counts unknown entries separately instead of as symlinks. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Codex --- src/application/ReferenceSourceImport.ts | 30 +++++-- .../ReferenceSourceImportEntries.ts | 9 ++ src/domain/referenceSourceGraph.test.ts | 24 ++++++ src/domain/referenceSourceGraph.ts | 12 ++- src/domain/referenceSourceSummary.test.ts | 20 +++++ src/domain/referenceSourceSummary.ts | 4 +- src/reference/ReferenceSourceReaderEntries.ts | 13 ++- src/reference/ReferenceSourceReaderErrors.ts | 5 ++ src/reference/ReferenceSourceReaderTypes.ts | 10 ++- .../referenceSourceFailureDetails.test.ts | 85 +++++++++++++++++++ 10 files changed, 197 insertions(+), 15 deletions(-) diff --git a/src/application/ReferenceSourceImport.ts b/src/application/ReferenceSourceImport.ts index 769f8bb8c..f917f1965 100644 --- a/src/application/ReferenceSourceImport.ts +++ b/src/application/ReferenceSourceImport.ts @@ -12,7 +12,7 @@ import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.j import type { AnalysisCleanupObservation } from "../domain/analysisErrorBase.js"; import { readReferenceSource } from "../reference/ReferenceSourceReader.js"; import type { - ReferenceSourceEntryKind, + ReferenceSourceExclusionKind, ReferenceSourceRead, ReferenceSourceReaderError, } from "../reference/ReferenceSourceReaderTypes.js"; @@ -111,7 +111,8 @@ const deriveInventoryState = ( entry.limitations.length > 0 || (entry.kind === "file" && entry.content_state !== "hashed") || (entry.kind === "directory" && entry.tree_state !== "enumerated") || - (entry.kind === "symlink" && entry.target_state !== "internal"), + (entry.kind === "symlink" && entry.target_state !== "internal") || + entry.kind === "unknown", ); if (partialEntry) return "partial"; const partialRelationship = input.relationships.some( @@ -142,11 +143,24 @@ const createShouldExclude = exclusions: HistoricalSourceGraphInput["exclusions"], secrets: PreparedReferenceSourceImport["secrets"], ignored: PreparedReferenceSourceImport["ignored"], - ): ((path: string, kind: ReferenceSourceEntryKind) => boolean) => + ): ((path: string, kind: ReferenceSourceExclusionKind) => boolean) => (path, kind) => { - const patternPath = kind === "directory" ? `${path}/` : path; - const secretMatch = secrets.test(patternPath); - if (secretMatch.ignored) { + // An entry of unknown kind may be a directory, so directory-only rules + // must still exclude it; this fails closed for caller-marked secrets. + const patternPaths = + kind === "directory" + ? [`${path}/`] + : kind === "unknown" + ? [path, `${path}/`] + : [path]; + const firstMatch = (matcher: typeof secrets) => { + const results = patternPaths.map((patternPath) => + matcher.test(patternPath), + ); + return results.find(({ ignored }) => ignored) ?? results[0]; + }; + const secretMatch = firstMatch(secrets); + if (secretMatch?.ignored === true) { if (!secretMatch.rule) throw new Error(`Ignored secret path has no matching rule: ${path}`); exclusions.push({ @@ -156,8 +170,8 @@ const createShouldExclude = }); return true; } - const match = ignored.test(patternPath); - if (!match.ignored) return false; + const match = firstMatch(ignored); + if (match?.ignored !== true) return false; if (!match.rule) throw new Error(`Ignored path has no matching rule: ${path}`); const reason = match.rule.mark; diff --git a/src/application/ReferenceSourceImportEntries.ts b/src/application/ReferenceSourceImportEntries.ts index 49c6f82f5..29dbef356 100644 --- a/src/application/ReferenceSourceImportEntries.ts +++ b/src/application/ReferenceSourceImportEntries.ts @@ -45,6 +45,8 @@ const entryRecoveryGuidance = ( return "This directory could not be read. Check its permissions, then try again."; if (entry.kind === "symlink") return "This symbolic link could not be read safely. Check the link and its permissions, then try again."; + if (entry.kind === "unknown") + return "This entry's type could not be determined. Check the parent directory and try again."; return "This file could not be read. Check its permissions, then try again."; }; @@ -73,6 +75,13 @@ const failedEntry = ( classifications, limitations: [limitation], }; + if (entry.kind === "unknown") + return { + path: entry.path, + kind: "unknown", + classifications: ["unknown"], + limitations: [limitation], + }; return { path: entry.path, kind: "file", diff --git a/src/domain/referenceSourceGraph.test.ts b/src/domain/referenceSourceGraph.test.ts index 1286cdde6..8fe868832 100644 --- a/src/domain/referenceSourceGraph.test.ts +++ b/src/domain/referenceSourceGraph.test.ts @@ -259,6 +259,30 @@ describe("historical source graph", () => { }); describe("partial historical source graphs", () => { + it("keeps unknown-entry diagnostics outside the root commitment", () => { + const base = graphInput(); + base.inventory_state = "partial"; + base.entries[2] = { + path: "src/package.json", + kind: "unknown", + classifications: ["unknown"], + limitations: ["Permission denied at /private/first"], + }; + const graph = createHistoricalSourceGraph(base); + const changedMessage = structuredClone(base); + changedMessage.entries[2] = { + path: "src/package.json", + kind: "unknown", + classifications: ["unknown"], + limitations: ["Permission denied at /private/second"], + }; + const revised = createHistoricalSourceGraph(changedMessage); + expect(revised.root_sha256).toBe(graph.root_sha256); + expect(computeHistoricalSourceGraphSha256(revised)).not.toBe( + computeHistoricalSourceGraphSha256(graph), + ); + }); + it("keeps an unreadable symlink target unknown and out of root identity", () => { const base = graphInput(); base.inventory_state = "partial"; diff --git a/src/domain/referenceSourceGraph.ts b/src/domain/referenceSourceGraph.ts index 197e473bf..a830e0aa0 100644 --- a/src/domain/referenceSourceGraph.ts +++ b/src/domain/referenceSourceGraph.ts @@ -111,6 +111,10 @@ const sourceEntrySchema = z.union([ sourceFileSchema, sourceDirectorySchema, sourceSymlinkSchema, + z.strictObject({ + ...entryBaseShape, + kind: z.literal("unknown"), + }), ]); const sourceRelationshipSchema = z.strictObject({ @@ -361,7 +365,8 @@ const checkCompleteInventory = ( entry.limitations.length > 0 || (entry.kind === "file" && entry.content_state !== "hashed") || (entry.kind === "directory" && entry.tree_state !== "enumerated") || - (entry.kind === "symlink" && entry.target_state !== "internal"), + (entry.kind === "symlink" && entry.target_state !== "internal") || + entry.kind === "unknown", ); const partialRelationship = graph.relationships.some( ({ parse_state, resolution }) => @@ -478,6 +483,11 @@ const rootCommitment = ( target: entry.target, target_state: entry.target_state, }; + case "unknown": + return { + kind: entry.kind, + path: entry.path, + }; } }), exclusions, diff --git a/src/domain/referenceSourceSummary.test.ts b/src/domain/referenceSourceSummary.test.ts index a0d23b0e1..3f34a073f 100644 --- a/src/domain/referenceSourceSummary.test.ts +++ b/src/domain/referenceSourceSummary.test.ts @@ -81,6 +81,26 @@ describe("committed historical-source summaries", () => { expect(graph).toEqual(original); }); + it("counts entries of unknown kind separately from symlinks", () => { + const graph = createHistoricalSourceGraph( + input([ + { + path: "deep", + kind: "unknown", + classifications: ["unknown"], + limitations: ["lstat: ENAMETOOLONG"], + }, + ]), + ); + expect(createHistoricalSourceSummary(graph, 1).counts).toMatchObject({ + entries: 1, + files: 0, + directories: 0, + symlinks: 0, + unknown: 1, + }); + }); + it("sums known bytes losslessly beyond the JSON safe integer range", () => { const graph = createHistoricalSourceGraph( input( diff --git a/src/domain/referenceSourceSummary.ts b/src/domain/referenceSourceSummary.ts index e7e99e3fa..55d24025d 100644 --- a/src/domain/referenceSourceSummary.ts +++ b/src/domain/referenceSourceSummary.ts @@ -29,6 +29,7 @@ export const createHistoricalSourceSummary = ( files: 0, directories: 0, symlinks: 0, + unknown: 0, relationships: graph.relationships.length, parse_failures: graph.parse_failures.length, exclusions: graph.exclusions.length, @@ -59,7 +60,8 @@ export const createHistoricalSourceSummary = ( } else if (entry.kind === "directory") { counts.directories += 1; treeStates[entry.tree_state] += 1; - } else counts.symlinks += 1; + } else if (entry.kind === "symlink") counts.symlinks += 1; + else counts.unknown += 1; // Canonical entries already use Unicode code-point order; filtering preserves it. if (entry.path.split("/").length <= outlineDepth) outline.push(outlineEntry(entry)); diff --git a/src/reference/ReferenceSourceReaderEntries.ts b/src/reference/ReferenceSourceReaderEntries.ts index e684a2b5c..8ec5e9d80 100644 --- a/src/reference/ReferenceSourceReaderEntries.ts +++ b/src/reference/ReferenceSourceReaderEntries.ts @@ -25,7 +25,7 @@ import { import type { PendingDirectory, ReferenceSourceEntry, - ReferenceSourceEntryKind, + ReferenceSourceExclusionKind, ReferenceSourceResult, TraversalState, } from "./ReferenceSourceReaderTypes.js"; @@ -201,6 +201,13 @@ const processEntry = async ( const metadata = await readMetadata(absolute); if (isAborted(state.signal)) return { ok: false, error: cancelled() }; if (!metadata.ok) { + const excluded = applyExclusion(state.shouldExclude, path, "unknown"); + if (!excluded.ok) + return { + ok: false, + error: failure("io", "Reference source exclusion check failed"), + }; + if (excluded.value) return { ok: true, value: undefined }; state.entries.push(entryFailure(path, "unknown", "io", metadata.message)); return { ok: true, value: undefined }; } @@ -371,10 +378,10 @@ const readSymlinkTarget = async ( const applyExclusion = ( shouldExclude: - | ((path: string, kind: ReferenceSourceEntryKind) => boolean) + | ((path: string, kind: ReferenceSourceExclusionKind) => boolean) | undefined, path: string, - kind: ReferenceSourceEntryKind, + kind: ReferenceSourceExclusionKind, ): { readonly ok: true; readonly value: boolean } | { readonly ok: false } => { try { return { ok: true, value: shouldExclude?.(path, kind) === true }; diff --git a/src/reference/ReferenceSourceReaderErrors.ts b/src/reference/ReferenceSourceReaderErrors.ts index 6ddd02a3f..2c826b4c9 100644 --- a/src/reference/ReferenceSourceReaderErrors.ts +++ b/src/reference/ReferenceSourceReaderErrors.ts @@ -29,6 +29,9 @@ const FILESYSTEM_ERROR_CODES = new Set([ "EISDIR", "ELOOP", "EMFILE", + // A traversed child can exceed the platform's absolute path limit even + // though the selected root and every component are valid. + "ENAMETOOLONG", "ENFILE", "ENOENT", "ENOTDIR", @@ -44,6 +47,8 @@ export const filesystemFailureDetail = ( ): string | undefined => { if (!(cause instanceof Error)) return undefined; const code: unknown = Reflect.get(cause, "code"); + if (code === "ENAMETOOLONG") + return `${operation}: ENAMETOOLONG (entry path exceeds the operating system path limit)`; return typeof code === "string" && FILESYSTEM_ERROR_CODES.has(code) ? `${operation}: ${cause.message}` : undefined; diff --git a/src/reference/ReferenceSourceReaderTypes.ts b/src/reference/ReferenceSourceReaderTypes.ts index 3b0a368b5..1fec38313 100644 --- a/src/reference/ReferenceSourceReaderTypes.ts +++ b/src/reference/ReferenceSourceReaderTypes.ts @@ -10,11 +10,17 @@ export type ReferenceSourceEntryKind = | "symlink" | "other"; +/** + * Kind offered to exclusion predicates. `unknown` marks an entry whose + * metadata could not be read, so its concrete kind cannot be claimed. + */ +export type ReferenceSourceExclusionKind = ReferenceSourceEntryKind | "unknown"; + export interface ReferenceSourceReaderOptions { readonly signal?: AbortSignal; readonly shouldExclude?: ( path: string, - kind: ReferenceSourceEntryKind, + kind: ReferenceSourceExclusionKind, ) => boolean; } @@ -84,7 +90,7 @@ export type TraversalState = { readonly signal?: AbortSignal; readonly shouldExclude?: ( path: string, - kind: ReferenceSourceEntryKind, + kind: ReferenceSourceExclusionKind, ) => boolean; readonly entries: ReferenceSourceEntry[]; readonly pending: PendingDirectory[]; diff --git a/tests/boundary/filesystem/referenceSourceFailureDetails.test.ts b/tests/boundary/filesystem/referenceSourceFailureDetails.test.ts index dd87ea92a..82476d6db 100644 --- a/tests/boundary/filesystem/referenceSourceFailureDetails.test.ts +++ b/tests/boundary/filesystem/referenceSourceFailureDetails.test.ts @@ -133,3 +133,88 @@ describe("reference import native entry failure details", () => { ).toMatchObject({ kind: "file", content_state: "hashed", limitations: [] }); }); }); + +describe("reference import paths beyond the platform limit", () => { + it.skipIf(process.platform === "win32")( + "reports an entry beyond the absolute path limit as an I/O failure", + async () => { + const root = await createTestTempDirectory("rea-import-deep-path-"); + await writeFile(join(root, "kept.txt"), "k"); + // Relative creation lets the tree exceed PATH_MAX (1024 on macOS, 4096 + // on Linux) while each 200-byte component stays below NAME_MAX. + const deepTree = (action: "create" | "remove") => + promisify(execFile)(process.execPath, [ + "-e", + `const fs = require("node:fs"); + const names = Array.from({ length: 24 }, (_, i) => "d" + String(i).padStart(2, "0") + "x".repeat(197)); + process.chdir(${JSON.stringify(root)}); + if (${JSON.stringify(action)} === "create") { + for (const name of names) { fs.mkdirSync(name); process.chdir(name); } + fs.writeFileSync("deep.txt", "d"); + } else { + for (const name of names) process.chdir(name); + fs.rmSync("deep.txt"); + for (const name of [...names].reverse()) { process.chdir(".."); fs.rmdirSync(name); } + }`, + ]); + await deepTree("create"); + try { + const read = await readReferenceSource(root); + if (!read.ok) throw new Error(read.error.message); + expect(read.value.entries).toContainEqual( + expect.objectContaining({ path: "kept.txt", status: "read" }), + ); + const failed = read.value.entries.find( + (entry) => entry.status === "failed", + ); + expect(failed).toMatchObject({ + status: "failed", + code: "io", + message: expect.stringContaining("ENAMETOOLONG"), + }); + const filteredRead = await readReferenceSource(root, { + shouldExclude: (path, kind) => + path === failed?.path && kind === "directory", + }); + if (!filteredRead.ok) throw new Error(filteredRead.error.message); + expect( + filteredRead.value.entries.find( + (entry) => entry.path === failed?.path, + ), + ).toMatchObject({ status: "failed", kind: "unknown", code: "io" }); + const imported = await importTree(root); + if (!imported.ok) throw new Error(imported.error.message); + expect(imported.value.entries).toContainEqual( + expect.objectContaining({ + path: "kept.txt", + content_state: "hashed", + }), + ); + const deep = imported.value.entries.find( + (entry) => entry.path === failed?.path, + ); + expect(deep?.limitations.join(" ")).toContain( + failed?.status === "failed" ? failed.message : "missing failure", + ); + // A directory-only secret rule still applies when the kind is unknown. + const secretPattern = `${failed?.path ?? "missing"}/`; + const secret = await importReferenceSource({ + root, + caller: "native-entry-failure-detail-test", + policy: { secretPatterns: [secretPattern] }, + }); + if (!secret.ok) throw new Error(secret.error.message); + expect( + secret.value.entries.some(({ path }) => path === failed?.path), + ).toBe(false); + expect(secret.value.exclusions).toContainEqual({ + path: failed?.path, + reason: "configured-secret", + pattern: secretPattern, + }); + } finally { + await deepTree("remove"); + } + }, + ); +}); From ff56f785946c609b09c1c60232b28d7c34ac89a9 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:33:26 -0700 Subject: [PATCH 9/9] fix(uninstall): remove the REA-owned ZCode fallback registration (#2783) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(uninstall): remove the REA-owned ZCode fallback registration ZCode loads the user-scope `~/.agents/mcp.json` `mcpServers` fallback whenever its native `mcp.servers` table is empty. Uninstall removed REA only from the native table, so a REA-owned fallback entry became eligible to load again once the last native server was gone, while uninstall reported ZCode as removed and complete. Also visit the ZCode fallback as a standard `mcpServers` JSON configuration in the uninstall host. It goes through the same ownership check, `.rea.backup`, readback and restore path as every other client configuration, so other fallback servers and settings, and a foreign `rea` entry, are preserved. Its result merges into the ZCode item. Fixes #2664 Co-Authored-By: Claude Opus 5.5 * fix(uninstall): preserve the strict ZCode fallback dialect 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(comparison): recheck historical calls-only changes (#2223) * fix(comparison): preserve incomplete function call evidence Keep missing, unknown, partial and unresolved call relationships unknown in function comparisons and reconstruction claims. Aggregate IDA caller and callee coverage without overwriting uncertainty. Validate with 144 focused tests, typecheck/lint, docs checks and test discovery. Real providers were not verified; the full headless IDA session suite requires unavailable Windows native controls. * fix(comparison): recheck historical calls-only changes --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> * fix(ci): isolate Linux Hopper process fixture inventory * fix(android): make DEX descriptor pattern portable * fix: repair the static-check failures on the default branch (#2895) * fix: repair the static-check failures on the default branch The default branch fails its own required `Static checks` job three ways, so every pull request reports that job as failed regardless of its own change. - `npm run format:check` reports `src/domain/functionComparison.test.ts` and `src/ida/IdaOperationRunner.ts`. - `npm run lint` reports a duplicate `import { join } from "node:path"` in `tests/boundary/mcp/ghidraInventoryMcp.test.ts` (lines 4 and 17). - `npm run typecheck` reports `format: "devin"` missing from the client format union in `src/application/SupportedClients.ts`, and an unchecked index in `tests/boundary/cli/clientProfileLifecycle.test.ts`, whose pair array is inferred as `string[][]`. Apply the pinned formatter, drop the duplicate import, list the `"devin"` format that its own definition already uses, and mark the pair array `as const`. Validation: `npm run check:fast` and `npm run format:check` pass. * fix(setup): keep Devin on the JSON configuration dialect --------- Co-authored-by: 吴佳浩 Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Lucien <164857476+dakjdakd@users.noreply.github.com> Co-authored-by: 吴佳浩Alben <35291372+XiaoBinGan@users.noreply.github.com> Co-authored-by: 吴佳浩 --- docs/client-configuration.md | 6 +- .../ClientConfigurationDocument.ts | 3 +- src/application/SupportedClients.ts | 1 + src/application/Uninstall.ts | 15 +++- .../zcodeClientConfiguration.test.ts | 90 ++++++++++++++++++- 5 files changed, 109 insertions(+), 6 deletions(-) diff --git a/docs/client-configuration.md b/docs/client-configuration.md index d03984ec8..346ff77be 100644 --- a/docs/client-configuration.md +++ b/docs/client-configuration.md @@ -294,7 +294,11 @@ the first native server into an empty table, it copies the fallback's `mcpServers` entries into the native table so they keep loading, and leaves the fallback file untouched. Existing REA environment overrides are preserved when refreshing its command. A malformed or unreadable fallback file fails setup instead of -being silently suppressed; repair or remove it and rerun. ZCode disables a +being silently suppressed; repair or remove it and rerun. Uninstall removes an +REA-owned `rea` entry from both the native table and the fallback, backing up +each changed file, so an emptied native table cannot load a leftover fallback +registration; other fallback servers, settings and a foreign `rea` entry are +kept. ZCode disables a server with `enable: false` on its entry; doctor reports such a registration as stale, and rerunning setup removes the flag to repair it. Native configuration uses strict JSON; setup refuses comments, trailing commas and a BOM rather than diff --git a/src/application/ClientConfigurationDocument.ts b/src/application/ClientConfigurationDocument.ts index f7ab8f0e2..896442835 100644 --- a/src/application/ClientConfigurationDocument.ts +++ b/src/application/ClientConfigurationDocument.ts @@ -167,7 +167,7 @@ export const parseZcodeFallbackConfiguration = ( ? {} : requireObject(document.mcpServers, "ZCode fallback mcpServers"), serversPath: ["mcpServers"], - dialect: "json", + dialect: "zcode_fallback", legacyServers: {}, }; }; @@ -183,6 +183,7 @@ export const parseClientConfiguration = ( if (format === undefined || format === "unsupported") throw new TypeError("client does not have a supported MCP config format"); // DeepSeek Harness stores a Cordis patch list, not a server table. + if (format === "zcode_fallback") return parseZcodeFallbackConfiguration(text); if (format === "dsh") return parseDshCordisDocument(text); const document = parseDocument(text, format); const serversKey = clientConfigurationServersKey(format); diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts index 20ab3ed29..c4da675e7 100644 --- a/src/application/SupportedClients.ts +++ b/src/application/SupportedClients.ts @@ -47,6 +47,7 @@ export interface SetupClient { | "pi" | "kimi" | "hermes" + | "zcode_fallback" | "zcode" | "dsh" | "unsupported"; diff --git a/src/application/Uninstall.ts b/src/application/Uninstall.ts index eac36c73d..d6447a8f6 100644 --- a/src/application/Uninstall.ts +++ b/src/application/Uninstall.ts @@ -231,12 +231,21 @@ export const systemUninstallHost = ( const clients = supportedClients(home, platform, environment); redirection = appDataRedirection(clients); return Promise.resolve( - clients.flatMap((client) => - uninstallConfigPaths(client).map((configPath) => ({ + clients.flatMap((client) => [ + ...uninstallConfigPaths(client).map((configPath) => ({ ...client, configPath, })), - ), + ...(client.zcodeFallbackPath === undefined + ? [] + : [ + { + ...client, + configPath: client.zcodeFallbackPath, + format: "zcode_fallback" as const, + }, + ]), + ]), ); }, inspectClient: async (client) => { diff --git a/tests/boundary/filesystem/zcodeClientConfiguration.test.ts b/tests/boundary/filesystem/zcodeClientConfiguration.test.ts index 4b00a2e01..268747356 100644 --- a/tests/boundary/filesystem/zcodeClientConfiguration.test.ts +++ b/tests/boundary/filesystem/zcodeClientConfiguration.test.ts @@ -13,7 +13,10 @@ import { } from "../../../src/application/SetupClientConfiguration.js"; import { skillDestinations } from "../../../src/application/SetupSkill.js"; import { supportedClients } from "../../../src/application/SupportedClients.js"; -import { systemUninstallHost } from "../../../src/application/Uninstall.js"; +import { + runUninstall, + systemUninstallHost, +} from "../../../src/application/Uninstall.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js"; @@ -257,6 +260,91 @@ describe("ZCode .agents fallback preservation", () => { }); }); +describe("ZCode fallback uninstall", () => { + const owned = { command: command[0], args: command.slice(1) }; + const writeFallback = async (home: string, servers: object) => { + await mkdir(join(home, ".agents"), { recursive: true }); + const text = `${JSON.stringify({ ui: { keep: true }, mcpServers: servers }, null, 2)}\n`; + await writeFile(fallbackPath(home), text); + return text; + }; + + it.each(["comment", "trailing-comma", "bom"])( + "fails closed on strict fallback syntax: %s", + async (mode) => { + const { home } = await zcodeClient(); + const valid = await writeFallback(home, { + rea: owned, + other: { command: "other-server" }, + }); + const original = + mode === "comment" + ? `// unsupported comment\n${valid}` + : mode === "bom" + ? `\uFEFF${valid}` + : valid.replace(/\}\s*$/u, ",}"); + await writeFile(fallbackPath(home), original); + const result = await runUninstall(false, systemUninstallHost(home)); + expect(result.items).toContainEqual( + expect.objectContaining({ name: "zcode", status: "failed" }), + ); + expect(await readFile(fallbackPath(home), "utf8")).toBe(original); + await expect( + readFile(`${fallbackPath(home)}.rea.backup`), + ).rejects.toMatchObject({ code: "ENOENT" }); + }, + ); + + it("removes the REA-owned fallback entry with the native registration", async () => { + const { home, client } = await zcodeClient(); + await writeFile( + client.configPath, + JSON.stringify({ mcp: { servers: { rea: owned } } }), + ); + const original = await writeFallback(home, { + rea: owned, + other: { command: "other-server" }, + }); + + const result = await runUninstall(false, systemUninstallHost(home)); + + expect(result.status).toBe("complete"); + expect(result.items.find(({ name }) => name === "zcode")?.status).toBe( + "removed", + ); + const native = JSON.parse(await readFile(client.configPath, "utf8")); + expect(native.mcp.servers).toEqual({}); + const fallback = JSON.parse(await readFile(fallbackPath(home), "utf8")); + expect(fallback).toEqual({ + ui: { keep: true }, + mcpServers: { other: { command: "other-server" } }, + }); + expect(await readFile(`${fallbackPath(home)}.rea.backup`, "utf8")).toBe( + original, + ); + }); + + it("removes a fallback-only REA entry and keeps a foreign rea entry", async () => { + for (const [servers, expected] of [ + [{ rea: owned }, {}], + [ + { rea: { command: "someone-else" } }, + { rea: { command: "someone-else" } }, + ], + ] as const) { + const { home } = await zcodeClient(); + await writeFallback(home, servers); + + expect( + (await runUninstall(false, systemUninstallHost(home))).status, + ).toBe("complete"); + expect( + JSON.parse(await readFile(fallbackPath(home), "utf8")).mcpServers, + ).toEqual(expected); + } + }); +}); + describe("ZCode fallback admission", () => { it.each([{ PORT: 123 }, { REA_MCP_INPUT_SCHEMA_PROFILE: "unknown" }])( "refuses malformed fallback REA environment %j before native writes",