narrative-graph 0.3.1

Turn prose into candidate relational facts — entity detection, relation labeling, confidence scoring, entirely local.
Documentation

narrative-graph

Turn prose into candidate relational facts, entirely local. No LLM, no network. Entities, relations, confidence scores and spans, for Rust and Node.

CI CodeQL OpenSSF Scorecard crates.io License


narrative-graph reads prose and returns candidate (subject, relation, object) facts with a confidence score and the exact source span each one came from. No API key, no network call, no model download. It stores nothing and queries nothing — it's a producer you point at any store, or at no store at all.

The default build has zero dependencies. cargo tree prints the crate and nothing else; the extraction core compiles against the standard library alone, and CI fails if that ever stops being true. Serde, TypeScript bindings, the Node addon, and the CLI are each opt-in features that serve a boundary, never the core.

Input:

Elena is Marco's sister. Marco mentors Dev, who works at the Archive.

Output (measured, cargo run --features cli -- extract -):

dev --works_at--> archive 0.75 [39..68]
elena --sister_of--> marco 0.85 [0..23]
marco --mentors--> dev 0.78 [25..42]

Works with Rust 1.77+ and Node.js 18+, on macOS, Linux, and Windows. Pairs naturally with holographic-memory's Meaning Memory — memorizeTriplet / relate_phase expect exactly this shape — but has no dependency on it and no opinion on what you do with a candidate.

Install

npm

npm install narrative-graph

Cargo

[dependencies]
narrative-graph = "0.3"

GitHub

npm install writerslogic/narrative-graph

Cargo features

Feature Adds Dependencies
(default) The heuristic extraction pipeline none
serde Serialize/Deserialize on the public types serde
json JSON output serde, serde_json
bindings TypeScript declarations via ts-rs serde, ts-rs
node-api The Node addon napi, napi-derive, napi-build
cli The narrative-graph binary clap, anyhow
model Local DeBERTa relation extraction Tract, SentencePiece

What It Extracts

Sentences

Segmentation is hand-rolled rather than a naive split on ./!/?, because narrative prose is made of exactly the constructs a naive splitter breaks on: honorifics (Dr. Smith went home.), initials (J. R. R. Tolkien), ellipses (She paused... then left.), and quoted dialogue with attribution ("Who are you?" she asked. is one sentence, not two). Sentences are returned as borrowed slices of the input, so segmentation allocates nothing per sentence.

Entities

The document's character profiles combine named mentions, unambiguous short forms, title and pronoun cues, and explicit family links. The same profiles resolve narration such as "he", "her sister", and "the old man" before the relation rules run. A description needs support in the text, such as "Mr. Hale, the old man," and a family role needs a unique referent. Caller aliases can supply identities the text leaves ambiguous.

You supply: { aliases: { "Marcus": "marcus_hale", "Mr Marcus Hale": "marcus_hale" } } Result: either mention resolves to marcus_hale in every candidate.

Keys match the mention's surface form exactly, and . is a separator, so the key is Mr Marcus Hale.

A wholly lowercase key is a lexicon entry instead: the phrase is searched for in the text as a literal, word-bounded, case-insensitive match and becomes a mention of the canonical name, which is how a phrase no capitalized-run detector can see reaches a referent. { aliases: { "the detective": "marcus" } } turns "The detective is Ms. Chen's brother." into marcus brother_of ms_chen. A lexicon match overlapping a mention already detected is dropped, so a key adds a mention and never replaces one: with "detective": "marcus", "Detective Marcus" stays detective_marcus. A lexicon key is therefore for a phrase carrying no capitalized name — a key like "ms. chen" spans one, and the run Ms Chen is already a mention, so the key never fires. A pronoun can take a lexicon mention as its referent, so "The detective said he was Ms. Chen's brother." reaches marcus rather than the sentence-opening the; a pronoun the mention itself covers is replaced by it.

Relations

Verb-phrase heuristics between two entity candidates in the same clause — familial, social, professional, and spatial relations ("sister of," "mentors," "works at," "located in"). Surface forms normalize to a small controlled vocabulary (sister_of, mentors, works_at, ...) rather than passing through raw verb phrases, so "trains," "is the mentor of," and "mentors" all collapse to the same relation type. Supply your own ontology map to override or extend the defaults.

Explainability

Every candidate reports the rule that produced it, not just a score — possessive-sister-pattern, verb-mentor-pattern, verb-works-at-pattern, relative-mentor-pattern, relative-works-at-pattern. A confidence number alone tells you nothing about why the pipeline believes something; the rule name does.

Confidence and Span

Every candidate carries a confidence score from the extraction rule's pattern strength and how close the subject and object are in the source text, plus the byte offset of its extracted span — a range covering the subject, the object, and the token that licensed the relation. Gate on a threshold, route low-confidence candidates to human review, or fetch source context for display.

analyze_document adds a calibrated estimate to observations from rule families represented in the reviewed public sample. Use facts_at_least to filter those observations, or calibratedConfidence in Node. The evaluation reports the evidence behind the estimates. Evaluation

Story history and events

analyze_document returns a timeline with each statement's span and polarity. Engagement, marriage, widowhood, divorce, friendship, enmity and alliance have state labels. The order follows the text, including when a story recounts earlier events. Explicit phrases such as "no longer Dev's friend" mark the end of a state. The events output covers explicit duels, proposals, journeys and deaths with a named or resolved actor, plus a target and location where the sentence supplies them.

The mentions output shows the source spans linked to each character ID. The knowledge output preserves the proposition or topic and the recipient of a statement such as "Nora told her about Dev's departure." Grounded topics also produce learned_about, knows_about, or told_about relations. Direct acquaintance uses knows.

Conversation view

analyze_document and analyzeDocumentNapi return dialogue.lines in source order. Each recognized quoted utterance has its own record, even when the same pair speaks repeatedly. speaker and listener are character IDs when the text supports an attribution. dialogue.unattributed counts lines missing either one. For a share-of-dialogue calculation, use spoken_spans in Rust or spokenSpans in Node to slice the quoted text around any interleaved narration. The ranges include quotation marks and use the same offsets as other evidence.

The English reader uses speech tags, direct addresses and two-person turn-taking. The Chinese reader uses speech tags and direct addresses with names from caller aliases or recognized titles. Character coreference, events and knowledge extraction use the English reader.

Chapters and series

Use Series in Rust or NarrativeSeries in Node to analyze a chapter at a time. Assign each chapter a book number, chapter number and revision number. Updating an existing key replaces that chapter's evidence. Passing the cached revision reuses its analysis. The merged graph retains chapter-relative spans. Set a common ID in Options.aliases for forms such as "Mr Darcy" and "Fitzwilliam Darcy" to keep the same character across books and revisions. Query a pair with relationship_history in Rust or relationshipHistory in Node to read its state changes in book, chapter and source order.

API

Item What it does
extract_candidate_triples(text, &Options) Run the heuristic pipeline over a passage
Options { aliases, min_confidence, rejections, ontology, language } Alias map, confidence floor, rejected triples, relation-vocabulary overrides, and the text's language (Language::English by default, or Language::Chinese)
TripleCandidate { subject, relation, object, confidence, span, rule } One candidate fact; span is a byte range into the input, rule names the pattern that produced it
extract_aggregates(text, &Options) Same pipeline, collapsed per fact instead of per sentence: one entry per triple, ordered by where the document first states it
AggregateTriple { subject, relation, object, polarity, confidence, spans, rules } One fact with every span that stated it; confidence is the best of them, and repetition does not raise it
find_conflicts(text, &Options) Claims a passage makes that cannot both be true: a fact and its denial, or two subjects where the relation admits one
Conflict { kind, left, right } Both sides with their evidence; the crate does not decide which one the manuscript meant
analyze(text, &Options) Candidates, aggregates and conflicts from one pass, as Analysis { candidates, aggregates, conflicts }
analyze_document(text, &Options) Relation analysis, linked mentions, character profiles, dialogue, story history, events, and knowledge
Series::update_chapter(position, revision, text) Add or replace a chapter and keep its current evidence in Series::aggregates()
narrative-graph extract chapter.txt --min-confidence 0.6 --format json
narrative-graph extract 紅樓夢.txt --language chinese

The CLI takes no alias map, so on Chinese text it finds only names written with a title (王夫人, 邢氏); bare given names such as 黛玉 need aliases through the library.

Installed alongside the crate (cargo install narrative-graph --features cli provides the narrative-graph binary), the same way holographic-memory ships hms-admin and hms-eval as bins in its own crate rather than separate packages. Useful for shell pipelines, CI checks, and inspecting output before wiring the library into an application.

For English prose, add the model feature to use a local student checkpoint alongside the rules. Training and evaluation

cargo run --release --features cli,model -- extract chapter.txt --model /path/to/checkpoint

In Rust, load the checkpoint once with StudentModel::load and call extract_candidate_triples or extract_aggregates on it. Both run locally on the CPU.

Function What it does
extractCandidateTriplesNapi(text, opts?) Run the heuristic pipeline over a passage
extractAggregatesNapi(text, opts?) / findConflictsNapi(text, opts?) Per-fact aggregates and conflicts, as in Rust
analyzeNapi(text, opts?) All three results from one pass
analyzeAsyncNapi(text, opts?) analyzeNapi on the libuv worker pool; returns a Promise and leaves the calling thread free
analyzeDocumentNapi(text, opts?) Relation analysis, linked mentions, character profiles, dialogue, timeline, events, and knowledge
new NarrativeSeries(opts?) Incrementally index chapters with updateChapter(book, chapter, revision, text)

Spans in Node are UTF-16 code unit offsets, so text.slice(span[0], span[1]) returns the evidence. The Rust API reports UTF-8 byte offsets; the two differ on non-ASCII text.

opts accepts aliases, minConfidence, rejections, ontology, and language ('english' or 'chinese'). The package exports TypeScript definitions through index.d.ts.

Guides

Requirements

  • Rust 1.77+ or Node.js 18+
  • No API key, no network access, no external service of any kind

Development

git clone https://github.com/writerslogic/narrative-graph.git
cd narrative-graph
cargo test                          # segmentation + heuristic pipeline
cargo test --all-features           # adds the ts-rs binding-export tests
cargo tree                          # should print this crate and nothing else
npm install && npm test             # node --test tests/node
npm run test:types                  # strict TS check against generated bindings

TypeScript definitions in bindings/ are generated from the Rust types via ts-rs — don't hand-edit them.

Why narrative-graph

Hand-written regex General-purpose NLP toolkit LLM-based extraction narrative-graph
Runs offline, no API key yes yes no yes
Tuned for narrative prose (dialogue attribution, familial/social relations) you build it no depends on prompt yes
Confidence score per candidate no model-dependent inconsistent across calls yes
Source span on every candidate you build it sometimes rarely yes
Cost per extraction free, but brittle free, general-purpose API cost + latency free, microsecond-scale
Output shape ready for a relational store you build it you build it you parse it yes -- matches memorizeTriplet/relate_phase

narrative-graph isn't trying to out-perform an LLM at open-domain relation extraction — it's trying to be the thing you reach for when a manuscript's characters and relationships need to become structured facts, offline, cheaply, and repeatably, with enough provenance on each candidate that a human or a downstream store can decide what to trust.

Contributing

We welcome contributions of all sizes. Check the issue tracker for good first issue labels, or see CONTRIBUTING.md for development setup.

The sentence-level pipeline, whole-document aggregation, cross-sentence pronoun linking, and contradiction detection are all in place; the design discussion behind each is preserved in the closed enhancement issues. New relation forms and language packs follow the same path: open an issue stating the prose pattern and how the result will be measured, then a patch.

Areas where help is especially welcome:

  • Additional relation-verb patterns for non-English narrative conventions
  • Integration examples for stores other than holographic-memory

Security

Found a vulnerability? Please report it privately — see SECURITY.md.

License

Apache-2.0 © WritersLogic, Inc.