From aff22d5b0fb0f8eee05efc1f193f7d65490d5e47 Mon Sep 17 00:00:00 2001 From: Arinjay Wyawhare <72088094+jaywyawhare@users.noreply.github.com> Date: Sat, 5 Dec 2026 07:00:56 +0530 Subject: [PATCH] Store agent-made facts with their source text --- docs/cli.md | 2 +- docs/inserting.md | 25 ++++- docs/mcp.md | 2 +- skill/SKILL.md | 14 +++ skill/references/writing.md | 4 + src/selfgraph/cli.py | 2 + src/selfgraph/insert.py | 52 +++++++++- src/selfgraph/mcp/server.py | 11 ++- tests/test_insert_with_facts.py | 82 ++++++++++++++++ typescript/src/cli.ts | 6 +- typescript/src/index.ts | 1 + typescript/src/insert.ts | 65 ++++++++++++- typescript/src/mcp.ts | 12 ++- typescript/src/models.ts | 7 ++ typescript/src/runtime.ts | 5 +- typescript/test/conformance.test.ts | 8 ++ typescript/test/conformance/helpers.ts | 1 + typescript/test/conformance/py_side.py | 40 ++++++++ typescript/test/conformance/ts_side.ts | 48 +++++++++ typescript/test/insertWithFacts.test.ts | 123 ++++++++++++++++++++++++ typescript/test/mcp.test.ts | 2 +- 21 files changed, 490 insertions(+), 22 deletions(-) create mode 100644 tests/test_insert_with_facts.py create mode 100644 typescript/test/insertWithFacts.test.ts diff --git a/docs/cli.md b/docs/cli.md index 4410b6ff..ff136529 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -98,7 +98,7 @@ settings from the environment are ignored silently. | `check-citations ANSWER_FILE --evidence FILE` | Checks the `[n]` citations in an answer file, or `-` for stdin, against the JSON `retrieve --numbered` printed, and prints the report ([citing the context](retrieval.md#citing-the-context)). It opens no store. | | `search` | Prints the ranked entities and passages for a query as JSON. See [`search`](#search). | | `neighbors`, `path` | List the entities near an entity, or find how two connect. See [`neighbors` and `path`](#neighbors-and-path). | -| `insert text` | Extracts from text, or `-` for stdin, with the configured LLM, else spaCy or the regex fallback ([inserting](inserting.md#from-text)). `--metadata` takes a JSON object or `KEY=VALUE` pairs, repeatable and merged in order. `--replace-source` makes the text [replace](inserting.md#replacing-a-source) the earlier versions of `--source-id`. `--chunking markdown` splits it on [headings](inserting.md#markdown). | +| `insert text` | Extracts from text, or `-` for stdin, with the configured LLM, else spaCy or the regex fallback ([inserting](inserting.md#from-text)). `--metadata` takes a JSON object or `KEY=VALUE` pairs, repeatable and merged in order. `--replace-source` makes the text [replace](inserting.md#replacing-a-source) the earlier versions of `--source-id`. `--chunking markdown` splits it on [headings](inserting.md#markdown). `--facts FILE` stores the facts in that JSON file with the text instead of extracting ([facts with their text](inserting.md#facts-with-their-text)). | | `insert facts` | Inserts facts from a JSON file, or `-` for stdin. `--placeholders` stores a [placeholder](inserting.md#references-to-entities-not-yet-inserted) for an entity reference not yet in the graph instead of failing. | | `sync DIR` | Syncs the text files under `DIR`, extracting only those that changed, once or with `--watch` until interrupted. See [`sync`](#sync). | | `code index DIR...` | Indexes source code into the graph, writing only the files that changed, once or with `--watch` until interrupted. See [`code index`](#code-index). | diff --git a/docs/inserting.md b/docs/inserting.md index b2b3a0aa..c2e89eb7 100644 --- a/docs/inserting.md +++ b/docs/inserting.md @@ -377,8 +377,9 @@ pass. `result.warnings` says which ran (`ner_extraction` or `basic_extraction`). - The regex pass types every entity `Thing` and links neighbouring names in a sentence with `RELATED_TO`. -Both can link the wrong pair. Use an LLM when the graph matters. `instructions` -and `prompts` are ignored here, with a `prompts_ignored` warning. +Both can link the wrong pair. Use an LLM when the graph matters, or extract the +facts yourself and pass them with the text, as [facts with their text](#facts-with-their-text) +shows. `instructions` and `prompts` are ignored here, with a `prompts_ignored` warning. ## From facts @@ -423,6 +424,26 @@ CLI `insert facts`, and the MCP `insert_facts` tool give the same errors. A [schema](schema.md), passed to the graph or to one insert, guides extraction and checks what you write. +### Facts with their text + +An agent with no `llm` configured can extract the facts itself. Pass them with +the text in one call: + +```python +result = await graph.insert.text(text, source_id="note", facts=facts) +``` + +Nothing is extracted, so `result.tiers` has no `extraction` entry. The text is +stored as the source, so [retrieval](retrieval.md) returns its passages with +citations, and `replace_source` retires what only older versions stated. The facts are checked as `insert.facts` checks them: in `strict` +schema mode a fact outside the schema is rejected rather than dropped. +`instructions` and `prompts` guide extraction, so passing them with `facts` +raises `invalid_argument` on the `facts` field. The CLI takes `insert text TEXT +--facts FILE`, and the MCP `insert_text` tool takes `facts`. + +Relation evidence that names no `source_id` cites the call's `source_id`, in +`insert.text` and `insert.facts`, so `{"quote": "..."}` is enough. + ### References to entities not yet inserted Every entity a relation, preference, or decision names must be in the facts or diff --git a/docs/mcp.md b/docs/mcp.md index 4025bf4f..2e9721a8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -186,7 +186,7 @@ default 50) and `[cursor]`. | `suggest_schema` | `[extend]`, `[min_count]` (default 1), `[format]` (`selfgraph` or `neo4j`) ([suggesting a schema](schema.md#suggesting-a-schema-from-the-graph)) | | `list_namespaces` | none ([several graphs](#several-graphs)) | | `use_namespace` | `namespace` ([several graphs](#several-graphs)) | -| `insert_text` | `text`, `[source_id]`, `[event_time]`, `[metadata]`, `[resolver]`, `[contradiction]`, `[schema]`, `[schema_mode]`, `[instructions]`, `[prompts]`, `[replace_source]`, `[chunking]` (`tokens` or `markdown`, see [markdown chunking](inserting.md#markdown)) | +| `insert_text` | `text`, `[source_id]`, `[event_time]`, `[metadata]`, `[resolver]`, `[contradiction]`, `[schema]`, `[schema_mode]`, `[instructions]`, `[prompts]`, `[replace_source]`, `[chunking]` (`tokens` or `markdown`, see [markdown chunking](inserting.md#markdown)), `[facts]` (stored with the text instead of extracting, see [facts with their text](inserting.md#facts-with-their-text)) | | `insert_facts` | `facts` (an object with `entities`, `relations`, `preferences`, `decisions`), `[source_id]`, `[event_time]`, `[resolver]`, `[contradiction]`, `[schema]`, `[schema_mode]`, `[placeholders]` ([placeholders](inserting.md#references-to-entities-not-yet-inserted)) | | `index_code` | `[paths]` (local directories inside the working directory or remote git URLs, default the directory itself), `[ref]` (remote branch, tag or commit), `[languages]`, `[remove_missing]` (default true) ([indexing code](#indexing-code)) | | `sync_folder` | `directory` (inside the working directory), `[globs]` (default `**/*.md` and `**/*.txt`), `[remove_missing]` (default false), `[resolver]`, `[contradiction]`, `[chunking]` (`tokens` or `markdown`) ([syncing a folder](#syncing-a-folder)) | diff --git a/skill/SKILL.md b/skill/SKILL.md index efd6e061..f4b13788 100644 --- a/skill/SKILL.md +++ b/skill/SKILL.md @@ -52,6 +52,20 @@ asyncio.run(main()) The heuristic extractor is coarse. Ready facts avoid extraction; LLM extraction is opt-in. Run `examples/retrieval.py` for the same workflow against a path you choose. +## Without an LLM key + +With no LLM configured, extract the facts yourself instead of relying on the heuristic +extractor: give entities real types, name the relations, and pass them with the text. + +```python +await graph.insert.text(text, source_id="note", facts={"entities": [...], "relations": [...]}) +``` + +Nothing is extracted. The text is still stored as the source, so passages, citations, and +`replace_source` keep working. Evidence that names no `source_id` cites the call's, so +`{"quote": "..."}` is enough. CLI `selfgraph insert text TEXT --facts FILE`; MCP `upsert_text` +with `facts`. The facts shape is in `references/writing.md`. + ## Load details when needed - Writes, schema, CRUD, resolution: `references/writing.md`. diff --git a/skill/references/writing.md b/skill/references/writing.md index d08b10da..46ccdab2 100644 --- a/skill/references/writing.md +++ b/skill/references/writing.md @@ -36,6 +36,10 @@ await graph.insert.facts( ) ``` +To keep the text as the source too, pass the same facts to `insert.text(text, source_id=..., facts=...)`: +nothing is extracted, and passages, citations, and `replace_source` work as they do for extracted text. +Relation evidence that names no `source_id` cites the call's `source_id`, in `insert.text` and `insert.facts`. + `await graph.export_facts()` (CLI `selfgraph export facts [FILE]`) returns the namespace's current entities, relations (with evidence and `certifications`), preferences, and decisions in this shape, each list ordered by id. Inserting it into an empty namespace, with `placeholders=True` when it names placeholders, and exporting diff --git a/src/selfgraph/cli.py b/src/selfgraph/cli.py index 7756fc6f..962be9e1 100644 --- a/src/selfgraph/cli.py +++ b/src/selfgraph/cli.py @@ -1123,6 +1123,7 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help="the text replaces --source-id's earlier versions: retire relations only they stated", ) + it.add_argument("--facts", help="a facts JSON file to store with the text instead of extracting, or '-' for stdin") _add_chunking(it) _add_call_overrides(it) @@ -1137,6 +1138,7 @@ async def insert_text(g, a): contradiction=a.call_contradiction, replace_source=a.replace_source, chunking=a.chunking, + facts=None if a.facts is None else read_json(a.facts, "facts"), ) ) diff --git a/src/selfgraph/insert.py b/src/selfgraph/insert.py index 669e1121..4bfc7e6a 100644 --- a/src/selfgraph/insert.py +++ b/src/selfgraph/insert.py @@ -67,6 +67,7 @@ async def text( contradiction: ContradictionMode | None = None, replace_source: bool = False, chunking: Chunking = "tokens", + facts: Extraction | Mapping[str, Any] | None = None, **options: Unpack[_NoOptions], ) -> InsertResult: """Extract and upsert text facts; content.upsert_text is the noun path and insert.text its compatibility alias. @@ -88,6 +89,8 @@ async def text( contradiction: Conflict handling policy, defaulting to the graph's policy. replace_source: treat the text as a replacement of source_id's earlier versions. chunking: "tokens", or "markdown" to split on headings and keep each chunk's section. + facts: entities, relations, preferences, and decisions to store with the text instead of extracting + them; the text is still recorded as the source, and evidence without a source_id cites it. Returns: what was inserted, with source_diff when replace_source is set. @@ -107,6 +110,7 @@ async def text( "contradiction", "replace_source", "chunking", + "facts", ], ) if resolver is not None: @@ -131,6 +135,26 @@ async def text( ) instructions = as_input(ExtractionInstructions, instructions, "instructions") prompts = as_input(ExtractionPrompts, prompts, "prompts") + if facts is not None: + if instructions is not None or prompts is not None: + raise ValidationError( + "instructions and prompts guide extraction, which facts skip; pass one or the other", + field="facts", + ) + return await self._c._apply_facts( + as_input(Extraction, _inherit_source(facts, source_id), "facts"), + source_id=source_id, + parsed_text=text, + media_type="text/plain", + metadata=metadata, + default_event_time=event_time, + schema=active_schema, + schema_mode=schema_mode, + resolver=resolver, + contradiction=contradiction, + replace_source=replace_source, + chunking=chunking, + ) extractor = self._c._build_extractor( instructions, prompts, schema=active_schema, source_id=source_id, chunking=chunking ) @@ -303,7 +327,7 @@ async def facts( Args: facts: the facts to merge. - source_id: optional source id to attach as provenance. + source_id: optional source id to attach as provenance; evidence without a source_id cites it. event_time: the default event time (a datetime or ISO 8601 text) for relations, preferences, and decisions that carry none of their own. schema: The schema for this call, defaulting to the graph's schema. @@ -326,7 +350,7 @@ async def facts( if facts is None: raise ValidationError("invalid facts: expected object") return await self._c._apply_facts( - as_input(Extraction, facts, "facts"), + as_input(Extraction, _inherit_source(facts, source_id), "facts"), source_id=source_id, parsed_text=None, media_type=None, @@ -341,3 +365,27 @@ async def facts( upsert_text = text upsert_facts = facts + + +def _inherit_source(facts: Any, source_id: str | None) -> Any: + """Give relation evidence that names no source the call's source_id. + + @param facts (Any): the facts as given. + @param source_id (str | None): the call's source id. + @return (Any): the facts, with each evidence item lacking a source_id citing the call's source. + """ + if source_id is None or not isinstance(facts, Mapping) or not isinstance(facts.get("relations"), list | tuple): + return facts + relations = [ + { + **rel, + "evidence": [ + {**ev, "source_id": source_id} if isinstance(ev, Mapping) and "source_id" not in ev else ev + for ev in rel["evidence"] + ], + } + if isinstance(rel, Mapping) and isinstance(rel.get("evidence"), list | tuple) + else rel + for rel in facts["relations"] + ] + return {**facts, "relations": relations} diff --git a/src/selfgraph/mcp/server.py b/src/selfgraph/mcp/server.py index 822c3923..c77ee53d 100644 --- a/src/selfgraph/mcp/server.py +++ b/src/selfgraph/mcp/server.py @@ -400,10 +400,13 @@ async def insert_text( prompts: dict | None = None, replace_source: StrictBool = False, chunking: Chunking = "tokens", + facts: dict | None = None, ) -> dict[str, Any]: """Extract and upsert facts from text; insert_text is a compatibility alias of upsert_text. Uses the - configured LLM, or with none - configured falls back to a built-in LLM-free extractor (coarser). event_time (ISO 8601 or relative such as 7d) is + configured LLM; with none configured, extract the entities and relations yourself and pass them as facts, + because the built-in LLM-free extractor is coarse. With facts, nothing is extracted, the text is still stored + as the source for passages, citations, and replace_source, and evidence without a source_id cites this one, + and instructions and prompts must be left out. event_time (ISO 8601 or relative such as 7d) is the default valid time for what is extracted; metadata is stored on the source. Idempotent: ids are derived deterministically from content, so re-inserting the @@ -432,6 +435,7 @@ async def insert_text( prompts=prompts, replace_source=replace_source, chunking=chunking, + facts=facts, ) ) ) @@ -462,7 +466,8 @@ async def insert_facts( is handled: warn keeps both and reports it, supersede retires the older relation. schema (a SelfGraph schema object) and schema_mode (off, warn, strict) override the server's for this call. placeholders stores a placeholder entity for a reference that is neither in the facts nor in the graph, instead of failing, and reports each one as a - placeholder_created warning; inserting an entity with that id later fills it in. + placeholder_created warning; inserting an entity with that id later fills it in. Evidence without a source_id + cites source_id. To keep the source text for passages and citations, pass it with these facts to insert_text. """ at = parse_time(event_time, "event_time") g = await _graph_handle() diff --git a/tests/test_insert_with_facts.py b/tests/test_insert_with_facts.py new file mode 100644 index 00000000..a9585556 --- /dev/null +++ b/tests/test_insert_with_facts.py @@ -0,0 +1,82 @@ +import json + +import pytest +from helpers import fresh_graph, json_file, kuzu_main, mcp_session, run + +from selfgraph import ValidationError + +TEXT = "Ann Lee leads the Payments team at Acme. In March, Bob Diaz joined Payments." +QUOTE = "Ann Lee leads the Payments team" +FACTS = { + "entities": [{"type": "Person", "name": "Ann Lee"}, {"type": "Team", "name": "Payments"}], + "relations": [ + {"from_entity": "person:ann-lee", "type": "LEADS", "to_entity": "team:payments", "evidence": [{"quote": QUOTE}]} + ], +} + + +def evidence_of(graph, relation_id): + return [(ev.source_id, ev.source_version, ev.quote) for ev in run(graph.relations.evidence(relation_id)).items] + + +def test_text_with_facts_stores_the_source_without_extracting(): + g = fresh_graph("withfacts") + result = run(g.insert.text(TEXT, source_id="doc1", facts=FACTS)) + assert sorted(entity.type for entity in result.entities) == ["Person", "Team"] + assert [relation.type for relation in result.relations] == ["LEADS"] + assert "extraction" not in result.tiers + assert evidence_of(g, result.relations[0].id) == [("doc1", result.source_version, QUOTE)] + retrieved = run(g.retrieve("who leads payments", numbered=True)) + assert retrieved.context.splitlines()[0] == f"SOURCE #1 | {TEXT}" + assert [record.kind for record in retrieved.evidence][0] == "passage" + + +def test_facts_evidence_takes_the_call_source_id_unless_it_names_one(): + g = fresh_graph("inherit") + evidence = ({"quote": QUOTE}, {"source_id": "other", "quote": QUOTE}) + facts = {**FACTS, "relations": ({**FACTS["relations"][0], "evidence": evidence},)} + result = run(g.insert.facts(facts, source_id="doc2")) + assert sorted(evidence_of(g, result.relations[0].id)) == [ + ("doc2", result.source_version, QUOTE), + ("other", "other:manual", QUOTE), + ] + + +def test_replace_source_with_facts_retires_what_only_older_versions_stated(): + g = fresh_graph("replace") + first = run(g.insert.text(TEXT, source_id="doc1", facts=FACTS)) + joined = { + "entities": [{"type": "Person", "name": "Bob Diaz"}, {"type": "Team", "name": "Payments"}], + "relations": [{"from_entity": "person:bob-diaz", "type": "JOINED", "to_entity": "team:payments"}], + } + second = run(g.insert.text("Bob Diaz joined Payments.", source_id="doc1", replace_source=True, facts=joined)) + assert second.source_diff.retired == [first.relations[0].id] + assert [relation.type for relation in second.relations] == ["JOINED"] + + +def test_strict_mode_rejects_caller_facts_outside_the_schema(): + g = fresh_graph("strict", schema={"entities": [{"name": "Person"}]}, schema_mode="strict") + with pytest.raises(ValidationError) as caught: + run(g.insert.text(TEXT, source_id="doc1", facts=FACTS)) + assert caught.value.code == "schema_violation" + assert run(g.entities.list()).items == [] + + +@pytest.mark.parametrize("extra", [{"instructions": {"entities": "people"}}, {"prompts": {}}]) +def test_facts_with_extraction_settings_is_rejected(extra): + g = fresh_graph("guard") + with pytest.raises(ValidationError) as caught: + run(g.insert.text(TEXT, source_id="doc1", facts=FACTS, **extra)) + assert (caught.value.code, caught.value.field) == ("invalid_argument", "facts") + assert str(caught.value) == "instructions and prompts guide extraction, which facts skip; pass one or the other" + assert run(g.entities.list()).items == [] + + +def test_cli_and_mcp_take_facts_with_the_text(tmp_path, capsys): + path = json_file(tmp_path, "facts.json", FACTS) + assert kuzu_main(tmp_path, "insert", "text", TEXT, "--source-id", "doc1", "--facts", path) == 0 + inserted = json.loads(capsys.readouterr().out) + assert sorted(entity["type"] for entity in inserted["entities"]) == ["Person", "Team"] + with mcp_session() as server: + result = run(server.insert_text(TEXT, source_id="doc1", facts=FACTS)) + assert [relation["type"] for relation in result["relations"]] == ["LEADS"] diff --git a/typescript/src/cli.ts b/typescript/src/cli.ts index b0b807cc..f82de8d0 100644 --- a/typescript/src/cli.ts +++ b/typescript/src/cli.ts @@ -42,7 +42,7 @@ import { DEFAULT_STANCE, DEFAULT_STATUS, type EvidenceInput, - type Extraction, + type FactsInput, type InsertResult, type JsonObject, type NeighborsResult, @@ -1700,6 +1700,7 @@ export function buildParser(): Command<[], GlobalOptions> { [], ) .option("--replace-source", "the text replaces --source-id's earlier versions: retire relations only they stated") + .option("--facts ", "a facts JSON file to store with the text instead of extracting, or '-' for stdin") .addOption(chunkingOption()) .addOption(callResolver()) .addOption(contradictionOption()) @@ -1714,6 +1715,7 @@ export function buildParser(): Command<[], GlobalOptions> { contradiction: o.contradiction as ContradictionMode | undefined, replace_source: o.replaceSource === true, chunking: o.chunking, + facts: o.facts === undefined ? undefined : (readJson(o.facts, "facts") as FactsInput), }) .then(inserted), ), @@ -1734,7 +1736,7 @@ export function buildParser(): Command<[], GlobalOptions> { .action((path, o, cmd) => emit(cmd, (g) => g.insert - .facts(readJson(path) as Extraction, { + .facts(readJson(path) as FactsInput, { source_id: o.sourceId, event_time: o.eventTime, resolver: (o.resolver as ResolverMode | undefined) ?? null, diff --git a/typescript/src/index.ts b/typescript/src/index.ts index efdd2d5c..d9337889 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -92,6 +92,7 @@ export { Extraction, ExtractionInstructions, ExtractionPrompts, + type FactsInput, type GraphDiff, type ImpactedEntity, type ImpactResult, diff --git a/typescript/src/insert.ts b/typescript/src/insert.ts index c25690b9..86ab8a1f 100644 --- a/typescript/src/insert.ts +++ b/typescript/src/insert.ts @@ -18,6 +18,7 @@ import { Extraction, ExtractionInstructions, ExtractionPrompts, + type FactsInput, type InsertResult, type InsertWarning, insertWarning, @@ -91,6 +92,8 @@ export interface InsertTextOptions { replace_source?: boolean; /** Split by token count or by heading. */ chunking?: Chunking; + /** Entities, relations, preferences, and decisions to store with the text instead of extracting them; evidence without a source_id cites source_id. */ + facts?: FactsInput | null; } export interface InsertFactsOptions { @@ -124,6 +127,7 @@ const TEXT_KEYS = keysOf({ contradiction: true, replace_source: true, chunking: true, + facts: true, }); export interface SyncOptions { @@ -520,6 +524,35 @@ export class Insert { requireSchemaForMode(options.schema_mode ?? this.graph.schemaMode, activeSchema ?? this.graph.schema); const callInstructions = asInput(ExtractionInstructions, options.instructions, "instructions"); const callPrompts = asInput(ExtractionPrompts, options.prompts, "prompts"); + if (options.facts != null) { + if (callInstructions != null || callPrompts != null) { + throw new ValidationError( + "instructions and prompts guide extraction, which facts skip; pass one or the other", + { + field: "facts", + }, + ); + } + return this.apply( + parseOrThrow(Extraction, inheritSource(options.facts, options.source_id ?? null), "facts"), + { + source_id: options.source_id ?? null, + parsed_text: text, + media_type: "text/plain", + metadata: options.metadata ?? null, + default_event_time: eventTime, + warnings: [], + replace_source: replaceSource, + chunking, + }, + activeSchema, + options.schema_mode ?? null, + options.resolver ?? null, + options.contradiction ?? null, + false, + null, + ); + } const extractor = this.extractorFor( callInstructions, callPrompts, @@ -661,11 +694,11 @@ export class Insert { * entity instead of failing the batch, and each one is reported as a "placeholder_created" warning. A later insert * or entities.create of an entity with that id fills it in. * - * @param facts (Extraction): the facts object. + * @param facts (FactsInput): the facts object; relation evidence may omit source_id to cite the call's. * @param options (InsertFactsOptions): the source id to record provenance under, event_time, the default event time for relations, preferences, and decisions that carry none of their own, and placeholders. * @return (InsertResult): what was inserted. */ - async facts(facts: Extraction, options: InsertFactsOptions = {}): Promise { + async facts(facts: FactsInput, options: InsertFactsOptions = {}): Promise { return traced( "selfgraph.insert.facts", { "selfgraph.namespace": this.graph.namespace }, @@ -677,17 +710,17 @@ export class Insert { /** * Validate and apply ready facts, as insert.facts does inside its span. * - * @param facts (Extraction): the facts object. + * @param facts (FactsInput): the facts object; relation evidence may omit source_id to cite the call's. * @param options (InsertFactsOptions): the insert.facts options. * @return (InsertResult): what was inserted. */ - private async applyFacts(facts: Extraction, options: InsertFactsOptions): Promise { + private async applyFacts(facts: FactsInput, options: InsertFactsOptions): Promise { checkOptions("insert.facts", options, FACTS_KEYS); requireOptionalText("source_id", options.source_id); const placeholders = options.placeholders ?? false; requireBool("placeholders", placeholders); const eventTime = parseTime(options.event_time, "event_time"); - const parsed = parseOrThrow(Extraction, facts, "facts"); + const parsed = parseOrThrow(Extraction, inheritSource(facts, options.source_id ?? null), "facts"); return this.apply( parsed, { @@ -709,3 +742,25 @@ export class Insert { ); } } + +/** + * Give relation evidence that names no source the call's source_id. + * + * @param facts (unknown): the facts as given. + * @param sourceId (string | null): the call's source id. + * @return (unknown): the facts, with each evidence item lacking a source_id citing the call's source. + */ +function inheritSource(facts: unknown, sourceId: string | null): unknown { + if (sourceId === null || !isPlainObject(facts) || !Array.isArray(facts.relations)) return facts; + const relations = facts.relations.map((rel: unknown) => + isPlainObject(rel) && Array.isArray(rel.evidence) + ? { + ...rel, + evidence: rel.evidence.map((ev: unknown) => + isPlainObject(ev) && ev.source_id === undefined ? { ...ev, source_id: sourceId } : ev, + ), + } + : rel, + ); + return { ...facts, relations }; +} diff --git a/typescript/src/mcp.ts b/typescript/src/mcp.ts index 098d6ceb..09956626 100644 --- a/typescript/src/mcp.ts +++ b/typescript/src/mcp.ts @@ -22,6 +22,7 @@ import { type EvidenceInput, type ExtractionInstructions, type ExtractionPrompts, + type FactsInput, Stance, Status, validationError, @@ -310,8 +311,10 @@ export const TOOLS: Tool[] = [ tool({ name: "insert_text", description: - "Extract and upsert facts from text; insert_text is a compatibility alias of upsert_text. Uses the configured LLM, or with none " + - "configured falls back to a built-in LLM-free extractor (coarser). event_time (ISO 8601 or relative such as 7d) is the default " + + "Extract and upsert facts from text; insert_text is a compatibility alias of upsert_text. Uses the configured LLM; with none " + + "configured, extract the entities and relations yourself and pass them as facts, because the built-in LLM-free extractor " + + "is coarse. With facts, nothing is extracted, the text is still stored as the source for passages, citations, and " + + "replace_source, and evidence without a source_id cites this one, and instructions and prompts must be left out. event_time (ISO 8601 or relative such as 7d) is the default " + "valid time for what is extracted; metadata is stored on the source. Idempotent: ids are derived " + "deterministically from content, so re-inserting the same text converges on the same graph instead of " + "duplicating it. Safe to retry. resolver (exact, default, fuzzy, or llm) overrides the server's entity " + @@ -336,6 +339,7 @@ export const TOOLS: Tool[] = [ prompts: optObj, replace_source: z.boolean().default(false), chunking: z.enum(CHUNKINGS).default("tokens"), + facts: optObj, }, run: async (g, a) => surfaced( @@ -351,6 +355,7 @@ export const TOOLS: Tool[] = [ schema_mode: a.schema_mode, instructions: a.instructions as ExtractionInstructions | null | undefined, prompts: a.prompts as ExtractionPrompts | null | undefined, + facts: a.facts as FactsInput | null | undefined, }), ), }), @@ -371,7 +376,8 @@ export const TOOLS: Tool[] = [ SCHEMA_ARGS + " placeholders stores a placeholder entity for a reference that is neither in the facts nor in the graph, " + "instead of failing, and reports each one as a placeholder_created warning; inserting an entity with that id " + - "later fills it in.", + "later fills it in. Evidence without a source_id cites source_id. To keep the source text for passages and " + + "citations, pass it with these facts to insert_text.", input: { facts: z.record(z.string(), z.any()), source_id: optStr, diff --git a/typescript/src/models.ts b/typescript/src/models.ts index 2df75196..2f6dc4a8 100644 --- a/typescript/src/models.ts +++ b/typescript/src/models.ts @@ -602,6 +602,13 @@ export const Extraction = z.strictObject({ }); export type Extraction = DeepReadonly>; export type ParsedExtraction = z.output; +export type FactsInput = Omit & { + readonly relations?: ReadonlyArray< + Omit & { + readonly evidence?: ReadonlyArray & { readonly source_id?: string }>; + } + >; +}; const DIRECT_PROVIDERS = [ "anthropic", diff --git a/typescript/src/runtime.ts b/typescript/src/runtime.ts index f546e6d1..a49f3f16 100644 --- a/typescript/src/runtime.ts +++ b/typescript/src/runtime.ts @@ -417,10 +417,11 @@ export function readText(path: string): string { * Read and parse a JSON file, or stdin when the path is "-". * * @param path (string): the file path, or "-". + * @param field (string | undefined): the argument at fault when the JSON is invalid. * @return (unknown): the parsed JSON. */ -export function readJson(path: string): unknown { - return parseJson(readText(path), ` in ${pyRepr(path)}`); +export function readJson(path: string, field?: string): unknown { + return parseJson(readText(path), ` in ${pyRepr(path)}`, field); } /** diff --git a/typescript/test/conformance.test.ts b/typescript/test/conformance.test.ts index 03cdbba9..97f1e61b 100644 --- a/typescript/test/conformance.test.ts +++ b/typescript/test/conformance.test.ts @@ -10,6 +10,7 @@ import { determinism, exitCodes, hydradbVersions, + insertWithFacts, kuzuOpenErrors, kuzuParamErrors, kuzuReadOnly, @@ -51,6 +52,13 @@ describe.skipIf(!PY)("cross-language conformance with the Python SDK", () => { expect(result).toEqual(py("code_hooks", "-", "-")); }); + it.skipIf(!live.get("kuzu"))( + "inserts text with caller facts and inherits the source id the same way in both languages", + async () => { + expect(await insertWithFacts()).toEqual(py("insert_with_facts", "-", "-")); + }, + ); + it.skipIf(!live.get("kuzu"))( "rejects empty Kuzu parameters with the same error fields in both languages", async () => { diff --git a/typescript/test/conformance/helpers.ts b/typescript/test/conformance/helpers.ts index cb109294..415a06f5 100644 --- a/typescript/test/conformance/helpers.ts +++ b/typescript/test/conformance/helpers.ts @@ -22,6 +22,7 @@ export function py( | "exit_codes" | "hydradb_versions" | "code_hooks" + | "insert_with_facts" | "code_ignore" | "code_walk" | "code_parse" diff --git a/typescript/test/conformance/py_side.py b/typescript/test/conformance/py_side.py index 441552c1..d33f4bf7 100644 --- a/typescript/test/conformance/py_side.py +++ b/typescript/test/conformance/py_side.py @@ -1978,6 +1978,43 @@ async def mcp_argument_errors(): return errors +async def insert_with_facts(): + """Insert text with caller facts whose evidence partly names no source, and read them back. + + @return (dict): the inserted ids and types, the tiers, the relation's evidence, the context, and the guard error. + """ + text = "Ann Lee leads the Payments team at Acme." + quote = "Ann Lee leads the Payments team" + facts = { + "entities": [{"type": "Person", "name": "Ann Lee"}, {"type": "Team", "name": "Payments"}], + "relations": [ + { + "from_entity": "person:ann-lee", + "type": "LEADS", + "to_entity": "team:payments", + "evidence": [{"quote": quote}, {"source_id": "other", "quote": quote}], + } + ], + } + async with SelfGraph(KuzuStore("")) as graph: + inserted = await graph.insert.text(text, source_id="doc1", facts=facts) + page = await graph.relations.evidence(inserted.relations[0].id) + context = (await graph.retrieve("who leads payments", numbered=True)).context + try: + await graph.insert.text(text, source_id="doc1", facts=facts, prompts={}) + guard = None + except ValidationError as exc: + guard = [exc.code, exc.field, str(exc)] + return { + "entities": [[entity.id, entity.type] for entity in inserted.entities], + "relations": [[relation.id, relation.type] for relation in inserted.relations], + "tiers": inserted.tiers, + "evidence": [[ev.source_id, ev.source_version, ev.quote] for ev in page.items], + "context": context, + "guard": guard, + } + + async def kuzu_param_errors(): """Bind empty containers that Kuzu cannot type and report the error both SDKs raise. @@ -5452,6 +5489,9 @@ async def main(): if cmd == "code_hooks": json.dump(code_hooks(), sys.stdout, ensure_ascii=False) return + if cmd == "insert_with_facts": + json.dump(await insert_with_facts(), sys.stdout, ensure_ascii=False) + return if cmd == "code_ignore": json.dump(code_ignore(), sys.stdout, ensure_ascii=False) return diff --git a/typescript/test/conformance/ts_side.ts b/typescript/test/conformance/ts_side.ts index 4f581fff..65c3b244 100644 --- a/typescript/test/conformance/ts_side.ts +++ b/typescript/test/conformance/ts_side.ts @@ -2428,6 +2428,54 @@ export async function kuzuParamErrors(): Promise ); } +/** + * Insert text with caller facts whose evidence partly names no source, and read them back. + * + * @return (Promise): the inserted ids and types, the tiers, the relation's evidence, the context, and the guard error. + */ +export async function insertWithFacts(): Promise { + const text = "Ann Lee leads the Payments team at Acme."; + const quote = "Ann Lee leads the Payments team"; + const facts = { + entities: [ + { type: "Person", name: "Ann Lee" }, + { type: "Team", name: "Payments" }, + ], + relations: [ + { + from_entity: "person:ann-lee", + type: "LEADS", + to_entity: "team:payments", + evidence: [{ quote }, { source_id: "other", quote }], + }, + ], + }; + const graph = new SelfGraph(new KuzuStore("")); + try { + await graph.initialize(); + const inserted = await graph.insert.text(text, { source_id: "doc1", facts }); + const page = await graph.relations.evidence(inserted.relations[0]!.id); + const context = (await graph.retrieve("who leads payments", { numbered: true })).context; + let guard: unknown[] | null = null; + try { + await graph.insert.text(text, { source_id: "doc1", facts, prompts: {} }); + } catch (exc) { + if (!(exc instanceof ValidationError)) throw exc; + guard = [exc.code, exc.field, exc.message]; + } + return { + entities: inserted.entities.map((entity) => [entity.id, entity.type]), + relations: inserted.relations.map((relation) => [relation.id, relation.type]), + tiers: inserted.tiers, + evidence: page.items.map((ev) => [ev.source_id, ev.source_version, ev.quote ?? null]), + context, + guard, + }; + } finally { + await graph.close(); + } +} + /** * Read a stored graph back through a read-only store, then open a database with no tables read-only. * diff --git a/typescript/test/insertWithFacts.test.ts b/typescript/test/insertWithFacts.test.ts new file mode 100644 index 00000000..2cb38672 --- /dev/null +++ b/typescript/test/insertWithFacts.test.ts @@ -0,0 +1,123 @@ +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { expect, it, vi } from "vitest"; +import { main } from "../src/cli.js"; +import { type FactsInput, type SelfGraph, ValidationError } from "../src/index.js"; +import { callTool, close, configure } from "../src/mcp.js"; +import { DEFAULT_SETTINGS } from "../src/runtime.js"; +import { forEachStore, freshGraphs, tempDir, tempKuzu } from "./helpers.js"; + +const TEXT = "Ann Lee leads the Payments team at Acme. In March, Bob Diaz joined Payments."; +const QUOTE = "Ann Lee leads the Payments team"; +const FACTS: FactsInput = { + entities: [ + { type: "Person", name: "Ann Lee" }, + { type: "Team", name: "Payments" }, + ], + relations: [ + { from_entity: "person:ann-lee", type: "LEADS", to_entity: "team:payments", evidence: [{ quote: QUOTE }] }, + ], +}; + +/** List a relation's evidence as tuples. @param g (SelfGraph): the graph. @param id (string): the relation id. @return (Promise>>): source id, version, and quote per record. */ +async function evidenceOf(g: SelfGraph, id: string): Promise>> { + return (await g.relations.evidence(id)).items.map((ev) => [ev.source_id, ev.source_version, ev.quote ?? null]); +} + +await forEachStore("insert.text with facts", (spec) => { + const open = freshGraphs(spec, "withfacts"); + + it("stores the source without extracting", async () => { + const g = open(); + const result = await g.insert.text(TEXT, { source_id: "doc1", facts: FACTS }); + expect(result.entities.map((entity) => entity.type).sort()).toEqual(["Person", "Team"]); + expect(result.relations.map((relation) => relation.type)).toEqual(["LEADS"]); + expect(Object.keys(result.tiers)).not.toContain("extraction"); + expect(await evidenceOf(g, result.relations[0]!.id)).toEqual([["doc1", result.source_version, QUOTE]]); + const retrieved = await g.retrieve("who leads payments", { numbered: true }); + expect(retrieved.context.split("\n")[0]).toBe(`SOURCE #1 | ${TEXT}`); + expect(retrieved.evidence![0]!.kind).toBe("passage"); + }); + + it("gives evidence the call's source_id unless it names one", async () => { + const g = open(); + const evidence = [ + { quote: QUOTE, source_id: undefined }, + { source_id: "other", quote: QUOTE }, + ]; + const facts = { ...FACTS, relations: [{ ...FACTS.relations![0]!, evidence }] } as FactsInput; + const result = await g.insert.facts(facts, { source_id: "doc2" }); + expect((await evidenceOf(g, result.relations[0]!.id)).sort()).toEqual([ + ["doc2", result.source_version, QUOTE], + ["other", "other:manual", QUOTE], + ]); + }); + + it("retires what only older versions stated on replace_source", async () => { + const g = open(); + const first = await g.insert.text(TEXT, { source_id: "doc1", facts: FACTS }); + const joined = { + entities: [ + { type: "Person", name: "Bob Diaz" }, + { type: "Team", name: "Payments" }, + ], + relations: [{ from_entity: "person:bob-diaz", type: "JOINED", to_entity: "team:payments" }], + } as FactsInput; + const second = await g.insert.text("Bob Diaz joined Payments.", { + source_id: "doc1", + replace_source: true, + facts: joined, + }); + expect(second.source_diff!.retired).toEqual([first.relations[0]!.id]); + expect(second.relations.map((relation) => relation.type)).toEqual(["JOINED"]); + }); + + it("rejects caller facts outside the schema in strict mode", async () => { + const g = open({ schema: { entities: [{ name: "Person" }] }, schema_mode: "strict" }); + const error = await g.insert.text(TEXT, { source_id: "doc1", facts: FACTS }).catch((exc: unknown) => exc); + expect(error).toBeInstanceOf(ValidationError); + expect((error as ValidationError).code).toBe("schema_violation"); + expect((await g.entities.list()).items).toEqual([]); + }); + + it.each([{ instructions: { entities: "people" } }, { prompts: {} }])("rejects facts with %o", async (extra) => { + const g = open(); + const error = await g.insert.text(TEXT, { source_id: "doc1", facts: FACTS, ...extra }).catch((exc: unknown) => exc); + expect(error).toBeInstanceOf(ValidationError); + expect([(error as ValidationError).code, (error as ValidationError).field]).toEqual(["invalid_argument", "facts"]); + expect((error as ValidationError).message).toBe( + "instructions and prompts guide extraction, which facts skip; pass one or the other", + ); + expect((await g.entities.list()).items).toEqual([]); + }); +}); + +it("takes facts with the text through the CLI and MCP", async () => { + const uri = tempKuzu("sg-withfacts-cli-"); + const path = join(tempDir("sg-withfacts-"), "facts.json"); + writeFileSync(path, JSON.stringify(FACTS)); + const flags = ["--store", "kuzu", "--uri", uri, "--namespace", "withfacts"]; + const out: string[] = []; + const write = vi.spyOn(process.stdout, "write").mockImplementation((chunk: unknown, ...rest: unknown[]) => { + out.push(String(chunk)); + (rest.find((r) => typeof r === "function") as (() => void) | undefined)?.(); + return true; + }); + try { + expect(await main([...flags, "insert", "text", TEXT, "--source-id", "doc1", "--facts", path])).toBe(0); + const inserted = JSON.parse(out.join("")) as { entities: Array<{ type: string }> }; + expect(inserted.entities.map((entity) => entity.type).sort()).toEqual(["Person", "Team"]); + } finally { + write.mockRestore(); + } + await configure({ ...DEFAULT_SETTINGS, store: "kuzu", uri, namespace: "withfacts-mcp" }); + try { + const { result, isError } = await callTool("insert_text", { text: TEXT, source_id: "doc1", facts: FACTS }); + expect(isError).toBe(false); + expect((result as { relations: Array<{ type: string }> }).relations.map((relation) => relation.type)).toEqual([ + "LEADS", + ]); + } finally { + await close(); + } +}); diff --git a/typescript/test/mcp.test.ts b/typescript/test/mcp.test.ts index 4f1976da..26b8efaf 100644 --- a/typescript/test/mcp.test.ts +++ b/typescript/test/mcp.test.ts @@ -339,7 +339,7 @@ describe("MCP tools over Kuzu", () => { await configure(); const keys = (name: string) => Object.keys(mcpTool(name).input).sort(); expect(keys("insert_text")).toEqual( - "chunking contradiction event_time instructions metadata prompts replace_source resolver schema schema_mode source_id text".split( + "chunking contradiction event_time facts instructions metadata prompts replace_source resolver schema schema_mode source_id text".split( " ", ), );