feat(ingest): ingest REA's JavaScript Application Graph

REA (morluto/rea, "Reverse Engineer Anything") reverse-engineers shipped apps —
native binaries, JS/Electron bundles, .NET, WASM — and emits a canonical,
evidence-bearing JavaScript Application Graph (JAG). This adds a graphify ingester
for it, so reverse-engineered structure becomes a queryable graphify graph:

    graphify extract --rea app.jag.json

- graphify/rea_ingest.py: `ingest_rea_jag(doc, source_file="")` maps JAG nodes
  (package/ASAR/electron main·preload·renderer/module/chunk/IPC/contextBridge/
  native add-on/...) to graphify nodes (kind -> file_type) and the JAG relation
  vocabulary (contains/loads/imports/calls/invokes/exposes/handles/...) to
  graphify relations, preserving the original relation in the edge context
  ("rea:<relation>"). REA's epistemic state drives confidence: observed ->
  EXTRACTED, inferred -> INFERRED (score capped). Endpoint-safe (mints
  `rea_external` stubs so no edge dangles); graph-wide coverage/limitations are
  attached to the root nodes' metadata.
- CLI: `graphify extract --rea <jag.json>` merges the ingested graph alongside
  AST/semantic/postgres/cargo sources, mirroring the existing ingesters.

Grounded in REA's documented JAG contract plus a synthetic fixture
(tests/fixtures/rea_jag_sample.json). REA is MIT; this consumes its JSON
contract, not its code.

DRAFT: validate against a real `rea ... --json` export before merge.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
safishamsiandClaude Opus 4.8 committed 2026-10-11 21:41:55 +01:00
1 parent a5ba60ddf6
commit d171ad8c55
4 files changed
+395 -4

No files matched your search

+23 -4
View File
@@ -3421,6 +3421,7 @@ def dispatch_command(cmd: str) -> None:
out_dir: Path | None = None
cli_postgres_dsn: str | None = None
cli_cargo: bool = False
cli_rea_path: str | None = None
cli_allow_partial: bool = False
# --allow-dedup-shrink: write a graph that is smaller because dedup
# merged nodes. A deleted file does not need this flag (#3774).
@@ -3549,6 +3550,10 @@ def dispatch_command(cmd: str) -> None:
elif a == "--cargo":
cli_cargo = True
i += 1
elif a == "--rea" and i + 1 < len(args):
cli_rea_path = args[i + 1]; i += 2
elif a.startswith("--rea="):
cli_rea_path = a.split("=", 1)[1]; i += 1
elif a == "--force":
force = True; i += 1
elif a == "--allow-partial":
@@ -3560,8 +3565,8 @@ def dispatch_command(cmd: str) -> None:
else:
i += 1
if not has_path and cli_postgres_dsn is None:
print("error: must specify a path to scan or a --postgres DSN", file=sys.stderr)
if not has_path and cli_postgres_dsn is None and cli_rea_path is None:
print("error: must specify a path to scan, a --postgres DSN, or a --rea graph", file=sys.stderr)
sys.exit(1)
if no_dedup and dedup_llm:
@@ -4404,13 +4409,27 @@ def dispatch_command(cmd: str) -> None:
print(f"[graphify extract] Cargo: {len(cargo_result['nodes'])} nodes, "
f"{len(cargo_result['edges'])} edges")
rea_result: dict = {"nodes": [], "edges": []}
if cli_rea_path is not None:
from graphify.rea_ingest import ingest_rea_jag
print(f"[graphify extract] ingesting REA application graph: {cli_rea_path}")
try:
import json as _json
rea_doc = _json.loads(Path(cli_rea_path).read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
print(f"error: cannot read --rea graph: {exc}", file=sys.stderr)
sys.exit(1)
rea_result = ingest_rea_jag(rea_doc, source_file=cli_rea_path)
print(f"[graphify extract] REA: {len(rea_result['nodes'])} nodes, "
f"{len(rea_result['edges'])} edges")
# Merge AST + semantic + pg_result + cargo_result. Order matters for deduplication: passing AST
# first means semantic node attributes win on collision (richer labels
# for symbols also referenced in docs). Hyperedges only come from the
# semantic side.
merged: dict = {
"nodes": list(ast_result.get("nodes", [])) + list(sem_result.get("nodes", [])) + list(pg_result.get("nodes", [])) + list(cargo_result.get("nodes", [])),
"edges": list(ast_result.get("edges", [])) + list(sem_result.get("edges", [])) + list(pg_result.get("edges", [])) + list(cargo_result.get("edges", [])),
"nodes": list(ast_result.get("nodes", [])) + list(sem_result.get("nodes", [])) + list(pg_result.get("nodes", [])) + list(cargo_result.get("nodes", [])) + list(rea_result.get("nodes", [])),
"edges": list(ast_result.get("edges", [])) + list(sem_result.get("edges", [])) + list(pg_result.get("edges", [])) + list(cargo_result.get("edges", [])) + list(rea_result.get("edges", [])),
"hyperedges": list(sem_result.get("hyperedges", [])),
"input_tokens": ast_result.get("input_tokens", 0) + sem_result.get("input_tokens", 0),
"output_tokens": ast_result.get("output_tokens", 0) + sem_result.get("output_tokens", 0),
+252
View File
@@ -0,0 +1,252 @@
"""rea_ingest.py — ingest REA's JavaScript Application Graph into Graphify.
REA (https://github.com/morluto/rea, "Reverse Engineer Anything") analyzes
shipped application bytes — native binaries, JavaScript/Electron bundles, .NET,
WASM — and emits a provider-neutral **JavaScript Application Graph** (JAG): a
canonical JSON graph of the application's structure with evidence attached to
every node and edge. Graphify turns code you *have source for* into a queryable
knowledge graph; this ingester lets you do the same for code you *don't* — feed
a JAG export in and `graphify query` / `path` / `explain` over a reverse-
engineered app.
Entry point:
ingest_rea_jag(doc: object, source_file: str = "") -> {"nodes": [...], "edges": [...]}
The result is endpoint-safe (every edge endpoint is a real node or a minted
``rea_external`` stub) so ``build_from_json`` keeps every edge.
Grounded in REA's documented JAG contract (docs/javascript-application-graph.md):
top-level ``nodes`` / ``edges`` / ``coverage`` / ``limitations``; each node has a
``kind``, display ``label``, and one or more ``observations``; each edge has
``source_node_id`` / ``target_node_id``, a ``relation`` from REA's fixed relation
vocabulary, and an epistemic state (``observed`` / ``inferred`` / ``unknown`` /
``unavailable``). Field-name aliases are accepted where the prose contract leaves
a name slightly ambiguous, so a minor schema revision degrades gracefully rather
than dropping the whole graph. REA is MIT-licensed; this consumes its JSON
*contract*, not its code.
NOTE: validated against a synthetic fixture built from the documented schema;
should be checked against a real ``rea ... --json`` export before release.
"""
from __future__ import annotations
from typing import Any
from graphify.extractors.base import _make_id
from graphify.security import sanitize_metadata
# REA node kinds that are structural code artifacts vs. conceptual boundaries.
# Everything not listed as a concept defaults to "code".
_REA_CONCEPT_KINDS = frozenset({
"package", "installer", "artifact", "asar entry", "asar_entry",
"browserwindow", "frame", "target", "contextbridge api",
"contextbridge_api", "ipc channel", "ipc_channel", "endpoint", "storage",
})
# REA's directed relation vocabulary -> Graphify's known relation set, so the
# analysis/affected passes understand the edges. The original REA relation is
# preserved verbatim in the edge ``context`` ("rea:<relation>").
_REA_RELATION_MAP = {
"contains": "contains",
"loads": "imports",
"imports": "imports",
"calls": "calls",
"invokes": "calls",
"sends": "calls",
"handles": "references",
"exposes": "references",
"maps_to": "references",
"persists_to": "references",
"observed_as": "references",
"changed_from": "references",
}
# REA confidence term -> a Graphify confidence_score.
_REA_CONFIDENCE_SCORE = {
"exact": 1.0, "high": 0.9, "medium": 0.7, "low": 0.5, "unknown": 0.3,
}
def _s(value: object, default: str = "") -> str:
return value if isinstance(value, str) and value else default
def _rea_node_id(raw_id: str) -> str:
"""Namespaced, build-safe Graphify id for a REA node (ids must be [a-z0-9_])."""
return _make_id("rea", raw_id)
def _node_kind(node: dict) -> str:
return _s(node.get("kind") or node.get("node_kind") or node.get("type"), "unknown")
def _node_label(node: dict, kind: str, raw_id: str) -> str:
return _s(node.get("label") or node.get("name"), f"{kind}:{raw_id.rsplit('_', 1)[-1]}")
def _edge_endpoints(edge: dict) -> tuple[str, str]:
src = _s(edge.get("source_node_id") or edge.get("source") or edge.get("from"))
tgt = _s(edge.get("target_node_id") or edge.get("target") or edge.get("to"))
return src, tgt
def _epistemic_state(entity: dict) -> str:
"""Strongest epistemic state of an entity (edge, or node via its observations)."""
direct = _s(entity.get("epistemic_state")).lower()
if direct:
return direct
best = ""
rank = {"observed": 3, "inferred": 2, "unknown": 1, "unavailable": 0}
for obs in entity.get("observations", []) or []:
if not isinstance(obs, dict):
continue
st = _s(obs.get("epistemic_state")).lower()
if st and rank.get(st, -1) > rank.get(best, -1):
best = st
return best
def _confidence(entity: dict, state: str) -> tuple[str, float]:
"""Map an epistemic state + REA confidence term to Graphify (confidence, score)."""
term = _s(entity.get("confidence")).lower()
for obs in entity.get("observations", []) or []:
if isinstance(obs, dict) and not term:
term = _s(obs.get("confidence")).lower()
# Only a directly observed fact earns EXTRACTED; everything else is INFERRED.
confidence = "EXTRACTED" if state == "observed" else "INFERRED"
default = 1.0 if state == "observed" else 0.7
score = _REA_CONFIDENCE_SCORE.get(term, default)
if confidence == "INFERRED":
score = min(score, 0.9) # inferred facts never claim certainty
return confidence, score
def _file_type(kind: str) -> str:
return "concept" if kind.lower() in _REA_CONCEPT_KINDS else "code"
def ingest_rea_jag(doc: object, source_file: str = "") -> dict[str, Any]:
"""Convert a REA JavaScript Application Graph into Graphify nodes and edges.
``doc`` is ``object`` because it arrives as arbitrary deserialized JSON from an
external tool; anything that is not the expected dict shape yields an empty
result rather than raising.
"""
nodes: list[dict[str, Any]] = []
edges: list[dict[str, Any]] = []
if not isinstance(doc, dict):
return {"nodes": nodes, "edges": edges}
raw_nodes = doc.get("nodes")
raw_edges = doc.get("edges")
if not isinstance(raw_nodes, list):
return {"nodes": nodes, "edges": edges}
host = _s(source_file) or f"rea:{_s(doc.get('graph_id'), 'graph')}"
# Graph-wide coverage/limitations are attached to the root nodes' metadata
# (the ingester contract is node/edge only, with no graph-level slot).
root_ids = {_s(r) for r in (doc.get("root_node_ids") or []) if isinstance(r, str)}
graph_coverage = _s(doc.get("coverage"))
graph_limitations = doc.get("limitations") if isinstance(doc.get("limitations"), list) else []
id_map: dict[str, str] = {}
seen_ids: set[str] = set()
# ---- pass 1: emit a node per REA entity ---------------------------------
for node in raw_nodes:
if not isinstance(node, dict):
continue
raw_id = _s(node.get("id") or node.get("node_id"))
if not raw_id:
continue
nid = _rea_node_id(raw_id)
id_map[raw_id] = nid
if nid in seen_ids:
continue
seen_ids.add(nid)
kind = _node_kind(node)
state = _epistemic_state(node)
meta: dict[str, Any] = {
"rea_kind": kind,
"rea_id": raw_id,
"rea_epistemic_state": state or "unknown",
}
authorities = [
_s(o.get("authority")) for o in (node.get("observations") or [])
if isinstance(o, dict) and _s(o.get("authority"))
]
if authorities:
meta["rea_authorities"] = sorted(set(authorities))
if raw_id in root_ids:
meta["rea_root"] = True
if graph_coverage:
meta["rea_coverage"] = graph_coverage
if graph_limitations:
meta["rea_limitations"] = graph_limitations
nodes.append({
"id": nid,
"label": _node_label(node, kind, raw_id),
"file_type": _file_type(kind),
"source_file": host,
"source_location": "",
"metadata": sanitize_metadata(meta),
})
# ---- pass 2: emit edges, minting external stubs so none dangle ----------
seen_edges: set[tuple[str, str, str]] = set()
for edge in raw_edges if isinstance(raw_edges, list) else []:
if not isinstance(edge, dict):
continue
raw_src, raw_tgt = _edge_endpoints(edge)
rea_rel = _s(edge.get("relation") or edge.get("kind"))
if not raw_src or not raw_tgt or not rea_rel:
continue
state = _epistemic_state(edge)
if state == "unavailable":
continue # an unavailable fact is not a relationship
src = id_map.get(raw_src)
tgt = id_map.get(raw_tgt)
# Endpoint-safety: mint a stub for an endpoint REA referenced but did not
# list as a node, so build_from_json keeps the edge.
for raw_ep, resolved in ((raw_src, src), (raw_tgt, tgt)):
if resolved is None:
stub = _rea_node_id(raw_ep)
id_map[raw_ep] = stub
if stub not in seen_ids:
seen_ids.add(stub)
nodes.append({
"id": stub,
"label": raw_ep.rsplit("_", 1)[-1] or raw_ep,
"file_type": "code",
"source_file": "",
"source_location": "",
"metadata": sanitize_metadata({"rea_external": True, "rea_id": raw_ep}),
})
src = id_map[raw_src]
tgt = id_map[raw_tgt]
if src == tgt:
continue # REA rejects self-edges; don't fabricate one
relation = _REA_RELATION_MAP.get(rea_rel.lower(), "references")
key = (src, tgt, relation)
if key in seen_edges:
continue
seen_edges.add(key)
confidence, score = _confidence(edge, state)
edges.append({
"source": src,
"target": tgt,
"relation": relation,
"confidence": confidence,
"confidence_score": score,
"source_file": host,
"source_location": "",
"weight": 1.0,
"context": f"rea:{rea_rel}",
"metadata": sanitize_metadata({
"rea_relation": rea_rel,
"rea_epistemic_state": state or "unknown",
}),
})
return {"nodes": nodes, "edges": edges}
+29
View File
@@ -0,0 +1,29 @@
{
"schema": "JavaScriptApplicationGraph",
"graph_id": "jag_demo",
"root_node_ids": ["jag_node_pkg"],
"coverage": "partial",
"limitations": ["dynamic IPC retained without a pairing edge"],
"nodes": [
{"id": "jag_node_pkg", "kind": "package", "label": "example.app", "observations": [{"authority": "artifact-bytes", "epistemic_state": "observed", "confidence": "exact"}]},
{"id": "jag_node_asar", "kind": "asar entry", "label": "app.asar", "observations": [{"authority": "artifact-bytes", "epistemic_state": "observed", "confidence": "exact"}]},
{"id": "jag_node_main", "kind": "electron main", "label": "main.js", "observations": [{"authority": "ast-analysis", "epistemic_state": "observed", "confidence": "high"}]},
{"id": "jag_node_bw", "kind": "browserwindow", "label": "BrowserWindow", "observations": [{"authority": "static-relationship-inference", "epistemic_state": "inferred", "confidence": "medium"}]},
{"id": "jag_node_preload", "kind": "preload", "label": "preload.js", "observations": [{"authority": "ast-analysis", "epistemic_state": "observed", "confidence": "high"}]},
{"id": "jag_node_cb", "kind": "contextBridge API", "label": "api.search", "observations": [{"authority": "ast-analysis", "epistemic_state": "observed", "confidence": "high"}]},
{"id": "jag_node_handler", "kind": "ipc handler", "label": "onSearch", "observations": [{"authority": "static-relationship-inference", "epistemic_state": "inferred", "confidence": "medium"}]},
{"id": "jag_node_chan", "kind": "ipc channel", "label": "search:query", "observations": [{"authority": "ast-analysis", "epistemic_state": "observed", "confidence": "high"}]},
{"id": "jag_node_native", "kind": "native add-on", "label": "fts.node", "observations": [{"authority": "ast-analysis", "epistemic_state": "observed", "confidence": "high"}]}
],
"edges": [
{"source_node_id": "jag_node_pkg", "target_node_id": "jag_node_asar", "relation": "contains", "epistemic_state": "observed", "confidence": "exact"},
{"source_node_id": "jag_node_main", "target_node_id": "jag_node_bw", "relation": "contains", "epistemic_state": "observed", "confidence": "high"},
{"source_node_id": "jag_node_bw", "target_node_id": "jag_node_preload", "relation": "loads", "epistemic_state": "inferred", "confidence": "medium"},
{"source_node_id": "jag_node_preload", "target_node_id": "jag_node_cb", "relation": "exposes", "epistemic_state": "inferred", "confidence": "medium"},
{"source_node_id": "jag_node_preload", "target_node_id": "jag_node_handler", "relation": "invokes", "epistemic_state": "inferred", "confidence": "low"},
{"source_node_id": "jag_node_handler", "target_node_id": "jag_node_chan", "relation": "handles", "epistemic_state": "inferred", "confidence": "medium"},
{"source_node_id": "jag_node_preload", "target_node_id": "jag_node_native", "relation": "imports", "epistemic_state": "observed", "confidence": "high"},
{"source_node_id": "jag_node_main", "target_node_id": "jag_node_missing_ext", "relation": "calls", "epistemic_state": "observed", "confidence": "high"},
{"source_node_id": "jag_node_preload", "target_node_id": "jag_node_cb", "relation": "exposes", "epistemic_state": "unavailable"}
]
}
+91
View File
@@ -0,0 +1,91 @@
"""Ingest REA's JavaScript Application Graph into a Graphify graph.
REA (morluto/rea) reverse-engineers shipped apps and emits a canonical
JavaScript Application Graph (nodes + evidence-bearing edges). `ingest_rea_jag`
maps that into Graphify's node/edge model so the result is queryable with
`graphify query`/`path`/`explain`. Built against REA's documented JAG contract
plus the synthetic fixture tests/fixtures/rea_jag_sample.json.
"""
from __future__ import annotations
import json
from pathlib import Path
from graphify.build import build_from_json
from graphify.rea_ingest import ingest_rea_jag
_FIXTURE = Path(__file__).parent / "fixtures" / "rea_jag_sample.json"
def _ingest():
doc = json.loads(_FIXTURE.read_text(encoding="utf-8"))
return ingest_rea_jag(doc, source_file="demo.jag.json")
def test_non_dict_input_yields_empty_result():
assert ingest_rea_jag(None) == {"nodes": [], "edges": []}
assert ingest_rea_jag("nope") == {"nodes": [], "edges": []}
assert ingest_rea_jag({"schema": "x"}) == {"nodes": [], "edges": []} # no nodes list
def test_nodes_and_edges_map_into_graphify():
res = _ingest()
labels = {n["label"] for n in res["nodes"]}
assert {"example.app", "preload.js", "fts.node", "search:query"} <= labels
# relation vocabulary is mapped to Graphify's known relations
relations = {e["relation"] for e in res["edges"]}
assert relations <= {"contains", "imports", "calls", "references"}
# the original REA relation is preserved in context for traceability
assert any(e["context"] == "rea:loads" for e in res["edges"])
assert any(e["context"] == "rea:invokes" for e in res["edges"])
def test_kind_maps_to_file_type():
res = _ingest()
by_label = {n["label"]: n for n in res["nodes"]}
# structural artifacts are code; process/IPC boundaries are concepts
assert by_label["preload.js"]["file_type"] == "code"
assert by_label["fts.node"]["file_type"] == "code"
assert by_label["example.app"]["file_type"] == "concept" # package
assert by_label["search:query"]["file_type"] == "concept" # ipc channel
def test_epistemic_state_drives_confidence():
res = _ingest()
by_ctx = {e["context"]: e for e in res["edges"]}
assert by_ctx["rea:contains"]["confidence"] == "EXTRACTED" # observed
assert by_ctx["rea:loads"]["confidence"] == "INFERRED" # inferred
# inferred edges never claim certainty
assert by_ctx["rea:loads"]["confidence_score"] <= 0.9
def test_unavailable_edge_is_dropped():
res = _ingest()
# the fixture's duplicate preload->contextBridge edge is epistemic "unavailable"
# and must not become a relationship; the observed/inferred ones still exist.
exposes = [e for e in res["edges"] if e["context"] == "rea:exposes"]
assert len(exposes) == 1
def test_external_endpoint_is_stubbed_not_dangling():
res = _ingest()
stubs = [n for n in res["nodes"] if n["metadata"].get("rea_external")]
assert len(stubs) == 1 # jag_node_missing_ext
node_ids = {n["id"] for n in res["nodes"]}
for e in res["edges"]:
assert e["source"] in node_ids and e["target"] in node_ids
def test_root_node_carries_graph_coverage_and_limitations():
res = _ingest()
root = next(n for n in res["nodes"] if n["metadata"].get("rea_root"))
assert root["metadata"]["rea_coverage"] == "partial"
assert root["metadata"]["rea_limitations"]
def test_build_from_json_accepts_the_ingested_graph():
res = _ingest()
G = build_from_json(res, directed=True)
# every edge endpoint resolves to a real node (nothing dangles)
assert G.number_of_nodes() == len(res["nodes"])
assert G.number_of_edges() >= 7