Metadata-Version: 2.4
Name: branching-story-kit
Version: 1.0.0
Summary: Zero-dependency branching narrative engine for interactive fiction, visual novels, and romance story apps: story-graph state tracking, gated choices, persistent memory log, save/export, static validator, and JSON Schema. By Ouba Studio.
Author-email: Ouba Studio <team@ouba.art>
License-Expression: MIT
Project-URL: Homepage, https://www.ouba.art
Project-URL: Repository, https://github.com/ouba-studio/branching-story-kit
Project-URL: Source, https://github.com/ouba-studio/branching-story-kit
Project-URL: Bug Tracker, https://github.com/ouba-studio/branching-story-kit/issues
Project-URL: Changelog, https://github.com/ouba-studio/branching-story-kit/blob/main/CHANGELOG.md
Project-URL: Documentation, https://jsr.io/@ouba-studio/branching-story-kit
Project-URL: Live Demo, https://ouba-studio.github.io/branching-story-kit/
Project-URL: Zenodo, https://doi.org/10.5281/zenodo.24514910
Project-URL: Benchmark Dataset, https://doi.org/10.7910/DVN/YEBHQR
Keywords: interactive-fiction,branching-narrative,visual-novel,romance,story-engine,narrative-engine,interactive-narrative,dating-sim,choose-your-own-adventure,text-adventure,game-dev,narrative-state-tracking,zero-dependency,json,ouba
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Games/Entertainment
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Markup
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Dynamic: license-file

# `branching-story-kit` (Python)

**Zero-dependency branching narrative engine for interactive fiction, visual novels, and romance story apps** — story-graph state tracking, gated choices, a persistent memory log, save/restore, a static validator, and a JSON Schema. Pure Python 3.10+, fully typed, MIT.

[![PyPI](https://img.shields.io/pypi/v/branching-story-kit?style=flat-square&color=c084fc)](https://pypi.org/project/branching-story-kit/)
[![Python](https://img.shields.io/badge/python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://pypi.org/project/branching-story-kit/)
[![Zenodo DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24514910.svg)](https://doi.org/10.5281/zenodo.24514910)
[![Harvard Dataverse DOI](https://img.shields.io/badge/Harvard%20Dataverse-10.7910%2FDVN%2FYEBHQR-2b6cb0?style=flat-square)](https://doi.org/10.7910/DVN/YEBHQR)
[![JSR](https://jsr.io/badges/@ouba-studio/branching-story-kit?style=flat-square)](https://jsr.io/@ouba-studio/branching-story-kit)
[![GitHub Pages — live demo](https://img.shields.io/badge/GitHub%20Pages-live%20demo-181717?style=flat-square&logo=github)](https://ouba-studio.github.io/branching-story-kit/)
[![Ouba — iOS · Android · Web](https://img.shields.io/badge/Ouba-iOS%20%C2%B7%20Android%20%C2%B7%20Web-c084fc?style=flat-square)](https://www.ouba.art/)
[![License: MIT](https://img.shields.io/badge/license-MIT-22c55e?style=flat-square)](./LICENSE)
[![dependencies: 0](https://img.shields.io/badge/dependencies-0-22c55e?style=flat-square)](./pyproject.toml)

Built in the open by **[Ouba Studio](https://www.ouba.art/)** — the team behind [Ouba](https://www.ouba.art/), free reader-first interactive fiction on web, iOS, and Android, and the [2026 AI Story Apps Benchmark](https://www.ouba.art/i-tested-ai-story-apps) (open data on [CERN Zenodo](https://doi.org/10.5281/zenodo.24511974) and [Harvard Dataverse](https://doi.org/10.7910/DVN/YEBHQR)).

This is the **Python port of the JavaScript/TypeScript package [`@ouba-studio/branching-story-kit`](https://github.com/ouba-studio/branching-story-kit)** ([JSR](https://jsr.io/@ouba-studio/branching-story-kit) · [npm](https://www.npmjs.com/package/@ouba-studio/branching-story-kit)). Same manifest, same semantics, same save-file shape — a route played in Python plays identically in the browser.

---

## Why `branching-story-kit`?

Most "interactive story" tooling is either a full game engine or a blank chat box. This kit is the small, boring, reliable layer in between: **a JSON story graph with explicit state**, so that what a reader did in turn 2 is still true in turn 15.

- **Zero dependencies** — one module, stdlib only, Python 3.10+. `dependencies = []`.
- **Relationship & flag state** — numeric effects *add*, everything else *assigns*; `requires` gates choices behind thresholds.
- **Persistent memory log** — `engine.remember("My cat's name is Marmalade.")` records reader-planted facts with turn numbers so long sessions don't drift.
- **`{{state}}` interpolation** in prose, with unknown placeholders left intact.
- **Free-text steering** — `set()` + `jump()` let typed input branch the plot without leaving the manifest.
- **Save / restore** — `export_save()` → `StoryEngine.import_save()` round-trips cursor, state, history, and memory.
- **Static validator + JSON Schema** — catch broken `next` links before you publish; validate manifests in your editor or CI.
- **Fully typed** — ships `py.typed` and inline annotations (`StoryEngine`, `SceneView`, `ValidationResult`).

## Install

```bash
pip install branching-story-kit
```

```bash
uv add branching-story-kit
# or
poetry add branching-story-kit
```

No compiled extensions, no transitive dependencies, no network calls at import time.

## Quickstart

```python
from branching_story_kit import StoryEngine, validate_story

story = {
    "id": "the-midnight-bookshop",
    "start": "start",
    "initialState": {"spark": 1, "trust": 1, "item": "none"},
    "scenes": {
        "start": {
            "title": "Rain on Bellweather Lane",
            "body": "Your {{item}} waits on the counter.",
            "choices": [
                {"label": "Take the mug", "next": "warm", "effects": {"spark": 2, "item": "Cardamom Tea"}},
                {"label": "Compare notes", "next": "warm", "effects": {"trust": 2}},
            ],
        },
        "warm": {"title": "Between the Stacks", "body": "Trust={{trust}} Spark={{spark}}", "ending": True},
    },
}

assert validate_story(story).valid

engine = StoryEngine(story)          # one instance == one reader session
view = engine.current()              # SceneView with gated choices filtered
print(view.body)                     # "Your none waits on the counter."
print(view.labels)                   # ["Take the mug", "Compare notes"]

view = engine.choose(0)              # applies effects, advances, returns the new scene
print(view.body)                     # "Trust=1 Spark=3"
print(engine.turn)                   # 2
print(engine.export_save())          # JSON: cursor + state + history + memory
```

### Gated choices

```python
{
    "label": "Tell him you kept the letter he wrote to you last winter, too.",
    "next": "end_letter",
    "requires": {"trust": 4},        # hidden until trust >= 4
}
```

`current()` filters gated choices out for you, so a UI can render `view.choices` without re-implementing the rules. `requires` uses JavaScript-style numeric coercion, so `"4"` counts and garbage counts as zero.

### Free-text steering

```python
engine.set("customLine", "Stay until the last page, then walk me home.")
engine.remember("Reader chose to stay past closing.")   # turn-stamped memory
engine.jump("end_custom")                              # effects optional
```

`remember()` ignores blank facts and stamps each entry with `{"turn": n, "fact": "..."}` — the same shape the JS engine writes.

### Save / restore

```python
saved = engine.export_save()                     # compact JSON string
restored = StoryEngine.import_save(saved, story)  # cursor, state, history, memory
```

`import_save()` accepts a JSON string **or** an already-parsed `dict`, and raises `SaveDataError` (a `ValueError`) on malformed or inconsistent payloads — never a bare `KeyError`.

### Static validation

```python
result = validate_story(story)
if not result:                       # ValidationResult is falsy when invalid
    raise SystemExit(result.errors)  # e.g. "Scene 'a' links to missing scene 'ghost'"
```

The validator never raises: garbage input yields `{"valid": False, "errors": [...]}`. A JSON Schema for editors and CI ships as package data:

```python
from pathlib import Path
import branching_story_kit

schema = Path(branching_story_kit.__file__).parent / "story.schema.json"
```

## API

| Name | What it does |
| :--- | :--- |
| `StoryEngine(story, initialState=None)` | Create a session. Raises `InvalidStoryError` on a manifest without `start`/`scenes`. |
| `engine.current()` | `SceneView` snapshot: `id`, `title`, `body`, `choices`, `ending`, `state` (copied). |
| `engine.turn` | Scene visits so far (the start scene counts as turn 1). |
| `engine.scene_id` / `engine.sceneId` | Current cursor (the second is the JS-style alias). |
| `engine.state` | Live reader state mapping. |
| `engine.history` | Ordered list of visited scene ids. |
| `engine.memory` | Turn-stamped memory log. |
| `engine.interpolate(text)` | Replace `{{key}}` placeholders; unknown keys stay literal. |
| `engine.set(key, value)` | Write one state value, return a copy of the state. |
| `engine.remember(fact)` | Append a trimmed, turn-stamped fact; blanks ignored. |
| `engine.choose(index)` | Take a visible choice by index; applies effects and advances. |
| `engine.jump(scene_id, effects=None)` | Jump straight to a scene (free-text steering). |
| `engine.export_save()` | Compact JSON of the whole session. |
| `StoryEngine.import_save(save, story)` | Restore a session from JSON string or mapping. |
| `validate_story(story)` | `ValidationResult(valid, errors)` — never raises. |
| `apply_effects(state, effects)` | Standalone helper: numbers add, others assign. |
| `interpolate(text, state)` | Standalone `{{key}}` interpolation. |

Errors: `BranchingStoryError` (a `ValueError`) is the base of `InvalidStoryError`, `UnknownSceneError`, `ChoiceError`, and `SaveDataError`.

## Play the demo — *The Midnight Bookshop*

A four-scene rivals-to-lovers branching romance with relationship meters, an inventory item, a trust-gated choice, a free-text steering moment, and four endings. It is the same manifest that powers the [GitHub Pages showcase](https://ouba-studio.github.io/branching-story-kit/) and the [itch.io build](https://ouba-art.itch.io/the-midnight-bookshop).

```bash
pip install branching-story-kit
python examples/play.py          # interactive terminal play-through
python examples/play.py --all    # print every authored route
```

Or headlessly:

```python
from branching_story_kit import StoryEngine
from examples.midnight_bookshop import story

engine = StoryEngine(story)
for scene in engine:             # engine is iterable: follows the first visible choice
    print(scene.title, scene.labels)
```

## Development

```bash
pip install -e ".[test]"
pytest                           # 69 tests, 100% passing
python -m build                  # wheel + sdist in dist/
```

The test-suite covers the engine, gating, interpolation, effects, memory, save/restore, the validator, the demo story's four routes, and packaging metadata (including "must stay zero-dependency").

## Compatibility with the JS package

| Behaviour | JS | Python |
| :--- | :--- | :--- |
| Manifest shape | `{"start", "scenes", "initialState"}` | identical |
| `requires` gating | `Number(state) >= Number(min)` | `_as_number()` equivalent |
| Numeric effects | add | add (booleans assign, as in JS) |
| `{{key}}` interpolation | unknown keys left literal | identical (`true`/`false` lowercase) |
| Save payload keys | `storyId, sceneId, state, history, memory` | identical |
| `choose(-1)` | out of bounds | out of bounds (never wraps) |

## Citation

If you use `branching-story-kit` in your research, product, or game, please cite it:

```bibtex
@software{ouba_studio_2026_branching_story_kit,
  author  = {{Ouba Studio}},
  title   = {branching-story-kit: A zero-dependency branching narrative engine for interactive fiction, visual novels, and romance story apps},
  year    = {2026},
  doi     = {10.5281/zenodo.24514910},
  url     = {https://github.com/ouba-studio/branching-story-kit},
  license = {MIT}
}
```

- **GitHub:** https://github.com/ouba-studio/branching-story-kit
- **Zenodo DOI:** https://doi.org/10.5281/zenodo.24514910
- **JSR:** https://jsr.io/@ouba-studio/branching-story-kit
- **Live demo:** https://ouba-studio.github.io/branching-story-kit/
- **Ouba Studio:** https://www.ouba.art/ · team@ouba.art
- **Companion benchmark dataset** (CC-BY-4.0): https://doi.org/10.7910/DVN/YEBHQR

## License

[MIT](./LICENSE) — © 2026 Ouba Studio.
