dsh-auto-ontology 0.2.1 → 0.3.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/README.md CHANGED
@@ -8,14 +8,25 @@ never silently dropped.
8
8
  ```bash
9
9
  npm i -g dsh-auto-ontology
10
10
  auto-ontology build --docs ~/my-corpus/*.md --domain "internal design docs" --save
11
+ auto-ontology build --kb <weknora-kb-id> --domain "..." --save # from a WeKnora knowledge base
11
12
  ```
12
13
 
13
14
  - Zero-infra: `python3` (stdlib) + a DeepSeek key you already have. No Docker,
14
15
  no database — the deliberate opposite of the enterprise-metadata stacks.
15
16
  - Two-pass pipeline: TBox schema from corpus samples → per-document ABox
16
17
  assertions, each with an evidence span.
18
+ - Chunk-level evidence: `build --kb` reads a WeKnora knowledge base's parsed
19
+ chunks (needs `WEKNORA_URL` / `WEKNORA_API_KEY`; `--limit N` to bound it) and
20
+ puts the `chunk_id` on every evidence — each assertion resolves back into
21
+ the base.
22
+ - Grounding pass: every type and relation claim is judged against its own
23
+ quote; an ungrounded one is flagged (`type_grounding: false`), never dropped.
17
24
  - Outputs: typed JSON (every assertion + evidence), zero-dep SVG cluster graph,
18
25
  markdown digest.
26
+ - `auto-ontology export x.json`: the artifact as an event stream
27
+ (`ao-trajectory/0.1`, newline JSON) — what dsh-EvoOntology's adapter consumes.
28
+ - `auto-ontology apply --proposals run.proposals.json --actor agent:<name>`:
29
+ a judge-grounded re-typing comes back as a certification, never as an edit.
19
30
  - Register the DSH skill:
20
31
  `ln -s "$(npm root -g)/dsh-auto-ontology/skills/dsh-auto-ontology" ~/.dsh/skills/dsh-auto-ontology`
21
32
 
@@ -3,6 +3,9 @@
3
3
  // (the dsh-laya sidecar precedent, proven across the family).
4
4
  //
5
5
  // auto-ontology build --docs <dir-or-glob> --domain "..." --save [--lang zh]
6
+ // auto-ontology build --kb <weknora-kb-id> --domain "..." --save [--limit N] (a knowledge base: every quote names its chunk)
7
+ // auto-ontology export ontologies/x.json > trajectory.ndjson (the artifact as events)
8
+ // auto-ontology apply run.proposals.json --actor agent:<name> (a judge's re-typing, applied as a certification)
6
9
  // auto-ontology --docs ... (build is the default subcommand)
7
10
  import { spawnSync } from "node:child_process";
8
11
  import path from "node:path";
@@ -12,17 +15,20 @@ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
12
15
  const argv = process.argv.slice(2);
13
16
  const [cmd, ...rest] = argv;
14
17
 
15
- let script_file = "build_ontology.py";
16
- if (cmd === "eval") {
17
- script_file = "eval_evidence.py"; // auto-ontology eval --from x.json [--n 20] [--seed 42]
18
- } else if (cmd === "validate") {
19
- script_file = "validate_format.py"; // auto-ontology validate ontologies/*.json
20
- }
18
+ const SUBCOMMANDS = { // named subcommands: strip the name, route the script
19
+ build: "build_ontology.py",
20
+ export: "build_ontology.py", // auto-ontology export [files...] [--from x.json] [--out f] → --trajectory
21
+ apply: "build_ontology.py", // auto-ontology apply <proposals.json> --actor agent:<name> [--from x.json]
22
+ eval: "eval_evidence.py", // auto-ontology eval --from x.json [--n 20] [--seed 42]
23
+ validate: "validate_format.py", // auto-ontology validate ontologies/*.json
24
+ };
25
+ const FLAG = { export: "--trajectory", apply: "--proposals" };
26
+ let script_file = SUBCOMMANDS[cmd] || "build_ontology.py";
21
27
  let pass;
22
- if (cmd === "build") {
23
- pass = rest;
28
+ if (SUBCOMMANDS[cmd]) {
29
+ pass = FLAG[cmd] ? [FLAG[cmd], ...rest] : rest;
24
30
  } else {
25
- pass = argv; // engine args pass through verbatim (build is the default)
31
+ pass = argv; // bare engine args pass through verbatim (build is the default)
26
32
  }
27
33
 
28
34
  // Artifacts land in the caller's cwd (the engine reads ONTOLOGY_HOME).
package/lib/index.js CHANGED
@@ -1,15 +1,20 @@
1
1
  /**
2
- * dsh-auto-ontology host plugin (0.2.0, issue #11): the ontology engine as typed tools.
2
+ * dsh-auto-ontology host plugin (issue #11; `kb` since issue #56): the ontology engine as typed tools.
3
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)
4
+ * Registers three agent tools on `ctx.tools` via @deepseek-ai/dsh-tools:
5
+ * ontology_build — two-pass build over a document corpus, or over the chunks of
6
+ * a WeKnora knowledge base (evidence on every assertion, type
7
+ * guard, coref, append-only merge; a kb build names each
8
+ * quote's chunk)
7
9
  * ontology_query — every assertion about a term, with its evidence spans
10
+ * ontology_export — the artifact as an ao-trajectory/0.1 event stream (the
11
+ * record format dsh-EvoOntology's adapter consumes)
8
12
  *
9
13
  * The tools spawn the bundled Python engine; artifacts land under the calling
10
14
  * process's cwd (./ontologies/), exactly like the CLI.
11
15
  */
12
16
  import { spawnSync } from "node:child_process";
17
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
13
18
  import path from "node:path";
14
19
  import { fileURLToPath } from "node:url";
15
20
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -30,23 +35,37 @@ function run(args, timeoutMs = 600_000) {
30
35
  }
31
36
 
32
37
  const LANG = { type: "string", enum: ["en", "zh"], description: "Output language (default en)." };
38
+ const KB_DEFAULT_LIMIT = 40; // chunks a typed-tool build reads from a knowledge base unless told otherwise
39
+
40
+ function newest() { // the engine's own default: the newest artifact under ./ontologies/
41
+ const dir = path.join(process.cwd(), "ontologies");
42
+ const files = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".json")) : [];
43
+ if (!files.length) throw new Error(`no ontology artifact under ${dir} — ontology_build writes one`);
44
+ const byAge = (a, b) => statSync(path.join(dir, b)).mtimeMs - statSync(path.join(dir, a)).mtimeMs;
45
+ return path.join(dir, files.sort(byAge)[0]);
46
+ }
33
47
 
34
48
  export async function apply(ctx) {
35
49
  ctx.tools.register(defineTool({
36
50
  name: "ontology_build",
37
51
  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.",
52
+ "Build an ontology from a document corpus, or from a WeKnora knowledge base: a TBox schema from " +
53
+ "sampled documents, then ABox assertions per document (per chunk for a knowledge base) where EVERY " +
54
+ "entity and relation carries a verbatim evidence quote (no evidence, no assertion; unknown types are " +
55
+ "flagged, never silently dropped). Conservative coreference merges certain mentions (aliases " +
56
+ "recorded); append-only merge folds new docs into an existing ontology without touching prior " +
57
+ "evidence; the same name under different types becomes a conflict entry holding both evidences. " +
58
+ "Pass `kb` (a knowledge-base id) to read the base's parsed chunks instead of files: each quote then " +
59
+ "carries the id of the chunk it was read from, so every assertion can be traced back into the base. " +
60
+ "Artifacts: typed JSON (+ evidence), SVG cluster graph, markdown digest under ./ontologies/. " +
61
+ "Takes about 10 seconds per document or chunk — the grounding judge is one call per quote.",
45
62
  parameters: {
46
- docs: { type: "string", required: true, description: "Document directory or glob, e.g. 'docs/*.md'." },
63
+ docs: { type: "string", description: "Document directory or glob, e.g. 'docs/*.md'. Required unless kb is given." },
64
+ kb: { type: "string", description: "WeKnora knowledge-base id to build from instead of docs (its parsed text chunks, one chunk = one document). Needs WEKNORA_URL / WEKNORA_API_KEY in the environment." },
65
+ limit: { type: "number", description: "With kb: read at most this many chunks, in reading order (default 40). Raise it to read more of the base." },
47
66
  domain: { type: "string", required: true, description: "Corpus domain description for the schema pass." },
48
67
  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)." },
68
+ sample: { type: "number", description: "Documents sampled for the schema pass (default 4)." },
50
69
  max_calls: { type: "number", description: "Cost guard: abort beyond this many LLM calls." },
51
70
  lang: LANG,
52
71
  },
@@ -56,12 +75,18 @@ export async function apply(ctx) {
56
75
  render: (_args, value) => [{ type: "text", text: value.summary }],
57
76
  },
58
77
  execute(args) {
78
+ if (!args.docs && !args.kb) throw new Error("ontology_build needs docs (a document corpus) or kb (a WeKnora knowledge-base id)");
79
+ if (args.docs && args.kb) throw new Error("ontology_build takes docs or kb, not both: one source per build");
80
+ // the typed tool reads a bounded slice unless told otherwise; a whole base can run for an hour
81
+ const source = args.kb
82
+ ? ["--kb", args.kb, "--limit", String(args.limit ?? KB_DEFAULT_LIMIT)]
83
+ : ["--docs", args.docs];
59
84
  const extra = ["--save",
60
85
  ...(args.merge ? ["--merge", args.merge] : []),
61
86
  ...(args.sample ? ["--sample", String(args.sample)] : []),
62
87
  ...(args.max_calls ? ["--max-calls", String(args.max_calls)] : []),
63
88
  ...(args.lang ? ["--lang", args.lang] : [])];
64
- return { summary: run(["--docs", args.docs, "--domain", args.domain, ...extra]) };
89
+ return { summary: run([...source, "--domain", args.domain, ...extra], args.kb ? 1_800_000 : 600_000) };
65
90
  },
66
91
  }));
67
92
 
@@ -84,4 +109,31 @@ export async function apply(ctx) {
84
109
  return { result: run(["--query", args.term, ...(args.from ? ["--from", args.from] : [])], 60_000) };
85
110
  },
86
111
  }));
112
+
113
+ ctx.tools.register(defineTool({
114
+ name: "ontology_export",
115
+ description:
116
+ "Export an ontology artifact as its event stream (ao-trajectory/0.1, newline JSON): one event per evidence " +
117
+ "quote with the judge's verdict, every certification (who issued it, the note, the evidence), the build, " +
118
+ "merges, conflicts and the type guard's catches. Deterministic and idempotent by event id — the record " +
119
+ "format dsh-EvoOntology's adapter consumes. Writes a .ndjson file and returns the tally plus the first events.",
120
+ parameters: {
121
+ from: { type: "string", description: "Ontology JSON path (default: newest under ./ontologies/)." },
122
+ out: { type: "string", description: "Output path (default: <artifact>.trajectory.ndjson)." },
123
+ limit: { type: "number", description: "Events returned inline after the tally (default 5)." },
124
+ },
125
+ output: {
126
+ schema: { type: "object", additionalProperties: false,
127
+ properties: { summary: { type: "string", required: true } } },
128
+ render: (_args, value) => [{ type: "text", text: value.summary }],
129
+ },
130
+ execute(args) {
131
+ const from = args.from || newest();
132
+ const out = args.out || from.replace(/\.json$/i, "") + ".trajectory.ndjson";
133
+ const head = run(["--trajectory", "--from", from, "--out", out], 120_000);
134
+ const lines = readFileSync(out, "utf8").split("\n").filter(Boolean);
135
+ const n = Math.max(0, Math.min(args.limit ?? 5, lines.length));
136
+ return { summary: [head, ...lines.slice(0, n)].join("\n") };
137
+ },
138
+ }));
87
139
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-auto-ontology",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
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": {
@@ -0,0 +1,119 @@
1
+ {
2
+ "version": "ao-adversarial/0.3",
3
+ "about": "Labelled (claim, quote) pairs for the type-grounding judge (scripts/grounding.py). grounded=false are mention-only traps: the quote names the entity (or its type word) without grounding the TYPE claim. grounded=true are quotes a too-strict judge must still accept. The first 20 cases were written by hand before any judge ran; one keeps the shape of a real failure from the 2026-11-18 artifact (it was copied from a private repository's document, so its names were replaced before publication and the set was re-run on both judges). 3 cases added 2026-11-25 pin contract clarifications found in a 273-assertion hand audit (implicit object, endpoints-only mention, roadmap item). 5 more added the same day, when the build's name/endpoint pre-reject was dropped in favour of the judge: two grounded cases whose quote does not spell the name (an extractor-coined label under the document's own wording), and three the judge must still reject without that rule (a quote about ANOTHER instance of the type, as entity and as relation, and a mention that names nobody).",
4
+ "cases": [
5
+ {"id": "mention-only", "grounded": false,
6
+ "kind": "entity", "name": "Northwind", "type": "company", "type_desc": "a for-profit organization",
7
+ "quote": "Northwind uses ToolX for backups.", "doc": "acme-handbook",
8
+ "why": "the name appears, but nothing says what Northwind is"},
9
+ {"id": "wrong-type-mention", "grounded": false,
10
+ "kind": "entity", "name": "ToolX", "type": "company", "type_desc": "a for-profit organization",
11
+ "quote": "Northwind uses ToolX for backups.", "doc": "acme-handbook",
12
+ "why": "ToolX is named; the quote does not make it a company"},
13
+ {"id": "name-absent", "grounded": false,
14
+ "kind": "entity", "name": "@acme/widget", "type": "cli_tool", "type_desc": "a command-line program",
15
+ "quote": "The CLI ships with a plugin system.", "doc": "acme-handbook",
16
+ "why": "the type word is present, the entity is never named"},
17
+ {"id": "role-reversal", "grounded": false,
18
+ "kind": "entity", "name": "DeepBlue", "type": "database", "type_desc": "a system that stores data",
19
+ "quote": "DeepBlue queries the database every night.", "doc": "acme-handbook",
20
+ "why": "DeepBlue is the agent that queries, not the database"},
21
+ {"id": "negation", "grounded": false,
22
+ "kind": "entity", "name": "Project Falcon", "type": "deployed_service", "type_desc": "a service running in production",
23
+ "quote": "Project Falcon is not yet deployed.", "doc": "acme-handbook",
24
+ "why": "the claim is negated"},
25
+ {"id": "hypothetical", "grounded": false,
26
+ "kind": "entity", "name": "Orion", "type": "partner", "type_desc": "an external organization under a formal partnership",
27
+ "quote": "If Orion were a partner, we would share the roadmap with them.", "doc": "acme-handbook",
28
+ "why": "hypothetical, not a fact"},
29
+ {"id": "type-word-other-sense", "grounded": false,
30
+ "kind": "entity", "name": "Gateway", "type": "network_gateway", "type_desc": "a network device that routes traffic between networks",
31
+ "quote": "The Gateway building houses the sales team.", "doc": "acme-handbook",
32
+ "why": "Gateway is a building here"},
33
+ {"id": "alias-instead-of-name", "grounded": false,
34
+ "kind": "entity", "name": "DeepSeek Harness", "type": "cli_tool", "type_desc": "a command-line program",
35
+ "quote": "DSH is a CLI agent harness.", "doc": "acme-handbook",
36
+ "why": "the quote names the alias, not the entity as written; linking them needs outside knowledge"},
37
+ {"id": "outside-knowledge", "grounded": false,
38
+ "kind": "entity", "name": "PostgreSQL", "type": "open_source_project", "type_desc": "a project whose source code is publicly licensed",
39
+ "quote": "PostgreSQL stores the catalog.", "doc": "acme-handbook",
40
+ "why": "true in the world, but the quote says nothing about licensing"},
41
+ {"id": "cjk-mention-only", "grounded": false,
42
+ "kind": "entity", "name": "星河科技", "type": "数据库", "type_desc": "用于存储数据的软件系统",
43
+ "quote": "星河科技每天晚上查询数据库。", "doc": "acme-handbook",
44
+ "why": "提到名字,但没说它是什么"},
45
+ {"id": "table-row-names-only", "grounded": false,
46
+ "kind": "entity", "name": "@acme/super-agent", "type": "dsh_plugin", "type_desc": "a DSH plugin package",
47
+ "quote": "`@acme/super-agent` | npm | 1.6.0", "doc": "acme-catalog",
48
+ "why": "the shape of a real failure in the 2026-11-18 artifact: the row names the package, not what it is"},
49
+ {"id": "relation-not-stated", "grounded": false,
50
+ "kind": "relation", "subject": "Northwind", "predicate": "develops", "object": "ToolX", "type_desc": "creates and maintains",
51
+ "quote": "Northwind uses ToolX for backups.", "doc": "acme-handbook",
52
+ "why": "using is not developing"},
53
+ {"id": "relation-reversed", "grounded": false,
54
+ "kind": "relation", "subject": "Redis", "predicate": "depends_on", "object": "App Server", "type_desc": "requires at runtime",
55
+ "quote": "The app server depends on Redis.", "doc": "acme-handbook",
56
+ "why": "the direction is reversed"},
57
+
58
+ {"id": "copula-definition", "grounded": true,
59
+ "kind": "entity", "name": "ToolX", "type": "cli_tool", "type_desc": "a command-line program",
60
+ "quote": "ToolX is a command-line tool that backs up directories.", "doc": "acme-handbook",
61
+ "why": "a definition"},
62
+ {"id": "apposition", "grounded": true,
63
+ "kind": "entity", "name": "Redis", "type": "database", "type_desc": "a system that stores data",
64
+ "quote": "We use Redis, an in-memory database, for sessions.", "doc": "acme-handbook",
65
+ "why": "apposition states the type"},
66
+ {"id": "predication-entails-type", "grounded": true,
67
+ "kind": "entity", "name": "Kafka", "type": "message_queue", "type_desc": "a system that moves messages between services",
68
+ "quote": "Kafka streams events between services.", "doc": "acme-handbook",
69
+ "why": "the predication entails the type definition"},
70
+ {"id": "cjk-definition", "grounded": true,
71
+ "kind": "entity", "name": "星河科技", "type": "数据库", "type_desc": "用于存储数据的软件系统",
72
+ "quote": "星河科技是一款分布式数据库。", "doc": "acme-handbook",
73
+ "why": "定义句"},
74
+ {"id": "relation-stated", "grounded": true,
75
+ "kind": "relation", "subject": "Northwind", "predicate": "develops", "object": "ToolX", "type_desc": "creates and maintains",
76
+ "quote": "Northwind develops ToolX.", "doc": "acme-handbook",
77
+ "why": "the relation is stated outright"},
78
+ {"id": "relation-implicit-subject", "grounded": true,
79
+ "kind": "relation", "subject": "acme-handbook", "predicate": "published_by", "object": "Acme Corp", "type_desc": "released to readers by",
80
+ "quote": "This handbook is published by Acme Corp.", "doc": "acme-handbook",
81
+ "why": "the subject is the document itself and is left implicit in the quote"},
82
+ {"id": "name-with-alias", "grounded": true,
83
+ "kind": "entity", "name": "DeepSeek Harness", "type": "cli_tool", "type_desc": "a command-line program",
84
+ "quote": "DeepSeek Harness (DSH) is a CLI agent harness.", "doc": "acme-handbook",
85
+ "why": "the name as written, plus the alias"},
86
+ {"id": "relation-mentions-both-only", "grounded": false,
87
+ "kind": "relation", "subject": "Northwind", "predicate": "develops", "object": "ToolX", "type_desc": "creates and maintains",
88
+ "quote": "Northwind and ToolX will both attend the conference.", "doc": "acme-handbook",
89
+ "why": "both endpoints are named; nothing says how they relate"},
90
+ {"id": "roadmap-item", "grounded": false,
91
+ "kind": "entity", "name": "ToolX", "type": "deployed_service", "type_desc": "a service running in production",
92
+ "quote": "ToolX is on the roadmap for next quarter.", "doc": "acme-handbook",
93
+ "why": "planned, not running: a roadmap item is not a fact"},
94
+ {"id": "substituted-instance", "grounded": false,
95
+ "kind": "entity", "name": "drawdown circuit breaker", "type": "guardrail", "type_desc": "a fail-closed, code-enforced safety mechanism",
96
+ "quote": "**sample-size alarm**: n<30 flags Sharpe/Sortino as noise", "doc": "dsh-quantstats",
97
+ "why": "the quote describes ANOTHER guardrail; the claim's own subject never appears"},
98
+ {"id": "substituted-endpoint", "grounded": false,
99
+ "kind": "relation", "subject": "dsh-quantstats", "predicate": "enforces", "object": "drawdown circuit breaker", "type_desc": "enforces in its code",
100
+ "quote": "**sample-size alarm**: n<30 flags Sharpe/Sortino as noise", "doc": "dsh-quantstats",
101
+ "why": "the plugin is named, but the quote is about another mechanism, not the object"},
102
+ {"id": "name-absent-mention", "grounded": false,
103
+ "kind": "entity", "name": "Rusty", "type": "person", "type_desc": "a human being",
104
+ "quote": "Mara mentioned them during standup.", "doc": "acme-handbook",
105
+ "why": "names nobody and says nothing about anyone being a person"},
106
+ {"id": "relation-implicit-object", "grounded": true,
107
+ "kind": "relation", "subject": "nightly backup", "predicate": "enforced_by", "object": "acme-backup", "type_desc": "implemented and run by",
108
+ "quote": "The nightly backup runs at 02:00 and cannot be switched off.", "doc": "acme-backup",
109
+ "why": "the object — the plugin the document itself is about — is left implicit in the quote"},
110
+ {"id": "alias-label", "grounded": true,
111
+ "kind": "entity", "name": "market_data_payload", "type": "data_payload", "type_desc": "a market data payload carrying its exchange and timestamp",
112
+ "quote": "Every payload carries its exchange and timestamp.", "doc": "dsh-ccxt",
113
+ "why": "the snake_case name is a label the extractor coined; the document says 'payload'"},
114
+ {"id": "relation-alias-object", "grounded": true,
115
+ "kind": "relation", "subject": "dsh-WrenAI", "predicate": "produces", "object": "skeleton model", "type_desc": "emits as an output",
116
+ "quote": "emits a skeleton: every table's columns with compact types", "doc": "dsh-wrenai",
117
+ "why": "the subject is the document's own project and the object appears in shortened form"}
118
+ ]
119
+ }