dsh-auto-ontology 0.0.1 → 0.2.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 vicfei
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,9 +1,26 @@
1
1
  # dsh-auto-ontology
2
2
 
3
- > Auto ontology construction, natively on DeepSeek Harness: feed documents, get a typed ontology (TBox + ABox) where **every entity and relation carries its source quote.** No evidence, no assertion; unknown types flagged, never silently dropped.
4
- >
5
- > Implements the concept of [NVIDIA/auto-ontology](https://github.com/NVIDIA/auto-ontology); independent community project, not affiliated.
3
+ **Auto ontology construction with evidence, for DeepSeek Harness** — feed it
4
+ documents, get a typed ontology (TBox + ABox) where every entity and relation
5
+ carries its source quote. No evidence, no assertion; unknown types are flagged,
6
+ never silently dropped.
6
7
 
7
- **Status: name reserved — first release in development.**
8
+ ```bash
9
+ npm i -g dsh-auto-ontology
10
+ auto-ontology build --docs ~/my-corpus/*.md --domain "internal design docs" --save
11
+ ```
8
12
 
9
- Engine and docs: https://github.com/vicfei/dsh-auto-ontology
13
+ - Zero-infra: `python3` (stdlib) + a DeepSeek key you already have. No Docker,
14
+ no database — the deliberate opposite of the enterprise-metadata stacks.
15
+ - Two-pass pipeline: TBox schema from corpus samples → per-document ABox
16
+ assertions, each with an evidence span.
17
+ - Outputs: typed JSON (every assertion + evidence), zero-dep SVG cluster graph,
18
+ markdown digest.
19
+ - Register the DSH skill:
20
+ `ln -s "$(npm root -g)/dsh-auto-ontology/skills/dsh-auto-ontology" ~/.dsh/skills/dsh-auto-ontology`
21
+
22
+ Implements the concept of [NVIDIA/auto-ontology](https://github.com/NVIDIA/auto-ontology)
23
+ (13.3k★, Apache-2.0) natively for DSH — clean-room, zero upstream code, not
24
+ affiliated. **Not investment/enterprise advice.**
25
+
26
+ Full docs: [github.com/vicfei/dsh-auto-ontology](https://github.com/vicfei/dsh-auto-ontology)
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ // dsh-auto-ontology CLI — a JS shell spawning the bundled Python engine
3
+ // (the dsh-laya sidecar precedent, proven across the family).
4
+ //
5
+ // auto-ontology build --docs <dir-or-glob> --domain "..." --save [--lang zh]
6
+ // auto-ontology --docs ... (build is the default subcommand)
7
+ import { spawnSync } from "node:child_process";
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
12
+ const argv = process.argv.slice(2);
13
+ const [cmd, ...rest] = argv;
14
+
15
+ let pass;
16
+ if (cmd === "build") {
17
+ pass = rest;
18
+ } else {
19
+ pass = argv; // engine args pass through verbatim (build is the default)
20
+ }
21
+
22
+ // Artifacts land in the caller's cwd (the engine reads ONTOLOGY_HOME).
23
+ const env = {
24
+ ...process.env,
25
+ ONTOLOGY_HOME: path.join(process.cwd(), "ontologies"),
26
+ };
27
+
28
+ const r = spawnSync("python3", [path.join(root, "scripts", "build_ontology.py"), ...pass], {
29
+ stdio: "inherit",
30
+ env,
31
+ });
32
+ process.exit(r.status ?? 1);
package/build.mjs ADDED
@@ -0,0 +1,14 @@
1
+ // prepack: stage the engine from the repo (npm/ never commits staged copies —
2
+ // publish always picks up the current tree; sweep __pycache__ like the family recipe)
3
+ import { cpSync, rmSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const here = path.dirname(fileURLToPath(import.meta.url));
8
+ const repo = path.resolve(here, "..");
9
+
10
+ rmSync(path.join(here, "scripts"), { recursive: true, force: true });
11
+ cpSync(path.join(repo, "scripts"), path.join(here, "scripts"), { recursive: true });
12
+ cpSync(path.join(repo, "LICENSE"), path.join(here, "LICENSE"));
13
+ rmSync(path.join(here, "scripts", "__pycache__"), { recursive: true, force: true });
14
+ console.log("staged scripts/ LICENSE from repo root");
@@ -0,0 +1,9 @@
1
+ # dsh-auto-ontology bundle layer (0.2.0): a real plugin insert.
2
+ #
3
+ # The patch inserts the plugin into the profile's layer stack; the module
4
+ # (lib/index.js) then registers the agent tools (ontology_build, ontology_query)
5
+ # on ctx.tools via @deepseek-ai/dsh-tools. The skill stays discoverable via
6
+ # dsh-skill-filesystem; the CLI stays on PATH via npm bin.
7
+ - insert:
8
+ - id: dsh-auto-ontology
9
+ name: 'dsh-auto-ontology'
package/lib/index.js ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * dsh-auto-ontology host plugin (0.2.0, issue #11): the ontology engine as typed tools.
3
+ *
4
+ * Registers two agent tools on `ctx.tools` via @deepseek-ai/dsh-tools:
5
+ * ontology_build — two-pass build over a document corpus (evidence on every
6
+ * assertion, type guard, coref, append-only merge)
7
+ * ontology_query — every assertion about a term, with its evidence spans
8
+ *
9
+ * The tools spawn the bundled Python engine; artifacts land under the calling
10
+ * process's cwd (./ontologies/), exactly like the CLI.
11
+ */
12
+ import { spawnSync } from "node:child_process";
13
+ import path from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { defineTool } from "@deepseek-ai/dsh-tools";
16
+
17
+ export const name = "auto-ontology";
18
+ export const inject = ["tools"];
19
+
20
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
21
+
22
+ function run(args, timeoutMs = 600_000) {
23
+ const env = { ...process.env,
24
+ ONTOLOGY_HOME: path.join(process.cwd(), "ontologies") };
25
+ const r = spawnSync("python3", [path.join(ROOT, "scripts", "build_ontology.py"), ...args],
26
+ { encoding: "utf8", timeout: timeoutMs, env, maxBuffer: 16 * 1024 * 1024 });
27
+ if (r.error) throw new Error(`build_ontology: ${r.error.message}`);
28
+ if (r.status !== 0) throw new Error(`build_ontology exited ${r.status}: ${(r.stderr || "").slice(-400)}`);
29
+ return (r.stdout || "").trim();
30
+ }
31
+
32
+ const LANG = { type: "string", enum: ["en", "zh"], description: "Output language (default en)." };
33
+
34
+ export async function apply(ctx) {
35
+ ctx.tools.register(defineTool({
36
+ name: "ontology_build",
37
+ description:
38
+ "Build an ontology from a document corpus: a TBox schema from sampled docs, then per-document " +
39
+ "ABox assertions where EVERY entity and relation carries a verbatim evidence quote (no evidence, " +
40
+ "no assertion; unknown types are flagged, never silently dropped). Conservative coreference merges " +
41
+ "certain mentions (aliases recorded); append-only --merge folds new docs into an existing ontology " +
42
+ "without touching prior evidence; the same name under different types becomes a conflict entry " +
43
+ "holding both evidences. Artifacts: typed JSON (+ evidence), SVG cluster graph, markdown digest " +
44
+ "under ./ontologies/. Takes ~10s + ~2s per document.",
45
+ parameters: {
46
+ docs: { type: "string", required: true, description: "Document directory or glob, e.g. 'docs/*.md'." },
47
+ domain: { type: "string", required: true, description: "Corpus domain description for the schema pass." },
48
+ merge: { type: "string", description: "Existing ontology JSON to fold into (append-only), e.g. ontologies/xxx.json." },
49
+ sample: { type: "number", description: "Docs sampled for the schema pass (default 4)." },
50
+ max_calls: { type: "number", description: "Cost guard: abort beyond this many LLM calls." },
51
+ lang: LANG,
52
+ },
53
+ output: {
54
+ schema: { type: "object", additionalProperties: false,
55
+ properties: { summary: { type: "string", required: true } } },
56
+ render: (_args, value) => [{ type: "text", text: value.summary }],
57
+ },
58
+ execute(args) {
59
+ const extra = ["--save",
60
+ ...(args.merge ? ["--merge", args.merge] : []),
61
+ ...(args.sample ? ["--sample", String(args.sample)] : []),
62
+ ...(args.max_calls ? ["--max-calls", String(args.max_calls)] : []),
63
+ ...(args.lang ? ["--lang", args.lang] : [])];
64
+ return { summary: run(["--docs", args.docs, "--domain", args.domain, ...extra]) };
65
+ },
66
+ }));
67
+
68
+ ctx.tools.register(defineTool({
69
+ name: "ontology_query",
70
+ description:
71
+ "Query the newest ontology (or a given one): every entity and relation touching a term — by name, " +
72
+ "alias, or relation endpoint — each with ALL of its evidence spans (verbatim quotes + source docs). " +
73
+ "The audit surface of the evidence-linked ontology.",
74
+ parameters: {
75
+ term: { type: "string", required: true, description: "Entity name, alias, or relation endpoint." },
76
+ from: { type: "string", description: "Ontology JSON path (default: newest under ./ontologies/)." },
77
+ },
78
+ output: {
79
+ schema: { type: "object", additionalProperties: false,
80
+ properties: { result: { type: "string", required: true } } },
81
+ render: (_args, value) => [{ type: "text", text: value.result }],
82
+ },
83
+ execute(args) {
84
+ return { result: run(["--query", args.term, ...(args.from ? ["--from", args.from] : [])], 60_000) };
85
+ },
86
+ }));
87
+ }
package/package.json CHANGED
@@ -1,10 +1,55 @@
1
1
  {
2
2
  "name": "dsh-auto-ontology",
3
- "version": "0.0.1",
4
- "description": "Auto ontology construction for DeepSeek Harness — two-pass LLM pipeline (TBox schema from corpus, ABox assertions per document) with evidence quotes on every entity/relation and type-guard against silent drops. Implements the concept of NVIDIA/auto-ontology. Name reserved; first release in development.",
5
- "keywords": ["deepseek-harness", "dsh", "dsh-plugin", "auto-ontology", "ontology", "knowledge-graph", "llm-extraction", "evidence-grounding"],
6
- "repository": {"type": "git", "url": "git+https://github.com/vicfei/dsh-auto-ontology.git"},
3
+ "version": "0.2.0",
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
+ "type": "module",
6
+ "bin": {
7
+ "auto-ontology": "bin/auto-ontology.js"
8
+ },
9
+ "scripts": {
10
+ "prepack": "node build.mjs"
11
+ },
12
+ "engines": {
13
+ "node": "^20.19.0 || >=22.0.0"
14
+ },
15
+ "dsh": {
16
+ "bundle": {
17
+ "patch": "./cordis.patch.yml"
18
+ },
19
+ "manifestVersion": 1
20
+ },
21
+ "files": [
22
+ "bin",
23
+ "lib",
24
+ "skills",
25
+ "scripts",
26
+ "cordis.patch.yml",
27
+ "build.mjs",
28
+ "LICENSE"
29
+ ],
30
+ "keywords": [
31
+ "deepseek-harness",
32
+ "dsh",
33
+ "dsh-plugin",
34
+ "auto-ontology",
35
+ "ontology",
36
+ "knowledge-graph",
37
+ "llm-extraction",
38
+ "evidence-grounding"
39
+ ],
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/vicfei/dsh-auto-ontology.git"
43
+ },
7
44
  "homepage": "https://github.com/vicfei/dsh-auto-ontology#readme",
45
+ "bugs": {
46
+ "url": "https://github.com/vicfei/dsh-auto-ontology/issues"
47
+ },
8
48
  "license": "MIT",
9
- "author": "vicfei"
10
- }
49
+ "author": "vicfei",
50
+ "main": "./lib/index.js",
51
+ "peerDependencies": {
52
+ "@deepseek-ai/cordis": "^4.0.0",
53
+ "@deepseek-ai/dsh-tools": ">=0.0.1-rc.1"
54
+ }
55
+ }
@@ -0,0 +1,516 @@
1
+ #!/usr/bin/env python3
2
+ """Auto ontology construction engine (the NVIDIA auto-ontology concept, native to DSH)
3
+
4
+ Upstream auto-ontology (13.3k★, Apache-2.0) builds governed semantic layers from
5
+ enterprise metadata. This plugin implements the document-corpus slot: a two-pass
6
+ LLM pipeline in a zero-infra stdlib CLI, with the family's difference — **evidence
7
+ tracing**: every entity/relation carries a verbatim evidence span ("no evidence, no
8
+ assertion"), and a type guard flags unknown types instead of silently dropping them.
9
+
10
+ O2 engine (v2): one fold-based store handles fresh builds, incremental merges,
11
+ coreference, and conflicts (issues #5 #6 #7 #8):
12
+ build: TBox schema from a corpus sample (--sample) -> per-document ABox
13
+ fold: entities/relations accumulate append-only; the same name under a
14
+ different TYPE becomes a conflict entry holding BOTH evidences —
15
+ flagged for review, never silently resolved
16
+ coref: one LLM pass clusters mentions of the same real-world thing; merges
17
+ record aliases and union evidence (provenance kept)
18
+ merge: --merge folds a new build into an existing ontology; prior evidence
19
+ is never edited or dropped (append-only across runs)
20
+ cost: per-call usage accounting + --max-calls hard cap; every artifact
21
+ carries provenance (model/temp/elapsed/calls/tokens)
22
+
23
+ Usage:
24
+ python3 scripts/build_ontology.py --docs <dir_or_glob> --domain "..." --save [--lang zh]
25
+ python3 scripts/build_ontology.py --docs <new> --domain "..." --merge ontologies/old.json --save
26
+ python3 scripts/build_ontology.py --query "WrenAI" [--from ontologies/x.json]
27
+ """
28
+ import argparse, datetime as dt, glob, json, math, os, re, subprocess, sys, time
29
+
30
+ KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
31
+
32
+ # Output language: English by default (international-first), --lang zh / ONTOLOGY_LANG for Chinese
33
+ LANG = os.environ.get("ONTOLOGY_LANG") or "en"
34
+ def tt(en, zh):
35
+ return en if LANG == "en" else zh
36
+
37
+ # npm CLI form lands artifacts in the caller's cwd via ONTOLOGY_HOME (repo default unchanged)
38
+ OUTDIR = os.environ.get("ONTOLOGY_HOME") or os.path.join(KIT, "ontologies")
39
+
40
+ COST = {"calls": 0, "in": 0, "out": 0}
41
+ MAX_CALLS = None
42
+
43
+
44
+ def _key(s):
45
+ """Name-matching key: case/punctuation-insensitive."""
46
+ return re.sub(r"[^a-z0-9]+", "", str(s).lower())
47
+
48
+
49
+ def llm(sysmsg, user, json_out=True):
50
+ if MAX_CALLS is not None and COST["calls"] >= MAX_CALLS:
51
+ raise SystemExit(f"cost guard: {MAX_CALLS} LLM calls reached (--max-calls)")
52
+ key = subprocess.run(["bash", "-c", 'grep -m1 "^export DEEPSEEK_API_KEY=" ~/.bashrc | cut -d= -f2'],
53
+ capture_output=True, text=True).stdout.strip().strip('"')
54
+ body = {"model": "deepseek-chat", "temperature": 0,
55
+ "messages": [{"role": "system", "content": sysmsg}, {"role": "user", "content": user}]}
56
+ if json_out:
57
+ body["response_format"] = {"type": "json_object"}
58
+ r = subprocess.run(["curl", "-s", "-m", "180", "https://api.deepseek.com/chat/completions",
59
+ "-H", f"Authorization: Bearer {key}", "-H", "Content-Type: application/json",
60
+ "-d", json.dumps(body)], capture_output=True, text=True)
61
+ parsed = json.loads(r.stdout)
62
+ txt = parsed["choices"][0]["message"]["content"]
63
+ COST["calls"] += 1
64
+ u = parsed.get("usage") or {}
65
+ COST["in"] += int(u.get("prompt_tokens") or 0)
66
+ COST["out"] += int(u.get("completion_tokens") or 0)
67
+ return json.loads(re.sub(r"^```(json)?|```$", "", txt.strip(), flags=re.M).strip()) if json_out else txt
68
+
69
+
70
+ # ── the fold store (pure; unit-tested in CI) ────────────────────────────────
71
+
72
+ def new_store(domain):
73
+ return {"domain": domain, "entities": {}, "relations": {}, "conflicts": [],
74
+ "flagged": [], "tbox_types": set(), "tbox_relations": {}, "merge_log": []}
75
+
76
+
77
+ def load_store(o):
78
+ """v1 or v2 ontology JSON -> store (legacy single-evidence fields synthesized into lists)."""
79
+ st = new_store(o.get("domain", "?"))
80
+ for t in o.get("tbox", {}).get("entity_types", []):
81
+ st["tbox_types"].add(t["name"])
82
+ for r in o.get("tbox", {}).get("relation_types", []):
83
+ st["tbox_relations"][(r.get("name"), r.get("domains"), r.get("ranges"))] = r
84
+ for e in o.get("abox", {}).get("entities", []):
85
+ evs = e.get("evidences") or [{"quote": e.get("evidence", ""), "doc": e.get("doc", "?")}]
86
+ docs = set(e.get("docs", [])) | ({e["doc"]} if e.get("doc") and e["doc"] != "?" else set())
87
+ st["entities"][_key(e["name"])] = {"name": e["name"], "type": e["type"],
88
+ "aliases": list(e.get("aliases", [])),
89
+ "docs": sorted(docs), "evidences": []}
90
+ for ev in evs:
91
+ _fold_ev(st["entities"][_key(e["name"])]["evidences"], ev)
92
+ for r in o.get("abox", {}).get("relations", []):
93
+ evs = r.get("evidences") or [{"quote": r.get("evidence", ""), "doc": r.get("doc", "?")}]
94
+ docs = set(r.get("docs", [])) | ({r["doc"]} if r.get("doc") and r["doc"] != "?" else set())
95
+ k = (_key(r["subject"]), r["predicate"], _key(r["object"]))
96
+ st["relations"][k] = {"subject": r["subject"], "predicate": r["predicate"], "object": r["object"],
97
+ "docs": sorted(docs), "evidences": []}
98
+ for ev in evs:
99
+ _fold_ev(st["relations"][k]["evidences"], ev)
100
+ st["conflicts"] = list(o.get("conflicts", []))
101
+ st["flagged"] = list(o.get("flagged_unknown_types", []))
102
+ st["merge_log"] = list(o.get("merge_log", []))
103
+ return st
104
+
105
+
106
+ def _fold_ev(evs, ev):
107
+ if isinstance(ev, str):
108
+ ev = {"quote": ev, "doc": "?"}
109
+ q, d = ev.get("quote", ""), ev.get("doc", "?")
110
+ if q and not any(e["quote"] == q for e in evs):
111
+ evs.append({"quote": q, "doc": d})
112
+
113
+
114
+ def fold_entity(st, name, etype, quote, doc):
115
+ """Append-only entity fold; the same name under a different type => conflict
116
+ holding BOTH evidences — recorded, never silently resolved."""
117
+ k = _key(name)
118
+ if not k:
119
+ return
120
+ cur = st["entities"].get(k)
121
+ if cur is None:
122
+ st["entities"][k] = {"name": name, "type": etype, "aliases": [],
123
+ "docs": [doc] if doc != "?" else [],
124
+ "evidences": [{"quote": quote, "doc": doc}]}
125
+ return
126
+ if cur["type"] != etype:
127
+ st["conflicts"].append({"entity": cur["name"], "types": {
128
+ cur["type"]: cur["evidences"][0] if cur["evidences"] else {"quote": "", "doc": "?"},
129
+ etype: {"quote": quote, "doc": doc}}})
130
+ return
131
+ _fold_ev(cur["evidences"], {"quote": quote, "doc": doc})
132
+ if doc != "?":
133
+ cur["docs"] = sorted(set(cur["docs"]) | {doc})
134
+
135
+
136
+ def fold_relation(st, subject, predicate, obj, quote, doc, alias_map=None):
137
+ if alias_map: # canonicalize endpoints through the coref result before folding
138
+ subject = alias_map.get(_key(subject), subject)
139
+ obj = alias_map.get(_key(obj), obj)
140
+ if not (subject and predicate and obj):
141
+ return
142
+ k = (_key(subject), predicate, _key(obj))
143
+ cur = st["relations"].get(k)
144
+ if cur is None:
145
+ st["relations"][k] = {"subject": subject, "predicate": predicate, "object": obj,
146
+ "docs": [doc] if doc != "?" else [],
147
+ "evidences": [{"quote": quote, "doc": doc}]}
148
+ return
149
+ _fold_ev(cur["evidences"], {"quote": quote, "doc": doc})
150
+ if doc != "?":
151
+ cur["docs"] = sorted(set(cur["docs"]) | {doc})
152
+
153
+
154
+ def apply_aliases(st, alias_pairs):
155
+ """Coref result [(canonical, alias)]: merge alias entities into canonical (aliases
156
+ recorded, evidence unioned); existing relations re-pointed. Returns merge records."""
157
+ merged, alias_map = [], {}
158
+ for canonical, alias in alias_pairs:
159
+ kc, ka = _key(canonical), _key(alias)
160
+ if kc == ka or ka not in st["entities"] or kc not in st["entities"]:
161
+ continue
162
+ c, a = st["entities"][kc], st["entities"][ka]
163
+ if c["type"] != a["type"]:
164
+ continue # a cross-type mention is a conflict, not a coref
165
+ c["aliases"] = sorted(set(c["aliases"]) | {a["name"]} | set(a["aliases"]))
166
+ for ev in a["evidences"]:
167
+ _fold_ev(c["evidences"], ev)
168
+ c["docs"] = sorted(set(c["docs"]) | set(a["docs"]))
169
+ del st["entities"][ka]
170
+ alias_map[ka] = c["name"]
171
+ merged.append({"canonical": c["name"], "alias": a["name"], "docs": a["docs"]})
172
+ for k in list(st["relations"]): # re-point existing relations at canonical names
173
+ r = st["relations"][k]
174
+ r["subject"] = alias_map.get(_key(r["subject"]), r["subject"])
175
+ r["object"] = alias_map.get(_key(r["object"]), r["object"])
176
+ nk = (_key(r["subject"]), r["predicate"], _key(r["object"]))
177
+ if nk != k:
178
+ tgt = st["relations"].pop(k)
179
+ if nk in st["relations"]:
180
+ cur = st["relations"][nk]
181
+ for ev in tgt["evidences"]:
182
+ _fold_ev(cur["evidences"], ev)
183
+ cur["docs"] = sorted(set(cur["docs"]) | set(tgt["docs"]))
184
+ else:
185
+ st["relations"][nk] = tgt
186
+ return merged, alias_map
187
+
188
+
189
+ def query_ontology(o, term):
190
+ """Every assertion touching `term` (name, alias, or endpoint) with its evidence spans."""
191
+ k = _key(term)
192
+ hits = {"entities": [], "relations": []}
193
+ for e in o.get("abox", {}).get("entities", []):
194
+ if k in (_key(e["name"]), *[_key(a) for a in e.get("aliases", [])]):
195
+ hits["entities"].append(e)
196
+ for r in o.get("abox", {}).get("relations", []):
197
+ if k in (_key(r["subject"]), _key(r["object"])):
198
+ hits["relations"].append(r)
199
+ return hits
200
+
201
+
202
+ def to_markdown(o):
203
+ """Ontology v2 -> shareable markdown digest (issue #12): stats + provenance,
204
+ conflicts table, entities by type, relations with evidence quotes."""
205
+ from collections import defaultdict
206
+ st = o.get("stats", {})
207
+ prov = o.get("provenance", {})
208
+ L = [f"# Ontology · {o.get('domain', '?')}", "",
209
+ f"- **{st.get('entities', 0)} entities · {st.get('relations', 0)} relations · "
210
+ f"{st.get('conflicts', 0)} conflicts · {st.get('flagged', 0)} unknown types flagged**",
211
+ f"- provenance: {prov.get('model', '?')} · {prov.get('calls', '?')} calls · "
212
+ f"{prov.get('tokens_in', 0):,} in / {prov.get('tokens_out', 0):,} out tokens · "
213
+ f"{prov.get('elapsed_s', '?')}s · built {o.get('built_at', '?')}", ""]
214
+ if o.get("conflicts"):
215
+ L += ["## Conflicts (both evidences kept, awaiting review)", "",
216
+ "| Entity | Types | Evidence A | Evidence B |", "|---|---|---|---|"]
217
+ for c in o["conflicts"][:20]:
218
+ t1, t2 = list(c["types"].items())[:2]
219
+ L.append(f"| {c['entity']} | {t1[0]} / {t2[0]} | "
220
+ f"\"{t1[1].get('quote', '')[:50]}\" ({t1[1].get('doc', '?')}) | "
221
+ f"\"{t2[1].get('quote', '')[:50]}\" ({t2[1].get('doc', '?')}) |")
222
+ L.append("")
223
+ by_type = defaultdict(list)
224
+ for e in o.get("abox", {}).get("entities", []):
225
+ by_type[e["type"]].append(e)
226
+ L.append("## Entities")
227
+ for t, es in sorted(by_type.items()):
228
+ L.append(f"\n### {t} ({len(es)})")
229
+ for e in es[:40]:
230
+ al = f" · aka {', '.join(e['aliases'])}" if e.get("aliases") else ""
231
+ ev = e["evidences"][0]["quote"] if e.get("evidences") else ""
232
+ L.append(f"- **{e['name']}**{al} — \"{ev[:70]}\" ({', '.join(e.get('docs', [])[:3])})")
233
+ L += ["", "## Relations", "", "| Subject | Predicate | Object | Evidence |", "|---|---|---|---|"]
234
+ for r in o.get("abox", {}).get("relations", [])[:200]:
235
+ ev = r["evidences"][0]["quote"] if r.get("evidences") else ""
236
+ L.append(f"| {r['subject']} | {r['predicate']} | {r['object']} | \"{ev[:50]}\" |")
237
+ L += ["", "> Every assertion carries its evidence span in the JSON; this page is the digest. "
238
+ "Not investment/enterprise advice."]
239
+ return "\n".join(L)
240
+
241
+
242
+ def to_jsonld(o):
243
+ """Ontology v2 JSON -> JSON-LD 1.1 (issue #9): entities as typed nodes with
244
+ evidence, relations as reified statement nodes with subject/object refs.
245
+ @vocab is a stable placeholder namespace — evidence stays first-class."""
246
+ import hashlib
247
+ def eid(name):
248
+ return "urn:dshao:entity:" + re.sub(r"[^a-z0-9]+", "-", str(name).lower()).strip("-")
249
+ def rid(r):
250
+ h = hashlib.sha1(f"{r['subject']}|{r['predicate']}|{r['object']}".encode()).hexdigest()[:10]
251
+ return f"urn:dshao:rel:{h}"
252
+ ctx = {"@vocab": "https://dsh-auto-ontology.dev/vocab/",
253
+ "name": "https://schema.org/name",
254
+ "aliases": {"@id": "https://dsh-auto-ontology.dev/vocab/alias", "@container": "@set"},
255
+ "evidence": {"@id": "https://dsh-auto-ontology.dev/vocab/evidence", "@container": "@list"}}
256
+ graph = []
257
+ for e in o.get("abox", {}).get("entities", []):
258
+ graph.append({"@id": eid(e["name"]), "@type": e["type"], "name": e["name"],
259
+ "aliases": e.get("aliases", []), "evidence": e.get("evidences", [])})
260
+ for r in o.get("abox", {}).get("relations", []):
261
+ graph.append({"@id": rid(r), "@type": r["predicate"],
262
+ "subject": {"@id": eid(r["subject"]), "name": r["subject"]},
263
+ "object": {"@id": eid(r["object"]), "name": r["object"]},
264
+ "evidence": r.get("evidences", [])})
265
+ return {"@context": ctx, "@graph": graph,
266
+ "dshao:domain": o.get("domain"), "dshao:built_at": o.get("built_at")}
267
+
268
+
269
+ def store_to_ontology(st, new_type_descs, provenance):
270
+ ents = sorted(st["entities"].values(), key=lambda e: e["name"].lower())
271
+ rels = sorted(st["relations"].values(), key=lambda r: (r["subject"].lower(), r["predicate"]))
272
+ return {
273
+ "domain": st["domain"], "built_at": dt.datetime.now().isoformat(timespec="seconds"),
274
+ "provenance": provenance,
275
+ "tbox": {"entity_types": [{"name": t, "desc": new_type_descs.get(t, "")}
276
+ for t in sorted(st["tbox_types"])],
277
+ "relation_types": list(st["tbox_relations"].values())},
278
+ "abox": {"entities": ents, "relations": rels},
279
+ "conflicts": st["conflicts"],
280
+ "flagged_unknown_types": st["flagged"],
281
+ "merge_log": st["merge_log"],
282
+ "stats": {"entities": len(ents), "relations": len(rels),
283
+ "conflicts": len(st["conflicts"]), "flagged": len(st["flagged"])},
284
+ }
285
+
286
+
287
+ # ── pipeline ────────────────────────────────────────────────────────────────
288
+
289
+ P_TBOX = {
290
+ "en": ("You are an ontology engineer. Extract the ontology schema (TBox) from the corpus sample. Output JSON: "
291
+ '{"entity_types":[{"name":"...","desc":"..."}],"relation_types":[{"name":"...","domains":"TypeA","ranges":"TypeB","desc":"..."}]}. '
292
+ "Type names in English snake_case; write every desc in English. Extract only what the corpus genuinely supports — prefer fewer, truer types."),
293
+ "zh": ("你是本体工程师。从语料样本抽取本体模式(TBox)。输出 JSON:"
294
+ '{"entity_types":[{"name":"...","desc":"..."}],"relation_types":[{"name":"...","domains":"类型A","ranges":"类型B","desc":"..."}]}'
295
+ "。类型名用英文 snake_case,desc 用中文。只抽取语料真实支撑的,宁缺毋滥。"),
296
+ }
297
+ P_ABOX = {
298
+ "en": ("You are an ontology instance extractor. From the document, extract entity and relation instances (ABox) based on the given TBox. "
299
+ "Discipline: every instance must carry evidence=a verbatim quote from the document (<=40 chars); types must come from the TBox; "
300
+ "when unsure, do not extract. Output JSON: "
301
+ '{"entities":[{"name":"...","type":"...","evidence":"..."}],'
302
+ '"relations":[{"subject":"...","predicate":"...","object":"...","evidence":"..."}]}'),
303
+ "zh": ("你是本体实例抽取器。基于给定 TBox 从文档抽取实体与关系实例(ABox)。"
304
+ "**纪律**:每条实例必须附 evidence=文档原文引文(不超过40字);类型必须取自 TBox;"
305
+ "不确定的不抽。输出 JSON:"
306
+ '{"entities":[{"name":"...","type":"...","evidence":"..."}],'
307
+ '"relations":[{"subject":"...","predicate":"...","object":"...","evidence":"..."}]}'),
308
+ }
309
+ P_COREF = {
310
+ "en": ("You resolve entity mentions in an ontology. Given entity names (with types), output JSON "
311
+ '{"pairs":[{"canonical":"...","alias":"..."}]} where alias is clearly the SAME real-world '
312
+ "thing as canonical under a different mention (abbreviation, casing, prefix). Merge ONLY "
313
+ "when certain; when arguable, do not merge. Never pair entities of different types."),
314
+ "zh": ("你在本体中做实体提及消解。给定实体名(含类型),输出 JSON "
315
+ '{"pairs":[{"canonical":"...","alias":"..."}]}——alias 与 canonical 须确定是同一现实事物'
316
+ "(缩写/大小写/前缀差异)。只有确定才合并,可争议的不合;不同类型绝不配对。"),
317
+ }
318
+
319
+
320
+ def build(docs, domain, base=None, sample=4):
321
+ st = base if base is not None else new_store(domain)
322
+ tbox = llm(P_TBOX[LANG],
323
+ tt(f"Domain: {domain}\nCorpus sample:\n" + "\n\n".join(d["text"][:1500] for d in docs[:sample]),
324
+ f"领域:{domain}\n语料样本:\n" + "\n\n".join(d["text"][:1500] for d in docs[:sample])))
325
+ known = {e["name"] for e in tbox.get("entity_types", [])}
326
+ new_type_descs = {e["name"]: e.get("desc", "") for e in tbox.get("entity_types", [])
327
+ if e["name"] not in st["tbox_types"]}
328
+ st["tbox_types"] |= known
329
+ for r in tbox.get("relation_types", []):
330
+ st["tbox_relations"][(r.get("name"), r.get("domains"), r.get("ranges"))] = r
331
+
332
+ per_doc = []
333
+ for d in docs:
334
+ out = llm(P_ABOX[LANG],
335
+ tt(f"TBox:\n{json.dumps(tbox, ensure_ascii=False)}\n\nDocument ({d['path']}):\n{d['text']}",
336
+ f"TBox:{json.dumps(tbox, ensure_ascii=False)}\n\n文档({d['path']}):\n{d['text']}"))
337
+ per_doc.append((d, out))
338
+ for e in out.get("entities", []):
339
+ if not e.get("name"):
340
+ continue
341
+ if e.get("type") in known:
342
+ fold_entity(st, e["name"], e["type"], e.get("evidence", ""), d["path"])
343
+ else:
344
+ st["flagged"].append({**e, "doc": d["path"]}) # type guard — never silently dropped
345
+
346
+ merged_aliases, alias_map = [], {}
347
+ names = [f"{e['name']} ({e['type']})" for e in st["entities"].values()]
348
+ if len(names) >= 2:
349
+ pairs = llm(P_COREF[LANG], tt(f"Domain: {domain}\nEntities:\n" + "\n".join(names),
350
+ f"领域:{domain}\n实体:\n" + "\n".join(names)))
351
+ merged_aliases, alias_map = apply_aliases(st, [(p.get("canonical"), p.get("alias"))
352
+ for p in pairs.get("pairs", [])
353
+ if p.get("canonical") and p.get("alias")])
354
+ for d, out in per_doc: # relations fold AFTER coref so endpoints are canonical
355
+ for r in out.get("relations", []):
356
+ fold_relation(st, r.get("subject"), r.get("predicate"), r.get("object"),
357
+ r.get("evidence", ""), d["path"], alias_map=alias_map)
358
+ return st, new_type_descs, merged_aliases
359
+
360
+
361
+ def _write_svg(path, o, domain):
362
+ ents, rels = o["abox"]["entities"], o["abox"]["relations"]
363
+ by_type = {}
364
+ for e in ents:
365
+ by_type.setdefault(e["type"], []).append(e)
366
+ colors = ["#2456c4", "#c23531", "#2f8a4c", "#8a5fc2", "#b07a2a", "#2a8a8a"]
367
+ nodes, cx, cy = [], 400, 340
368
+ clusters = list(by_type.items())[:6]
369
+ for ci, (t, es) in enumerate(clusters):
370
+ r0, ang0 = 60 + ci * 45, ci * 2 * math.pi / max(len(clusters), 1)
371
+ gx, gy = cx + r0 * 1.9 * math.cos(ang0), cy + r0 * 1.5 * math.sin(ang0)
372
+ for i, e in enumerate(es[:10]):
373
+ a = 2 * math.pi * i / max(len(es[:10]), 1)
374
+ nodes.append((e["name"][:14], gx + 52 * math.cos(a), gy + 40 * math.sin(a), colors[ci % 6]))
375
+ svg = [f'<svg xmlns="http://www.w3.org/2000/svg" width="860" height="700" font-family="monospace">',
376
+ f'<text x="10" y="16" font-size="13">{domain} · {len(ents)} entities / {len(rels)} relations</text>']
377
+ nm = {n[0]: (n[1], n[2]) for n in nodes}
378
+ for r in rels:
379
+ if r["subject"][:14] in nm and r["object"][:14] in nm:
380
+ x1, y1 = nm[r["subject"][:14]]
381
+ x2, y2 = nm[r["object"][:14]]
382
+ svg.append(f'<line x1="{x1:.0f}" y1="{y1:.0f}" x2="{x2:.0f}" y2="{y2:.0f}" stroke="#99a" stroke-width="0.7"/>')
383
+ for name, x, y, c in nodes:
384
+ svg.append(f'<circle cx="{x:.0f}" cy="{y:.0f}" r="4" fill="{c}"/>'
385
+ f'<text x="{x + 6:.0f}" y="{y + 3:.0f}" font-size="9" fill="#345">{name}</text>')
386
+ svg.append("</svg>")
387
+ open(path, "w").write("".join(svg))
388
+
389
+
390
+ def main():
391
+ global LANG, MAX_CALLS
392
+ ap = argparse.ArgumentParser()
393
+ ap.add_argument("--docs", default=None, help="directory or glob, e.g. '~/dsh-*/README.md'")
394
+ ap.add_argument("--domain", default=None, help="corpus domain description (schema pass)")
395
+ ap.add_argument("--merge", default=None, help="existing ontology JSON to fold into (append-only)")
396
+ ap.add_argument("--query", default=None, help="query mode: every assertion about X, with evidence")
397
+ ap.add_argument("--jsonld", action="store_true", help="export the ontology as JSON-LD 1.1 (with --from, or the newest artifact)")
398
+ ap.add_argument("--html", action="store_true", help="render the ontology as a single-file HTML digest (with --save, or --from standalone)")
399
+ ap.add_argument("--from", dest="frm", default=None, help="ontology file for --query (default: newest in outdir)")
400
+ ap.add_argument("--sample", type=int, default=4, help="docs sampled for the TBox schema pass")
401
+ ap.add_argument("--max-calls", type=int, default=None, help="cost guard: abort beyond this many LLM calls")
402
+ ap.add_argument("--save", action="store_true")
403
+ ap.add_argument("--lang", choices=("en", "zh"), default=LANG, help="output language (default en)")
404
+ args = ap.parse_args()
405
+ LANG = args.lang
406
+ MAX_CALLS = args.max_calls
407
+ t0 = time.time()
408
+
409
+ if args.html and not args.docs:
410
+ import render_html
411
+ path = args.frm or max(glob.glob(os.path.join(OUTDIR, "*.json")), key=os.path.getmtime)
412
+ out = os.path.splitext(path)[0] + ".html"
413
+ open(out, "w", encoding="utf-8").write(render_html.render(to_markdown(json.load(open(path)))))
414
+ print(f"html -> {out}")
415
+ return
416
+
417
+ if args.jsonld:
418
+ path = args.frm or max(glob.glob(os.path.join(OUTDIR, "*.json")), key=os.path.getmtime)
419
+ out = os.path.splitext(path)[0] + ".jsonld"
420
+ json.dump(to_jsonld(json.load(open(path))), open(out, "w"), ensure_ascii=False, indent=1)
421
+ print(f"jsonld -> {out}")
422
+ return
423
+
424
+ if args.query:
425
+ path = args.frm or max(glob.glob(os.path.join(OUTDIR, "*.json")), key=os.path.getmtime)
426
+ hits = query_ontology(json.load(open(path)), args.query)
427
+ print(f"# {args.query} — {path}")
428
+ for e in hits["entities"]:
429
+ print(f"\n[{e['type']}] {e['name']}" +
430
+ (f" (aliases: {', '.join(e['aliases'])})" if e.get("aliases") else ""))
431
+ for ev in e.get("evidences", []):
432
+ print(f' | {ev["doc"]}: "{ev["quote"]}"')
433
+ for r in hits["relations"]:
434
+ print(f"\n({r['subject']}) -[{r['predicate']}]-> ({r['object']})")
435
+ for ev in r.get("evidences", []):
436
+ print(f' | {ev["doc"]}: "{ev["quote"]}"')
437
+ if not hits["entities"] and not hits["relations"]:
438
+ print(tt("no assertions matched", "无匹配断言"))
439
+ return
440
+
441
+ if not args.docs or not args.domain:
442
+ sys.exit(tt("--docs and --domain are required for a build", "构建需要 --docs 与 --domain"))
443
+ paths = sorted(glob.glob(os.path.expanduser(args.docs))) if "*" in args.docs else \
444
+ sorted(glob.glob(os.path.join(args.docs, "*")))
445
+ docs = []
446
+ for p in paths:
447
+ try:
448
+ docs.append({"path": os.path.basename(os.path.dirname(p)) or p,
449
+ "text": open(p, errors="ignore").read()[:6000]})
450
+ except OSError:
451
+ pass
452
+ if not docs:
453
+ sys.exit(tt("no documents matched", "无文档"))
454
+ print(tt(f"corpus: {len(docs)} doc(s) · domain: {args.domain}",
455
+ f"语料:{len(docs)} 篇 · 领域:{args.domain}"), file=sys.stderr)
456
+
457
+ base, prior_stats = None, None
458
+ if args.merge:
459
+ base = load_store(json.load(open(args.merge)))
460
+ prior_stats = {k: len(base[k]) for k in ("entities", "relations", "conflicts")}
461
+ print(tt(f"merging into {args.merge} (append-only)", f"增量并入 {args.merge}(append-only)"), file=sys.stderr)
462
+
463
+ st, new_type_descs, corefed = build(docs, args.domain, base=base, sample=max(1, args.sample))
464
+ if corefed:
465
+ st["merge_log"].append({"ran_at": dt.datetime.now().isoformat(timespec="seconds"),
466
+ "coref_merges": corefed})
467
+ if prior_stats:
468
+ st["merge_log"][-1] if st["merge_log"] else st["merge_log"].append({})
469
+ st["merge_log"][-1].update({"merged_into": args.merge,
470
+ "added_docs": len(docs),
471
+ "entities_before": prior_stats["entities"],
472
+ "entities_after": len(st["entities"])})
473
+ prov = {"model": "deepseek-chat", "temperature": 0, "elapsed_s": round(time.time() - t0),
474
+ "calls": COST["calls"], "tokens_in": COST["in"], "tokens_out": COST["out"],
475
+ "docs_this_run": len(docs), "merged_from": bool(args.merge)}
476
+ o = store_to_ontology(st, new_type_descs, prov)
477
+
478
+ print(f"\n## Ontology build · {args.domain}\n")
479
+ print(tt(f"- Entity types {len(o['tbox']['entity_types'])} · entities {o['stats']['entities']} · "
480
+ f"relations {o['stats']['relations']} · conflicts {o['stats']['conflicts']} · "
481
+ f"unknown types flagged {o['stats']['flagged']}",
482
+ f"- 实体类型 {len(o['tbox']['entity_types'])} · 实体 {o['stats']['entities']} · "
483
+ f"关系 {o['stats']['relations']} · 冲突 {o['stats']['conflicts']} · "
484
+ f"未知类型拦截 {o['stats']['flagged']}"))
485
+ print(tt(f"- provenance: {prov['calls']} calls · {prov['tokens_in']:,} in / {prov['tokens_out']:,} out tokens · {prov['elapsed_s']}s",
486
+ f"- 溯源:{prov['calls']} 次调用 · {prov['tokens_in']:,} 入 / {prov['tokens_out']:,} 出 · {prov['elapsed_s']}s"))
487
+ for c in o["conflicts"][:6]:
488
+ print(f" ⚔ conflict: {c['entity']} typed " + " vs ".join(c["types"]) +
489
+ tt(" — both evidences kept, awaiting review", " —— 双方证据保全,待复核"))
490
+ for r in o["abox"]["relations"][:10]:
491
+ ev = r["evidences"][0]["quote"] if r["evidences"] else ""
492
+ print(f" - R: ({r['subject']}) -[{r['predicate']}]-> ({r['object']}) | ev: {ev[:40]}")
493
+
494
+ if args.save:
495
+ os.makedirs(OUTDIR, exist_ok=True)
496
+ base_path = os.path.join(OUTDIR, dt.datetime.now().strftime("%Y%m%d-%H%M"))
497
+ json.dump(o, open(base_path + ".json", "w"), ensure_ascii=False, indent=1)
498
+ _write_svg(base_path + ".svg", o, args.domain)
499
+ if args.html:
500
+ try:
501
+ import render_html
502
+ open(base_path + ".html", "w", encoding="utf-8").write(render_html.render(to_markdown(o)))
503
+ except Exception as exc:
504
+ print(f"⚠ html render skipped ({type(exc).__name__})", file=sys.stderr)
505
+ open(base_path + ".md", "w").write(tt(
506
+ f"# Ontology · {args.domain}\n\nEntities {o['stats']['entities']} · relations {o['stats']['relations']} · "
507
+ f"conflicts {o['stats']['conflicts']} · unknown types flagged {o['stats']['flagged']}.\n"
508
+ f"Evidence lives in the JSON; provenance: {prov['calls']} calls, {prov['elapsed_s']}s.\n",
509
+ f"# 本体 · {args.domain}\n\n实体 {o['stats']['entities']} · 关系 {o['stats']['relations']} · "
510
+ f"冲突 {o['stats']['conflicts']} · 未知类型拦截 {o['stats']['flagged']}。\n"
511
+ f"证据随 JSON;溯源:{prov['calls']} 次调用,{prov['elapsed_s']}s。\n"))
512
+ print(f"\n→ {base_path}.json / .svg / .md", file=sys.stderr)
513
+
514
+
515
+ if __name__ == "__main__":
516
+ main()
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env python3
2
+ """render_html — IC-MEMO → single-file HTML (issue #4, R3)
3
+
4
+ One static page: sidebar table of contents, the yaml head as a highlighted block,
5
+ sections, tables (guest critiques), and the footer — no frameworks, no external
6
+ assets, shareable as a single file; readable in a browser, on a phone, in print.
7
+
8
+ A deliberately small Markdown subset, enough for IC-MEMO structure: headings,
9
+ fenced code blocks, tables, lists, bold/inline-code, hr, blockquotes, paragraphs.
10
+
11
+ Usage:
12
+ python3 scripts/render_html.py memos/DEMO-2026-11-16-guests.md # → <name>.html
13
+ python3 scripts/render_html.py memo.md -o out.html
14
+ """
15
+ import argparse, html, os, re, sys
16
+
17
+
18
+ def esc(s):
19
+ return html.escape(s, quote=False)
20
+
21
+
22
+ def inline(s):
23
+ s = esc(s)
24
+ s = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", s)
25
+ s = re.sub(r"(?<!\w)\*(?!\s)([^*]+?)\*(?!\w)", r"<em>\1</em>", s)
26
+ s = re.sub(r"`([^`]+)`", r"<code>\1</code>", s)
27
+ return s
28
+
29
+
30
+ def slug(s):
31
+ return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-") or "s"
32
+
33
+
34
+ def render(md, title=None):
35
+ lines = md.splitlines()
36
+ out, toc, in_code, code_buf, table_buf, para_buf = [], [], False, [], [], []
37
+ title = title or (re.match(r"#\s+(.+)", next((l for l in lines if l.startswith("# ")), "")).group(1)
38
+ if any(l.startswith("# ") for l in lines) else "IC-MEMO")
39
+
40
+ def flush_para():
41
+ if para_buf:
42
+ out.append("<p>" + inline(" ".join(para_buf)) + "</p>")
43
+ para_buf.clear()
44
+
45
+ def flush_table():
46
+ if not table_buf:
47
+ return
48
+ rows = [[c.strip() for c in r.strip().strip("|").split("|")] for r in table_buf]
49
+ if len(rows) > 1 and set("".join(rows[1])) <= set("-: "):
50
+ rows.pop(1)
51
+ t = ["<table><thead><tr>" + "".join(f"<th>{inline(c)}</th>" for c in rows[0]) + "</tr></thead><tbody>"]
52
+ for r in rows[1:]:
53
+ t.append("<tr>" + "".join(f"<td>{inline(c)}</td>" for c in r) + "</tr>")
54
+ t.append("</tbody></table>")
55
+ out.append("".join(t))
56
+ table_buf.clear()
57
+
58
+ for line in lines:
59
+ if line.strip().startswith("```"):
60
+ flush_para(); flush_table()
61
+ if in_code:
62
+ out.append('<pre class="yaml">' + esc("\n".join(code_buf)) + "</pre>")
63
+ code_buf.clear()
64
+ in_code = not in_code
65
+ continue
66
+ if in_code:
67
+ code_buf.append(line)
68
+ continue
69
+ if line.strip().startswith("|"):
70
+ flush_para()
71
+ table_buf.append(line)
72
+ continue
73
+ flush_table()
74
+ h = re.match(r"^(#{1,3})\s+(.*)", line)
75
+ if h:
76
+ flush_para()
77
+ level = len(h.group(1))
78
+ sid = slug(h.group(2))
79
+ if level <= 2 and not line.startswith("# "):
80
+ toc.append(f'<a href="#{sid}">{esc(h.group(2))}</a>')
81
+ out.append(f'<h{level} id="{sid}">{inline(h.group(2))}</h{level}>')
82
+ elif re.match(r"^-{3,}$", line.strip()):
83
+ flush_para(); out.append("<hr>")
84
+ elif line.startswith("> "):
85
+ flush_para(); out.append("<blockquote>" + inline(line[2:]) + "</blockquote>")
86
+ elif line.startswith("- "):
87
+ flush_para()
88
+ out.append("<ul><li>" + inline(line[2:]) + "</li></ul>") # IC-MEMO lists are flat
89
+ elif not line.strip():
90
+ flush_para()
91
+ else:
92
+ para_buf.append(line.strip())
93
+ flush_para(); flush_table()
94
+
95
+ toc_html = "".join(toc) or "<em>(no sections)</em>"
96
+ return f"""<!doctype html>
97
+ <html lang="en"><head><meta charset="utf-8">
98
+ <meta name="viewport" content="width=device-width,initial-scale=1">
99
+ <title>{esc(title)}</title>
100
+ <style>
101
+ :root{{--bg:#0d1117;--panel:#161b22;--fg:#c9d1d9;--dim:#8b949e;--accent:#f2cc60;--link:#a5d6ff;--ok:#3fb950;--warn:#e3b341}}
102
+ *{{box-sizing:border-box}}
103
+ body{{margin:0;background:var(--bg);color:var(--fg);font:15px/1.65 -apple-system,"Segoe UI",Roboto,"Helvetica Neue",sans-serif}}
104
+ .layout{{display:flex;min-height:100vh}}
105
+ nav{{width:260px;flex:none;background:var(--panel);padding:24px 18px;border-right:1px solid #21262d;position:sticky;top:0;max-height:100vh;overflow:auto}}
106
+ nav b{{color:var(--accent);font-size:13px;letter-spacing:.06em;text-transform:uppercase}}
107
+ nav a{{display:block;color:var(--dim);text-decoration:none;font-size:13px;padding:5px 8px;border-radius:6px}}
108
+ nav a:hover{{color:var(--link);background:#1c2129}}
109
+ main{{flex:1;max-width:820px;margin:0 auto;padding:40px 32px}}
110
+ h1{{font-size:26px;margin:0 0 4px}}
111
+ h2{{font-size:19px;margin:36px 0 12px;padding-bottom:6px;border-bottom:1px solid #21262d}}
112
+ h3{{font-size:16px;color:var(--accent);margin:24px 0 8px}}
113
+ pre.yaml{{background:var(--panel);border:1px solid #21262d;border-radius:10px;padding:14px 16px;overflow:auto;font:12.5px/1.5 ui-monospace,Menlo,Consolas,monospace;color:var(--link)}}
114
+ table{{border-collapse:collapse;margin:14px 0;width:100%}}
115
+ th,td{{border:1px solid #21262d;padding:7px 12px;text-align:left;font-size:14px}}
116
+ th{{color:var(--accent);background:var(--panel)}}
117
+ blockquote{{border-left:3px solid var(--accent);margin:12px 0;padding:2px 14px;color:var(--dim)}}
118
+ code{{background:var(--panel);border-radius:5px;padding:1px 5px;font-size:13px}}
119
+ ul{{padding-left:22px}} li{{margin:4px 0}}
120
+ hr{{border:0;border-top:1px solid #21262d;margin:28px 0}}
121
+ footer,.foot{{color:var(--dim);font-size:13px}}
122
+ @media(max-width:860px){{.layout{{display:block}}nav{{position:static;width:auto;border-right:0;border-bottom:1px solid #21262d}}nav a{{display:inline-block;margin:2px}}}}
123
+ @media print{{nav{{display:none}}body{{background:#fff;color:#111}}}}
124
+ </style></head>
125
+ <body><div class="layout">
126
+ <nav><b>IC-MEMO</b>{toc_html}</nav>
127
+ <main>{''.join(out)}
128
+ <p class="foot">Rendered by dsh-tradingagents · single-file page, no external assets · not investment advice</p>
129
+ </main></div></body></html>"""
130
+
131
+
132
+ def main():
133
+ ap = argparse.ArgumentParser()
134
+ ap.add_argument("memo", help="IC-MEMO markdown file")
135
+ ap.add_argument("-o", "--out", default=None)
136
+ args = ap.parse_args()
137
+ md = open(args.memo, encoding="utf-8").read()
138
+ out = args.out or os.path.splitext(args.memo)[0] + ".html"
139
+ open(out, "w", encoding="utf-8").write(render(md))
140
+ print(f"html → {out}")
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env python3
2
+ """weknora_bridge — ingest an evidence-linked ontology into a WeKnora KB (issue #10, O3)
3
+
4
+ Family synergy: WeKnora is the family's knowledge store; this bridge turns each
5
+ ontology entity into a small manual-knowledge document (name, type, aliases,
6
+ evidence quotes with source docs, and its relations) so that KB retrieval — and
7
+ anything built on it — is grounded in the same evidence spans the ontology
8
+ carries. Grounded in WeKnora = grounded in quotes, not vibes.
9
+
10
+ Scope discipline (deliberate): the bridge never creates a knowledge base — the
11
+ scoped API key used here allows ingest only, and a KB is a person's choice.
12
+ Pass an existing --kb id (created with a management key, or by the owner).
13
+ Auth follows the family convention: env WEKNORA_URL / WEKNORA_API_KEY /
14
+ WEKNORA_TENANT_ID (headers X-API-Key / X-Tenant-ID — the weknora-ops form).
15
+
16
+ Usage:
17
+ python3 scripts/weknora_bridge.py --from ontologies/x.json --kb <kb-id> [--limit 50] [--dry-run]
18
+ """
19
+ import argparse, glob, json, os, sys, urllib.request
20
+
21
+ OUTDIR = os.environ.get("ONTOLOGY_HOME") or os.path.join(
22
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "ontologies")
23
+
24
+
25
+ def entity_docs(o, limit=None):
26
+ """Pure: ontology v2 -> [(title, markdown)] per entity, evidence-first.
27
+ Relations touching the entity ride along (with their evidence quotes)."""
28
+ by_name = {}
29
+ for e in o.get("abox", {}).get("entities", []):
30
+ by_name[e["name"]] = e
31
+ rel_by_end = {}
32
+ for r in o.get("abox", {}).get("relations", []):
33
+ rel_by_end.setdefault(r["subject"], []).append(r)
34
+ rel_by_end.setdefault(r["object"], []).append(r)
35
+ docs = []
36
+ for e in o.get("abox", {}).get("entities", []):
37
+ evs = "\n".join(f'- "{v["quote"]}" ({v["doc"]})' for v in e.get("evidences", [])[:5]) or "- (no evidence)"
38
+ aliases = f"\nAliases: {', '.join(e.get('aliases', []))}." if e.get("aliases") else ""
39
+ rels = rel_by_end.get(e["name"], [])
40
+ rel_lines = "\n".join(
41
+ f"- ({r['subject']}) -[{r['predicate']}]-> ({r['object']}) — \"{r['evidences'][0]['quote']}\""
42
+ if r.get("evidences") else f"- ({r['subject']}) -[{r['predicate']}]-> ({r['object']})"
43
+ for r in rels[:8])
44
+ body = (f"# {e['name']} ({e['type']}){aliases}\n\n"
45
+ f"Domain: {o.get('domain', '?')} · type: {e['type']} · "
46
+ f"sources: {', '.join(e.get('docs', [])[:5]) or '?'}\n\n"
47
+ f"Evidence:\n{evs}\n"
48
+ + (f"\nRelations:\n{rel_lines}\n" if rel_lines else ""))
49
+ docs.append((f"Ontology: {e['name']} ({e['type']})", body))
50
+ if limit and len(docs) >= limit:
51
+ break
52
+ return docs
53
+
54
+
55
+ def ingest(title, text, kb, base, key, tenant):
56
+ body = json.dumps({"title": title, "text": text, "content": text}).encode()
57
+ headers = {"X-API-Key": key, "Content-Type": "application/json"}
58
+ if tenant:
59
+ headers["X-Tenant-ID"] = tenant
60
+ req = urllib.request.Request(f"{base.rstrip('/')}/api/v1/knowledge-bases/{kb}/knowledge/manual",
61
+ data=body, headers=headers, method="POST")
62
+ with urllib.request.urlopen(req, timeout=60) as r:
63
+ return r.status
64
+
65
+
66
+ def main():
67
+ ap = argparse.ArgumentParser()
68
+ ap.add_argument("--from", dest="frm", default=None, help="ontology JSON (default: newest artifact)")
69
+ ap.add_argument("--kb", required=True, help="existing WeKnora knowledge-base id (the bridge never creates one)")
70
+ ap.add_argument("--limit", type=int, default=50, help="max entity docs this pass (default 50)")
71
+ ap.add_argument("--dry-run", action="store_true")
72
+ args = ap.parse_args()
73
+
74
+ path = args.frm or max(glob.glob(os.path.join(OUTDIR, "*.json")), key=os.path.getmtime)
75
+ o = json.load(open(path))
76
+ docs = entity_docs(o, limit=args.limit)
77
+ print(f"{path} → kb {args.kb}: {len(docs)} entity doc(s)" + (" (dry run)" if args.dry_run else ""))
78
+ if args.dry_run:
79
+ for title, body in docs[:2]:
80
+ print(f"\n--- {title}\n{body[:300]}")
81
+ return
82
+ base = os.environ.get("WEKNORA_URL")
83
+ key = os.environ.get("WEKNORA_API_KEY")
84
+ if not (base and key):
85
+ sys.exit("WEKNORA_URL / WEKNORA_API_KEY not set (family config: ~/.config/weknora-ops/config)")
86
+ tenant = os.environ.get("WEKNORA_TENANT_ID")
87
+ ok = 0
88
+ for title, body in docs:
89
+ try:
90
+ ingest(title, body, args.kb, base, key, tenant)
91
+ ok += 1
92
+ except Exception as exc:
93
+ print(f"✗ {title}: {exc}", file=sys.stderr)
94
+ print(f"ingested {ok}/{len(docs)}")
95
+
96
+
97
+ if __name__ == "__main__":
98
+ main()
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: dsh-auto-ontology
3
+ 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 and a type guard against silent drops. English-first, --lang zh for Chinese.
4
+ ---
5
+
6
+ Use this skill when asked to turn a document corpus into a knowledge graph /
7
+ ontology ("extract a knowledge graph from these docs", "build an ontology").
8
+ **Evidence is the contract** — no assertion lands without its source quote, and
9
+ unknown types are flagged, never silently dropped.
10
+
11
+ ## Run
12
+
13
+ `auto-ontology` must be on PATH (`npm i -g dsh-auto-ontology`).
14
+
15
+ ```bash
16
+ auto-ontology build --docs <dir-or-glob> --domain "<description>" --save # typed JSON + SVG cluster graph + md digest
17
+ auto-ontology build --docs '*.md' --domain "..." --lang zh # Chinese prompts/artifacts
18
+ ```
19
+
20
+ Requires `python3` (stdlib only) and a `DEEPSEEK_API_KEY` in `~/.bashrc`.
21
+ Artifacts land in `./ontologies/` (relative to where you invoke); the SVG is
22
+ the shareable overview, the JSON carries every assertion with its evidence span.
23
+
24
+ ## Discipline
25
+
26
+ - Every entity/relation must carry `evidence` = a verbatim quote (≤40 chars);
27
+ the engine rejects no-evidence assertions.
28
+ - Instance types must come from the extracted TBox; unknown types are recorded
29
+ in `flagged_unknown_types`, never silently dropped.
30
+ - Artifacts are append-only in spirit: a new run writes new files; it never
31
+ edits a prior ontology.