Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions forebear/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,12 +218,13 @@ async def list_assessments(k: str | None = None):

def do(g: Graph):
rows = g.assessments(kk)
verdicts: dict[str, str | None] = {}
for r in rows: # does the graph still give the saved verdict?
if r["k"] not in verdicts:
cur = assess(g, r["k"])
verdicts[r["k"]] = cur["verdict"] if cur else None
r["verdict_now"] = verdicts[r["k"]]
verdicts: dict[tuple[str, int], str | None] = {}
for r in rows: # does the graph still give the saved verdict, at the depth it was saved at?
key = (r["k"], r["depth"])
if key not in verdicts:
cur = assess(g, r["k"], r["depth"])
verdicts[key] = cur["verdict"] if cur else None
r["verdict_now"] = verdicts[key]
r["stale"] = bool(r["stale"] or r["verdict_now"] != r["verdict"])
return rows
return await run(do)
Expand Down Expand Up @@ -318,8 +319,8 @@ def do(g: Graph):
payload = {"verdict": a["verdict"], "signals": [{k2: s[k2] for k2 in ("code", "severity", "title", "chain")}
for s in a["signals"]],
"coverage": a["coverage"], "rules_version": a["rules_version"], "depth": a["depth"]}
aid = g.save_assessment(k, a["verdict"], payload, text, "template", flagged)
return {"id": aid, "verdict": a["verdict"], "flagged_recalls": flagged}
aid = g.save_assessment(k, a["verdict"], payload, text, "template", flagged, depth=a["depth"])
return {"id": aid, "verdict": a["verdict"], "depth": a["depth"], "flagged_recalls": flagged}
r = await run(do)
if r is None:
raise HTTPException(404, f"{k} is not in the graph")
Expand Down
73 changes: 57 additions & 16 deletions forebear/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
(:Company {name})
(:Recall {id, recall_number, event, classification, root_cause, design_related,
initiated, status, firm, reason, product, url})
(:Assessment {id, created_at, target_k, verdict, payload, memo, memo_source})
(:Assessment {id, created_at, target_k, verdict, depth, payload, memo, memo_source})

(Device)-[:CITES {kind: predicate|reference|mention, confidence, page, snippet, quote,
method, text_source, source_url, source_sha256, name_check, panel_check,
Expand Down Expand Up @@ -249,16 +249,19 @@ def citation(self, src: str, dst: str) -> dict | None:
return rows[0] if rows else None

def save_assessment(self, target_k: str, verdict: str, payload: dict, memo: str,
memo_source: str, recall_ids: list[str]) -> str:
memo_source: str, recall_ids: list[str], depth: int | None = None) -> str:
"""`depth` is the number of predicate generations the saved verdict was computed over; history recomputes
and checks staleness at that depth. Defaults to payload['depth'] when the payload carries it."""
aid = "A-" + uuid.uuid4().hex[:10]
depth = _assessment_depth(depth if depth is not None else payload.get("depth"))[0]
self.conn.execute(
"""MATCH (d:Device {k:$k})
CREATE (a:Assessment {id:$id, created_at: datetime(), target_k:$k, verdict:$verdict,
CREATE (a:Assessment {id:$id, created_at: datetime(), target_k:$k, verdict:$verdict, depth:$depth,
payload:$payload, memo:$memo, memo_source:$src})
CREATE (a)-[:ASSESSED]->(d)
WITH a UNWIND $recalls AS rid
MATCH (x:Recall {id: rid}) MERGE (a)-[:FLAGGED]->(x)""",
{"k": target_k, "id": aid, "verdict": verdict, "payload": json.dumps(payload),
{"k": target_k, "id": aid, "verdict": verdict, "depth": depth, "payload": json.dumps(payload),
"memo": memo, "src": memo_source, "recalls": recall_ids})
return aid

Expand Down Expand Up @@ -463,25 +466,63 @@ def recall_event_reach(self, event: str, depth: int = 3) -> dict:
return {"event": event, "recalled": devs, "descendants": desc}

def assessments(self, k: str | None = None, limit: int = 20) -> list[dict]:
"""Saved assessments, each with a `stale` flag: after it was saved, a citation somewhere in
the assessed device's ancestry (4 generations) was reviewed or AI-labelled, or a device in
that ancestry was (re-)ingested - so the saved verdict may no longer match the graph."""
"""Saved assessments, each with its `depth` and a `stale` flag: after it was saved, a citation leaving the
assessed device or an ancestor within that depth was reviewed or AI-labelled, or a device within that
depth was (re-)ingested - so the saved verdict may no longer match the graph. These are the edges and
devices assess() reads at that depth. `depth_source` says where the depth came from: 'recorded' on the
node, or for an assessment saved before depth was stored, 'legacy_payload' (the depth inside its saved
payload, which is the depth its verdict was computed at) or 'legacy_default' (neither: the API default 4)."""
rows = self.q(
"""MATCH (a:Assessment)-[:ASSESSED]->(d:Device)
WHERE $k IS NULL OR d.k = $k
RETURN a.id AS id, a.depth AS depth, a.payload AS payload, toString(a.created_at) AS created_at
ORDER BY created_at DESC LIMIT $n""", {"k": k, "n": limit})
if not rows:
return []
scoped = []
for r in rows:
if r["depth"] is not None:
depth, source = _assessment_depth(r["depth"])[0], "recorded"
else:
try:
legacy = json.loads(r["payload"] or "{}").get("depth")
except (TypeError, ValueError, AttributeError):
legacy = None
depth, ok = _assessment_depth(legacy)
source = "legacy_payload" if ok else "legacy_default"
scoped.append({"id": r["id"], "depth": depth, "source": source})
return self.q(
"""UNWIND $rows AS r
MATCH (a:Assessment {id: r.id})-[:ASSESSED]->(d:Device)
OPTIONAL MATCH (a)-[:FLAGGED]->(x:Recall)
WITH a, d, collect(x.id) AS flagged
OPTIONAL MATCH (d)-[:CITES*0..4]->(y:Device)-[c:CITES]->(:Device)
WHERE c.reviewed_at > a.created_at OR c.ai_at > a.created_at
WITH a, d, flagged, collect(DISTINCT y.k + '->' + endNode(c).k) AS changed_edges
OPTIONAL MATCH (d)-[:CITES*0..4]->(z:Device) WHERE z.ingested_live_at > a.created_at
WITH a, d, flagged, changed_edges, collect(DISTINCT z.k) AS reingested
WITH r, a, d, collect(x.id) AS flagged
OPTIONAL MATCH p = (d)-[:CITES*0..8]->(y:Device)-[c:CITES]->(:Device)
WHERE length(p) <= r.depth + 1 AND (c.reviewed_at > a.created_at OR c.ai_at > a.created_at)
WITH r, a, d, flagged, collect(DISTINCT y.k + '->' + endNode(c).k) AS changed_edges
OPTIONAL MATCH q = (d)-[:CITES*0..8]->(z:Device)
WHERE length(q) <= r.depth AND z.ingested_live_at > a.created_at
WITH r, a, d, flagged, changed_edges, collect(DISTINCT z.k) AS reingested
RETURN a.id AS id, toString(a.created_at) AS created_at, d.k AS k, d.name AS name,
a.verdict AS verdict, a.memo AS memo, a.memo_source AS memo_source, flagged,
a.verdict AS verdict, r.depth AS depth, r.source AS depth_source,
a.memo AS memo, a.memo_source AS memo_source, flagged,
changed_edges, reingested,
size(changed_edges) > 0 OR size(reingested) > 0 AS stale
ORDER BY created_at DESC LIMIT $n""", {"k": k, "n": limit})
return rows
ORDER BY created_at DESC""", {"rows": scoped})


ASSESSMENT_DEFAULT_DEPTH = 4 # what POST /api/assessments used when no depth was sent


def _assessment_depth(v) -> tuple[int, bool]:
"""(depth, valid): an assessment depth clamped to the 1-8 generations assess() traverses, or the API default
when `v` is missing or not an integer (booleans included)."""
if isinstance(v, bool) or not isinstance(v, (int, float, str)):
return ASSESSMENT_DEFAULT_DEPTH, False
try:
n = int(v)
except (ValueError, OverflowError):
return ASSESSMENT_DEFAULT_DEPTH, False
return max(1, min(n, 8)), True


def _clean(d: dict | None) -> dict | None:
Expand Down
13 changes: 10 additions & 3 deletions forebear/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,12 @@
"a person's review. Only a person's review in the app makes a link trusted or removes it.",
"inputSchema": {"type": "object", "properties": {"src": K, "dst": K, "status": {"type": "string", "enum": ["confirmed", "rejected", ""]},
"note": {"type": "string"}}, "required": ["src", "dst", "status"]}},
{"name": "save_assessment", "description": "Persist the current check as an (:Assessment) node linked to the device and its flagged recalls.",
"inputSchema": {"type": "object", "properties": {"k_number": K, "note": {"type": "string"}}, "required": ["k_number"]}},
{"name": "save_assessment", "description": "Persist the current check as an (:Assessment) node linked to the device and its flagged recalls. "
"`depth` is the number of predicate generations the saved verdict is computed over "
"(1-6, default 4); history rechecks the assessment at that depth.",
"inputSchema": {"type": "object", "properties": {"k_number": K, "note": {"type": "string"},
"depth": {"type": "integer", "minimum": 1, "maximum": 6, "default": 4}},
"required": ["k_number"]}},
{"name": "investigate", "description": "Run Forebear's autonomous investigation agent (NVIDIA-hosted LLM over the graph tools; labelled "
"deterministic fallback if inference is unavailable) on one device and wait for the report. "
"Returns the deterministic conclusion, recall totals, uncertainties, verified and rejected agent "
Expand Down Expand Up @@ -148,7 +152,10 @@ def call_tool(name: str, args: dict):
"status": args["status"], "note": args.get("note"),
"via": "mcp-client"})
if name == "save_assessment":
return _http("POST", "/api/assessments", json={"k": up(args["k_number"]), "note": args.get("note")})
depth = args.get("depth", 4)
if isinstance(depth, bool) or not isinstance(depth, int) or not 1 <= depth <= 6:
raise ValueError("depth must be an integer from 1 to 6")
return _http("POST", "/api/assessments", json={"k": up(args["k_number"]), "note": args.get("note"), "depth": depth})
if name == "investigate":
body = {"request": args["request"], "depth": int(args.get("generations", 4)), "mode": args.get("mode", "auto")}
if args.get("k_number"):
Expand Down
28 changes: 28 additions & 0 deletions tests/test_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,31 @@ def test_relate_native_mcp_read_cypher(real_copy):
body = json.loads(res[2]["result"]["content"][0]["text"])
assert body["rows"] == [{"p": "K113053", "n": 1}] # Z-1973-2021 (event 88058; Z-1957/1958 are event 88071)
assert res[3]["result"]["isError"] is True # writes refused on the read-only surface


def test_mcp_save_assessment_records_the_requested_depth(live_api):
"""K251770 reports no design-recall signal at depth 1 and REVIEW_LINEAGE from depth 2."""
call = lambda i, args: {"jsonrpc": "2.0", "id": i, "method": "tools/call", # noqa: E731
"params": {"name": "save_assessment", "arguments": {"k_number": "K251770", **args}}}
res = rpc_session([sys.executable, "-m", "forebear.mcp_server"], INIT + [
{"jsonrpc": "2.0", "id": 2, "method": "tools/list"},
call(3, {"depth": 1}), call(4, {"depth": 2}), call(5, {}), call(6, {"depth": 6}),
call(7, {"depth": 0}), call(8, {"depth": 7}), call(9, {"depth": "2"}), call(10, {"depth": True}),
call(11, {"depth": 1.5}),
], env=live_api)
tool = next(t for t in res[2]["result"]["tools"] if t["name"] == "save_assessment")
assert tool["inputSchema"]["properties"]["depth"] == {"type": "integer", "minimum": 1, "maximum": 6, "default": 4}
assert tool["inputSchema"]["required"] == ["k_number"]
out = {i: json.loads(res[i]["result"]["content"][0]["text"]) for i in (3, 4, 5, 6)}
assert {i: (o["depth"], o["verdict"]) for i, o in out.items()} == {
3: (1, "NO_DESIGN_RECALL_SIGNAL"), 4: (2, "REVIEW_LINEAGE"), 5: (4, "REVIEW_LINEAGE"), 6: (6, "REVIEW_LINEAGE")}
for i in (7, 8, 9, 10, 11): # rejected, never saved at another depth
assert res[i]["result"]["isError"] is True
assert "depth must be an integer from 1 to 6" in res[i]["result"]["content"][0]["text"]
import httpx
hist = {h["id"]: h for h in httpx.get(live_api["FOREBEAR_URL"] + "/api/assessments", params={"k": "K251770"}).json()}
assert len(hist) == 4 # the invalid calls saved nothing
for o in out.values():
h = hist[o["id"]]
assert (h["depth"], h["depth_source"], h["verdict"]) == (o["depth"], "recorded", o["verdict"])
assert h["verdict_now"] == h["verdict"] and h["stale"] is False
131 changes: 131 additions & 0 deletions tests/test_saved_assessment_depth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"""A saved assessment keeps the query depth it was computed at: history recomputes its verdict and checks staleness
at that depth, so an unchanged graph never makes it stale, while a change to evidence that depth reads still does.

Tiny graph lineage used here: K000004 -> K000003 -> K000002 (design-related Class I recall) -> K000001, and
K000004 -> K000008. At depth 1 K000004 reports no signal; from depth 2 the recall makes it REVIEW_LINEAGE.
"""
import importlib
import json

import pytest
from fastapi.testclient import TestClient

from conftest import build_tiny
from forebear.lineage import assess

K = "K000004"


def _legacy(g, aid, verdict, payload):
"""An assessment node as saved before depth was stored on it."""
g.conn.execute("""MATCH (d:Device {k:$k})
CREATE (a:Assessment {id:$id, created_at: datetime(), target_k:$k, verdict:$v, payload:$p,
memo:'m', memo_source:'template'})-[:ASSESSED]->(d)""",
{"k": K, "id": aid, "v": verdict, "p": payload})


@pytest.fixture
def tiny_api(tmp_path, monkeypatch):
path = tmp_path / "tiny.rl"
g = build_tiny(path)
assert [assess(g, K, d)["verdict"] for d in (1, 2, 4)] == \
["NO_DESIGN_RECALL_SIGNAL", "REVIEW_LINEAGE", "REVIEW_LINEAGE"]
_legacy(g, "A-legacy-p1", "NO_DESIGN_RECALL_SIGNAL", json.dumps({"verdict": "NO_DESIGN_RECALL_SIGNAL", "depth": 1}))
_legacy(g, "A-legacy-none", "REVIEW_LINEAGE", json.dumps({"verdict": "REVIEW_LINEAGE"}))
_legacy(g, "A-legacy-bad", "REVIEW_LINEAGE", "not json")
g.close()
monkeypatch.setenv("FOREBEAR_DB", str(path))
from forebear import api
importlib.reload(api)
with TestClient(api.app) as c:
yield c, path


def _history(c):
return {h["id"]: h for h in c.get("/api/assessments", params={"k": K}).json()}


def _save(c, depth):
r = c.post("/api/assessments", json={"k": K, "depth": depth})
assert r.status_code == 200
return r.json()


def test_each_depth_is_saved_and_unchanged_graph_is_not_stale(tiny_api):
c, _ = tiny_api
saved = {d: _save(c, d) for d in (1, 2, 4)}
assert {d: (s["depth"], s["verdict"]) for d, s in saved.items()} == {
1: (1, "NO_DESIGN_RECALL_SIGNAL"), 2: (2, "REVIEW_LINEAGE"), 4: (4, "REVIEW_LINEAGE")}
h = _history(c)
for d, s in saved.items():
row = h[s["id"]]
assert (row["depth"], row["depth_source"]) == (d, "recorded")
# recomputed at its own depth: the depth-1 verdict is not compared with the depth-4 one
assert row["verdict_now"] == row["verdict"] == s["verdict"]
assert row["stale"] is False and row["changed_edges"] == [] and row["reingested"] == []


def test_depth_is_stored_on_the_assessment_node(tiny_api):
c, _ = tiny_api
ids = {_save(c, d)["id"]: d for d in (1, 2, 4)}
from forebear import api # the API is the single writer: read through its store and thread
rows = c.portal.call(api.run, lambda g: g.q(
"MATCH (a:Assessment) WHERE a.id IN $ids RETURN a.id AS id, a.depth AS depth, a.payload AS p",
{"ids": list(ids)}))
assert {r["id"]: r["depth"] for r in rows} == ids
assert {r["id"]: json.loads(r["p"])["depth"] for r in rows} == ids


def test_a_change_within_the_saved_depth_makes_it_stale_and_one_beyond_does_not(tiny_api):
c, _ = tiny_api
ids = {d: _save(c, d)["id"] for d in (1, 2, 4)}
# K000002 -> K000001 leaves the generation-2 ancestor: read at depth 2 and 4, not at depth 1
assert c.post("/api/citation/review", json={"src": "K000002", "dst": "K000001", "status": "confirmed"}).status_code == 200
h = _history(c)
assert h[ids[1]]["stale"] is False and h[ids[1]]["changed_edges"] == []
for d in (2, 4):
assert h[ids[d]]["stale"] is True and h[ids[d]]["changed_edges"] == ["K000002->K000001"]
assert h[ids[d]]["verdict_now"] == h[ids[d]]["verdict"]


def test_a_relevant_citation_change_flags_every_depth_and_reports_the_new_verdict(tiny_api):
c, _ = tiny_api
ids = {d: _save(c, d)["id"] for d in (1, 2, 4)}
# rejecting the direct predicate removes the whole ancestry: relevant at every depth
assert c.post("/api/citation/review", json={"src": K, "dst": "K000003", "status": "rejected"}).status_code == 200
h = _history(c)
for d in (1, 2, 4):
assert h[ids[d]]["stale"] is True and f"{K}->K000003" in h[ids[d]]["changed_edges"]
assert h[ids[d]]["verdict_now"] == assess_now(c, d)
assert h[ids[2]]["verdict_now"] != h[ids[2]]["verdict"]
assert h[ids[4]]["verdict_now"] != h[ids[4]]["verdict"]


def assess_now(c, depth):
return c.get(f"/api/assess/{K}", params={"depth": depth}).json()["verdict"]


def test_legacy_assessments_use_the_payload_depth_or_the_old_default(tiny_api):
c, _ = tiny_api
h = _history(c)
# saved before depth was stored: the payload records the depth its verdict was computed at
assert (h["A-legacy-p1"]["depth"], h["A-legacy-p1"]["depth_source"]) == (1, "legacy_payload")
assert h["A-legacy-p1"]["verdict_now"] == "NO_DESIGN_RECALL_SIGNAL" and h["A-legacy-p1"]["stale"] is False
# no depth anywhere (or an unreadable payload): the API default the assessment was saved with
for aid in ("A-legacy-none", "A-legacy-bad"):
assert (h[aid]["depth"], h[aid]["depth_source"]) == (4, "legacy_default")
assert h[aid]["verdict_now"] == "REVIEW_LINEAGE" and h[aid]["stale"] is False
# and genuine changes still flag legacy records, scoped to their depth
c.post("/api/citation/review", json={"src": "K000002", "dst": "K000001", "status": "confirmed"})
h = _history(c)
assert h["A-legacy-p1"]["stale"] is False
assert h["A-legacy-none"]["stale"] is True and h["A-legacy-bad"]["stale"] is True


def test_depth_parsing_falls_back_safely():
from forebear.graph import _assessment_depth
assert _assessment_depth(2) == (2, True)
assert _assessment_depth("3") == (3, True)
assert _assessment_depth(0) == (1, True) and _assessment_depth(99) == (8, True)
for bad in (None, True, "x", [], {}, float("inf")):
assert _assessment_depth(bad) == (4, False)
Loading
Loading