dsh-auto-ontology 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,11 +12,17 @@ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
12
12
  const argv = process.argv.slice(2);
13
13
  const [cmd, ...rest] = argv;
14
14
 
15
+ const SUBCOMMANDS = { // named subcommands: strip the name, route the script
16
+ build: "build_ontology.py",
17
+ eval: "eval_evidence.py", // auto-ontology eval --from x.json [--n 20] [--seed 42]
18
+ validate: "validate_format.py", // auto-ontology validate ontologies/*.json
19
+ };
20
+ let script_file = SUBCOMMANDS[cmd] || "build_ontology.py";
15
21
  let pass;
16
- if (cmd === "build") {
22
+ if (SUBCOMMANDS[cmd]) {
17
23
  pass = rest;
18
24
  } else {
19
- pass = argv; // engine args pass through verbatim (build is the default)
25
+ pass = argv; // bare engine args pass through verbatim (build is the default)
20
26
  }
21
27
 
22
28
  // Artifacts land in the caller's cwd (the engine reads ONTOLOGY_HOME).
@@ -25,7 +31,7 @@ const env = {
25
31
  ONTOLOGY_HOME: path.join(process.cwd(), "ontologies"),
26
32
  };
27
33
 
28
- const r = spawnSync("python3", [path.join(root, "scripts", "build_ontology.py"), ...pass], {
34
+ const r = spawnSync("python3", [path.join(root, "scripts", script_file), ...pass], {
29
35
  stdio: "inherit",
30
36
  env,
31
37
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-auto-ontology",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Auto ontology construction for DeepSeek Harness — two-pass LLM pipeline (TBox schema from corpus, ABox assertions per document) with an evidence quote on every entity/relation, a type guard against silent drops, append-only incremental merge, conservative coreference, JSON-LD export and evidence-span queries. Zero-infra stdlib CLI + typed agent tools.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -71,7 +71,8 @@ def llm(sysmsg, user, json_out=True):
71
71
 
72
72
  def new_store(domain):
73
73
  return {"domain": domain, "entities": {}, "relations": {}, "conflicts": [],
74
- "flagged": [], "tbox_types": set(), "tbox_relations": {}, "merge_log": []}
74
+ "flagged": [], "tbox_types": set(), "tbox_relations": {}, "merge_log": [],
75
+ "certifications": {}, "suppressed": 0}
75
76
 
76
77
 
77
78
  def load_store(o):
@@ -100,8 +101,39 @@ def load_store(o):
100
101
  st["conflicts"] = list(o.get("conflicts", []))
101
102
  st["flagged"] = list(o.get("flagged_unknown_types", []))
102
103
  st["merge_log"] = list(o.get("merge_log", []))
104
+ st["certifications"] = dict(o.get("certifications", {}))
105
+ st["suppressed"] = 0
103
106
  return st
104
107
 
108
+ def certify(o, name, verdict, note=""):
109
+ """Human verdict on an entity (issue #13, the upstream Learn pillar,
110
+ evidence-first version): record travels WITH the ontology (portable artifact).
111
+ rejected — the (name, type) pair is suppressed in every later fold; the
112
+ original evidence stays in the certification record for audit. A different
113
+ type re-asserting the same name is a NEW assertion and re-enters (the
114
+ rejection was about that typing, not the string).
115
+ accepted — the entity is marked trusted; conflicts against it still get
116
+ recorded (they are never silently resolved), the mark is the human word."""
117
+ st = load_store(o)
118
+ k = _key(name)
119
+ e = st["entities"].get(k)
120
+ if e is None:
121
+ raise SystemExit(tt(f"no such entity: {name}", f"无此实体:{name}"))
122
+ o.setdefault("certifications", {})[k] = {
123
+ "name": e["name"], "type": e["type"], "verdict": verdict, "at":
124
+ dt.datetime.now().isoformat(timespec="seconds"), "note": note,
125
+ "evidence": e["evidences"][0] if e["evidences"] else {}}
126
+ if verdict == "reject":
127
+ del st["entities"][k]
128
+ st["relations"] = {rk: r for rk, r in st["relations"].items()
129
+ if _key(r["subject"]) != k and _key(r["object"]) != k}
130
+ o["abox"] = {"entities": sorted(st["entities"].values(), key=lambda x: x["name"].lower()),
131
+ "relations": sorted(st["relations"].values(),
132
+ key=lambda r: (r["subject"].lower(), r["predicate"]))}
133
+ o["stats"]["entities"] = len(st["entities"])
134
+ o["stats"]["relations"] = len(st["relations"])
135
+ return o
136
+
105
137
 
106
138
  def _fold_ev(evs, ev):
107
139
  if isinstance(ev, str):
@@ -113,10 +145,15 @@ def _fold_ev(evs, ev):
113
145
 
114
146
  def fold_entity(st, name, etype, quote, doc):
115
147
  """Append-only entity fold; the same name under a different type => conflict
116
- holding BOTH evidences — recorded, never silently resolved."""
148
+ holding BOTH evidences — recorded, never silently resolved. A rejected
149
+ certification suppresses the (name, type) pair — counted, never re-asserted."""
117
150
  k = _key(name)
118
151
  if not k:
119
152
  return
153
+ cert = st.get("certifications", {}).get(k)
154
+ if cert and cert.get("verdict") == "reject" and cert.get("type") == etype:
155
+ st["suppressed"] = st.get("suppressed", 0) + 1
156
+ return
120
157
  cur = st["entities"].get(k)
121
158
  if cur is None:
122
159
  st["entities"][k] = {"name": name, "type": etype, "aliases": [],
@@ -239,6 +276,64 @@ def to_markdown(o):
239
276
  return "\n".join(L)
240
277
 
241
278
 
279
+ def diff_ontologies(a, b):
280
+ """Run-layer diff (issue #14): what changed between two ontology artifacts,
281
+ at evidence granularity. Removed entities are reported with their cause when
282
+ knowable (certification rejection recorded in b)."""
283
+ ea = {e["name"]: e for e in a.get("abox", {}).get("entities", [])}
284
+ eb = {e["name"]: e for e in b.get("abox", {}).get("entities", [])}
285
+ ra = {(r["subject"], r["predicate"], r["object"]): r for r in a.get("abox", {}).get("relations", [])}
286
+ rb = {(r["subject"], r["predicate"], r["object"]): r for r in b.get("abox", {}).get("relations", [])}
287
+ certs_b = {c.get("name"): c for c in b.get("certifications", {}).values()}
288
+ d = {"entities_added": sorted(set(eb) - set(ea)),
289
+ "entities_removed": sorted(set(ea) - set(eb)),
290
+ "removal_causes": {n: ("certified-reject: " + certs_b[n]["note"]) if n in certs_b and certs_b[n]["verdict"] == "reject"
291
+ else "not re-asserted" for n in sorted(set(ea) - set(eb))},
292
+ "evidence_grown": {n: len(eb[n].get("evidences", [])) - len(ea[n].get("evidences", []))
293
+ for n in set(ea) & set(eb)
294
+ if len(eb[n].get("evidences", [])) != len(ea[n].get("evidences", []))},
295
+ "aliases_added": {n: [x for x in eb[n].get("aliases", []) if x not in ea[n].get("aliases", [])]
296
+ for n in set(ea) & set(eb) if set(eb[n].get("aliases", [])) - set(ea[n].get("aliases", []))},
297
+ "relations_added": sorted(set(rb) - set(ra)),
298
+ "relations_removed": sorted(set(ra) - set(rb)),
299
+ "conflicts_added": [c for c in b.get("conflicts", []) if c not in a.get("conflicts", [])],
300
+ "certifications_added": [c for c in b.get("certifications", {}).values()
301
+ if c["name"] not in {x.get("name") for x in a.get("certifications", {}).values()}],
302
+ "stats": {"a": a.get("stats", {}), "b": b.get("stats", {})}}
303
+ return d
304
+
305
+
306
+ def render_diff(d):
307
+ L = ["# Ontology diff"]
308
+ L.append(f"\n{d['stats']['a'].get('entities', '?')} → {d['stats']['b'].get('entities', '?')} entities · "
309
+ f"{d['stats']['a'].get('relations', '?')} → {d['stats']['b'].get('relations', '?')} relations\n")
310
+ if d["entities_added"]:
311
+ L.append("**Entities added**: " + ", ".join(d["entities_added"]))
312
+ if d["entities_removed"]:
313
+ L.append("**Entities removed**:")
314
+ L += [f"- {n} — {cause}" for n, cause in d["removal_causes"].items()]
315
+ if d["evidence_grown"]:
316
+ L.append("**Evidence grown**: " + ", ".join(f"{n} ({v:+d})" for n, v in d["evidence_grown"].items()))
317
+ if d["aliases_added"]:
318
+ L.append("**Aliases added**: " + ", ".join(f"{n} += {a}" for n, a in d["aliases_added"].items() if a))
319
+ if d["relations_added"]:
320
+ L.append(f"**Relations added** ({len(d['relations_added'])}):")
321
+ L += [f"- ({s}) -[{p}]-> ({o})" for s, p, o in d["relations_added"][:30]]
322
+ if d["relations_removed"]:
323
+ L.append(f"**Relations removed**: {len(d['relations_removed'])}")
324
+ if d["conflicts_added"]:
325
+ L.append("**New conflicts**:")
326
+ L += [f"- {c['entity']}: {' vs '.join(c['types'])}" for c in d["conflicts_added"]]
327
+ if d["certifications_added"]:
328
+ L.append("**Certifications**:")
329
+ L += [f"- {c['name']} → {c['verdict']}" + (f" ({c['note']})" if c.get("note") else "")
330
+ for c in d["certifications_added"]]
331
+ if not any([d["entities_added"], d["entities_removed"], d["relations_added"], d["relations_removed"],
332
+ d["evidence_grown"], d["conflicts_added"], d["certifications_added"], d["aliases_added"]]):
333
+ L.append("(no material changes)")
334
+ return "\n".join(L)
335
+
336
+
242
337
  def to_jsonld(o):
243
338
  """Ontology v2 JSON -> JSON-LD 1.1 (issue #9): entities as typed nodes with
244
339
  evidence, relations as reified statement nodes with subject/object refs.
@@ -279,8 +374,10 @@ def store_to_ontology(st, new_type_descs, provenance):
279
374
  "conflicts": st["conflicts"],
280
375
  "flagged_unknown_types": st["flagged"],
281
376
  "merge_log": st["merge_log"],
377
+ "certifications": st.get("certifications", {}),
282
378
  "stats": {"entities": len(ents), "relations": len(rels),
283
- "conflicts": len(st["conflicts"]), "flagged": len(st["flagged"])},
379
+ "conflicts": len(st["conflicts"]), "flagged": len(st["flagged"]),
380
+ "suppressed_by_certification": st.get("suppressed", 0)},
284
381
  }
285
382
 
286
383
 
@@ -394,6 +491,12 @@ def main():
394
491
  ap.add_argument("--domain", default=None, help="corpus domain description (schema pass)")
395
492
  ap.add_argument("--merge", default=None, help="existing ontology JSON to fold into (append-only)")
396
493
  ap.add_argument("--query", default=None, help="query mode: every assertion about X, with evidence")
494
+ ap.add_argument("--diff", nargs=2, metavar=("OLD", "NEW"),
495
+ help="diff two ontology artifacts at evidence granularity")
496
+ ap.add_argument("--certify", default=None, metavar="NAME",
497
+ help="certification mode: --certify NAME --verdict accept|reject [--note ...] [--from x.json]")
498
+ ap.add_argument("--verdict", choices=("accept", "reject"), default=None, help="verdict for --certify")
499
+ ap.add_argument("--note", default="", help="optional note recorded with a certification")
397
500
  ap.add_argument("--jsonld", action="store_true", help="export the ontology as JSON-LD 1.1 (with --from, or the newest artifact)")
398
501
  ap.add_argument("--html", action="store_true", help="render the ontology as a single-file HTML digest (with --save, or --from standalone)")
399
502
  ap.add_argument("--from", dest="frm", default=None, help="ontology file for --query (default: newest in outdir)")
@@ -406,6 +509,21 @@ def main():
406
509
  MAX_CALLS = args.max_calls
407
510
  t0 = time.time()
408
511
 
512
+ if args.diff:
513
+ a, b = (json.load(open(p)) for p in args.diff)
514
+ print(render_diff(diff_ontologies(a, b)))
515
+ return
516
+
517
+ if args.certify:
518
+ if not args.verdict:
519
+ sys.exit("--certify needs --verdict accept|reject")
520
+ path = args.frm or max(glob.glob(os.path.join(OUTDIR, "*.json")), key=os.path.getmtime)
521
+ o = certify(json.load(open(path)), args.certify, args.verdict, note=args.note)
522
+ out = os.path.join(OUTDIR, dt.datetime.now().strftime("%Y%m%d-%H%M%S") + "-certified.json")
523
+ json.dump(o, open(out, "w"), ensure_ascii=False, indent=1)
524
+ print(f"{args.certify} {args.verdict} -> {out}")
525
+ return
526
+
409
527
  if args.html and not args.docs:
410
528
  import render_html
411
529
  path = args.frm or max(glob.glob(os.path.join(OUTDIR, "*.json")), key=os.path.getmtime)
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env python3
2
+ """eval_evidence — the honest precision metric (issue #15, O4)
3
+
4
+ One number anyone can rerun: sample N assertions from an ontology
5
+ (deterministically, seed+ontology), and for each ask a model — given ONLY the
6
+ evidence quote and the source doc name — whether the quote supports the
7
+ assertion. precision = supported / sampled. This measures the plugin's core
8
+ claim ("every assertion carries supporting evidence"), not a leaderboard: no
9
+ enterprise stack, no hidden test set — the artifact under test is the file you
10
+ point at, the sampling is seeded, the model and settings print with the result.
11
+
12
+ Usage:
13
+ python3 scripts/eval_evidence.py --from ontologies/x.json [--n 20] [--seed 42]
14
+ auto-ontology eval --from ontologies/x.json # via the npm bin
15
+ """
16
+ import argparse, glob, json, os, random, re, subprocess, sys
17
+
18
+ KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
+ OUTDIR = os.environ.get("ONTOLOGY_HOME") or os.path.join(KIT, "ontologies")
20
+
21
+
22
+ def sample_assertions(o, n, seed):
23
+ """Deterministic sample across entities and relations — pure, CI-tested."""
24
+ def first_ev(x): # v2 evidences list, or the v1 single-evidence field
25
+ if x.get("evidences"):
26
+ return x["evidences"][0]
27
+ if x.get("evidence"):
28
+ return {"quote": x["evidence"], "doc": x.get("doc", "?")}
29
+ return {}
30
+ pool = []
31
+ for e in o.get("abox", {}).get("entities", []):
32
+ ev = first_ev(e)
33
+ pool.append({"kind": "entity", "assertion": f"{e['name']} is of type '{e['type']}'",
34
+ "quote": ev.get("quote", ""), "doc": ev.get("doc", "?")})
35
+ for r in o.get("abox", {}).get("relations", []):
36
+ ev = first_ev(r)
37
+ pool.append({"kind": "relation",
38
+ "assertion": f"{r['subject']} --{r['predicate']}--> {r['object']}",
39
+ "quote": ev.get("quote", ""), "doc": ev.get("doc", "?")})
40
+ pool = [p for p in pool if p["quote"]]
41
+ rng = random.Random(seed)
42
+ return (rng.sample(pool, n) if len(pool) >= n else pool), len(pool)
43
+
44
+
45
+ def judge(sample):
46
+ """One call: does the quote alone support the assertion? yes/no + reason."""
47
+ key = subprocess.run(["bash", "-c", 'grep -m1 "^export DEEPSEEK_API_KEY=" ~/.bashrc | cut -d= -f2'],
48
+ capture_output=True, text=True).stdout.strip().strip('"')
49
+ body = {"model": "deepseek-chat", "temperature": 0, "response_format": {"type": "json_object"},
50
+ "messages": [
51
+ {"role": "system", "content":
52
+ 'You audit ontology assertions. Given ONLY an evidence quote and the assertion it '
53
+ 'allegedly supports, output JSON {"supported": true|false, "reason": "<=20 words"}. '
54
+ 'Be strict: paraphrase is fine, but if the quote does not actually contain the fact '
55
+ 'asserted, it is not supported. Do not use outside knowledge.'},
56
+ {"role": "user", "content":
57
+ f"Assertion: {sample['assertion']}\nEvidence quote (from doc {sample['doc']}): "
58
+ f"\"{sample['quote']}\""}]}
59
+ r = subprocess.run(["curl", "-s", "-m", "120", "https://api.deepseek.com/chat/completions",
60
+ "-H", f"Authorization: Bearer {key}", "-H", "Content-Type: application/json",
61
+ "-d", json.dumps(body)], capture_output=True, text=True)
62
+ out = json.loads(r.stdout)["choices"][0]["message"]["content"]
63
+ return json.loads(re.sub(r"^```(json)?|```$", "", out.strip(), flags=re.M).strip())
64
+
65
+
66
+ def main():
67
+ ap = argparse.ArgumentParser()
68
+ ap.add_argument("--from", dest="frm", default=None)
69
+ ap.add_argument("--n", type=int, default=20)
70
+ ap.add_argument("--seed", type=int, default=42)
71
+ args = ap.parse_args()
72
+ path = args.frm or max(glob.glob(os.path.join(OUTDIR, "*.json")), key=os.path.getmtime)
73
+ o = json.load(open(path))
74
+ samples, pool = sample_assertions(o, args.n, args.seed)
75
+ if not samples:
76
+ sys.exit("no evidenced assertions to sample")
77
+ ok, rows = 0, []
78
+ for s in samples:
79
+ v = judge(s)
80
+ ok += bool(v.get("supported"))
81
+ rows.append((s, v))
82
+ precision = ok / len(samples)
83
+ print(f"# evidence-support precision · {path}")
84
+ print(f"sampled {len(samples)}/{pool} evidenced assertions · seed {args.seed} · deepseek-chat · temp 0\n")
85
+ for s, v in rows:
86
+ mark = "✓" if v.get("supported") else "✗"
87
+ print(f"{mark} [{s['kind']}] {s['assertion']}")
88
+ print(f' quote: "{s["quote"]}" ({s["doc"]}) — {v.get("reason", "")}')
89
+ print(f"\nprecision = {ok}/{len(samples)} = {precision:.0%}")
90
+ print("rerun: same artifact + same seed → same sample (judge temperature is 0). "
91
+ "This measures quote-support of the file you point at — not a leaderboard.")
92
+
93
+
94
+ if __name__ == "__main__":
95
+ main()
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env python3
2
+ """validate_format — evidence-linked ontology v0.1 conformance (issue #16).
3
+
4
+ Pure stdlib checks of the normative clauses in docs/FORMAT.md. Exit 1 with the
5
+ violation list when any check fails; quiet success otherwise.
6
+ """
7
+ import json, re, sys
8
+
9
+
10
+ def validate(o):
11
+ v = []
12
+ for k in ("domain", "built_at", "tbox", "abox", "stats"):
13
+ if k not in o:
14
+ v.append(f"missing top-level key: {k}")
15
+ tbox_types = {t.get("name") for t in o.get("tbox", {}).get("entity_types", [])}
16
+ abox = o.get("abox", {})
17
+ ents = abox.get("entities", [])
18
+ rels = abox.get("relations", [])
19
+ if not ents and not rels:
20
+ v.append("abox has no entities and no relations")
21
+ names = set()
22
+ for e in ents:
23
+ n = e.get("name")
24
+ if not n:
25
+ v.append("entity without a name")
26
+ continue
27
+ names.add(n)
28
+ if e.get("type") not in tbox_types:
29
+ v.append(f"entity {n!r}: type {e.get('type')!r} not in tbox")
30
+ evs = e.get("evidences") or []
31
+ if not evs or not any(x.get("quote") for x in evs):
32
+ v.append(f"entity {n!r}: no evidence quote (contract clause 2)")
33
+ for x in evs:
34
+ if not x.get("quote") or not x.get("doc"):
35
+ v.append(f"entity {n!r}: malformed evidence {x!r}")
36
+ for r in rels:
37
+ if not (r.get("subject") and r.get("predicate") and r.get("object")):
38
+ v.append(f"relation missing endpoint/predicate: {r!r}")
39
+ continue
40
+ evs = r.get("evidences") or []
41
+ if not evs or not any(x.get("quote") for x in evs):
42
+ v.append(f"relation {r['subject']}-{r['predicate']}->{r['object']}: no evidence quote (clause 3)")
43
+ for c in o.get("conflicts", []):
44
+ if len(c.get("types", {})) < 2:
45
+ v.append(f"conflict on {c.get('entity')!r} carries fewer than two typed sides (clause 4)")
46
+ for k, c in o.get("certifications", {}).items():
47
+ if c.get("verdict") not in ("accept", "reject"):
48
+ v.append(f"certification {k!r}: verdict must be accept|reject (clause 5)")
49
+ return v
50
+
51
+
52
+ def main():
53
+ if len(sys.argv) < 2:
54
+ sys.exit("usage: validate_format.py <ontology.json> [...]")
55
+ bad = 0
56
+ for p in sys.argv[1:]:
57
+ try:
58
+ v = validate(json.load(open(p)))
59
+ except Exception as exc:
60
+ print(f"✗ {p}: unreadable ({exc})")
61
+ bad += 1
62
+ continue
63
+ if v:
64
+ bad += 1
65
+ print(f"✗ {p}:")
66
+ for x in v[:10]:
67
+ print(f" - {x}")
68
+ else:
69
+ print(f"✓ {p} conforms to evidence-linked ontology v0.1")
70
+ sys.exit(1 if bad else 0)
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()