canonarc 0.1.0__tar.gz
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.
- canonarc-0.1.0/LICENSE +21 -0
- canonarc-0.1.0/PKG-INFO +422 -0
- canonarc-0.1.0/README.md +386 -0
- canonarc-0.1.0/pyproject.toml +72 -0
- canonarc-0.1.0/setup.cfg +4 -0
- canonarc-0.1.0/src/canonarc/__init__.py +119 -0
- canonarc-0.1.0/src/canonarc/cli.py +159 -0
- canonarc-0.1.0/src/canonarc/embedders.py +233 -0
- canonarc-0.1.0/src/canonarc/engine.py +1830 -0
- canonarc-0.1.0/src/canonarc/episodic.py +192 -0
- canonarc-0.1.0/src/canonarc/extractors.py +790 -0
- canonarc-0.1.0/src/canonarc/hooks.py +76 -0
- canonarc-0.1.0/src/canonarc/models.py +289 -0
- canonarc-0.1.0/src/canonarc/presets.py +352 -0
- canonarc-0.1.0/src/canonarc/py.typed +0 -0
- canonarc-0.1.0/src/canonarc/resolver.py +220 -0
- canonarc-0.1.0/src/canonarc/store.py +2052 -0
- canonarc-0.1.0/src/canonarc/voice.py +397 -0
- canonarc-0.1.0/src/canonarc.egg-info/PKG-INFO +422 -0
- canonarc-0.1.0/src/canonarc.egg-info/SOURCES.txt +33 -0
- canonarc-0.1.0/src/canonarc.egg-info/dependency_links.txt +1 -0
- canonarc-0.1.0/src/canonarc.egg-info/entry_points.txt +2 -0
- canonarc-0.1.0/src/canonarc.egg-info/requires.txt +12 -0
- canonarc-0.1.0/src/canonarc.egg-info/top_level.txt +1 -0
- canonarc-0.1.0/tests/test_critique_and_pitfalls.py +547 -0
- canonarc-0.1.0/tests/test_engine_e2e.py +211 -0
- canonarc-0.1.0/tests/test_episodic_memory.py +394 -0
- canonarc-0.1.0/tests/test_epistemic_state.py +488 -0
- canonarc-0.1.0/tests/test_extensibility_and_pitfalls.py +292 -0
- canonarc-0.1.0/tests/test_multiparty_voice.py +257 -0
- canonarc-0.1.0/tests/test_refactoring_and_critique_fixes.py +684 -0
- canonarc-0.1.0/tests/test_sliding_window_halo.py +250 -0
- canonarc-0.1.0/tests/test_store_lineage.py +382 -0
- canonarc-0.1.0/tests/test_synthetic_story_e2e.py +852 -0
- canonarc-0.1.0/tests/test_voice_gates.py +303 -0
canonarc-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CanonArc contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
canonarc-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: canonarc
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tier 1-6 Temporal Graph, Episodic Ledger, Voice Bank & Causal Time-Travel Engine for LLMs
|
|
5
|
+
Author: CanonArc Contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/jovistos/canonarc
|
|
8
|
+
Project-URL: Repository, https://github.com/jovistos/canonarc
|
|
9
|
+
Project-URL: Documentation, https://github.com/jovistos/canonarc/tree/main/docs
|
|
10
|
+
Project-URL: Issues, https://github.com/jovistos/canonarc/issues
|
|
11
|
+
Keywords: memory,graph,vector,time-travel,epistemic,llm,interactive-fiction,visual-novel,localization,simulation
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Games/Entertainment :: Role-Playing
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: pydantic>=2.0
|
|
26
|
+
Requires-Dist: numpy>=1.26
|
|
27
|
+
Requires-Dist: rapidfuzz>=3.0
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
30
|
+
Requires-Dist: ruff>=0.4; extra == "dev"
|
|
31
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
32
|
+
Provides-Extra: notebooks
|
|
33
|
+
Requires-Dist: jupyterlab>=4.0; extra == "notebooks"
|
|
34
|
+
Requires-Dist: ipykernel>=6.0; extra == "notebooks"
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
<p align="center">
|
|
38
|
+
<img src="https://raw.githubusercontent.com/jovistos/canonarc/main/docs/assets/banner.jpg" alt="canonarc — Branchable, spoiler-free narrative memory and world-state engine for LLMs" width="100%" />
|
|
39
|
+
</p>
|
|
40
|
+
|
|
41
|
+
<h1 align="center"><code>canonarc</code></h1>
|
|
42
|
+
|
|
43
|
+
<p align="center">
|
|
44
|
+
<strong>Branchable, spoiler-free narrative memory & world-state engine for LLM games, interactive fiction, localization, and multi-agent simulations — in a single SQLite file.</strong>
|
|
45
|
+
</p>
|
|
46
|
+
|
|
47
|
+
<p align="center">
|
|
48
|
+
<a href="https://github.com/jovistos/canonarc/actions/workflows/ci.yml"><img src="https://github.com/jovistos/canonarc/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
|
|
49
|
+
<img src="https://img.shields.io/badge/python-3.11%2B-blue?style=flat-square" alt="Python 3.11+" />
|
|
50
|
+
<img src="https://img.shields.io/badge/typing-PEP%20561%20py.typed-3776AB?style=flat-square" alt="PEP 561 Typed" />
|
|
51
|
+
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="MIT License" /></a>
|
|
52
|
+
</p>
|
|
53
|
+
|
|
54
|
+
<p align="center">
|
|
55
|
+
<a href="docs/handbook.md"><strong>Handbook</strong></a> •
|
|
56
|
+
<a href="docs/architecture.md">Architecture</a> •
|
|
57
|
+
<a href="docs/epistemics-and-pov.md">Epistemics & POV</a> •
|
|
58
|
+
<a href="examples/README.md">Examples</a> •
|
|
59
|
+
<a href="docs/benchmarks.md">Benchmarks</a> •
|
|
60
|
+
<a href="docs/api-reference.md">API Reference</a>
|
|
61
|
+
</p>
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## Why `canonarc`?
|
|
66
|
+
|
|
67
|
+
Most LLM memory frameworks (`mem0`, `Zep`, `LangMem`) are built for **conversational chatbots** running in continuous wall-clock time. They break down in **Interactive Fiction, Visual Novels (Ren'Py / Ink), Multi-Agent Simulations, Creative Writing Co-Pilots, and Sequential Localization Pipelines**, where time advances in discrete **causal steps** (turns, scenes, ticks, or chunks) and world state must be **rewindable, branchable, character-scoped, and spoiler-free**.
|
|
68
|
+
|
|
69
|
+
### The 6-Tier World-State Model
|
|
70
|
+
|
|
71
|
+
`canonarc` unifies narrative state, dialogue voice, and episodic memory inside a single append-only SQLite database (or `:memory:`):
|
|
72
|
+
|
|
73
|
+
| Tier | Layer | What It Tracks |
|
|
74
|
+
| :---: | :--- | :--- |
|
|
75
|
+
| **Tier 1** | **Base Entity Attributes** | Immutable character/item metadata seeded at step 0 (gender, declension, archetypes, exonyms). |
|
|
76
|
+
| **Tier 2** | **Asymmetric Dyadic Edges** | Directed relationships (`A → B ≠ B → A`) such as register, tone, trust, or hidden `facade` vs. `stance`. |
|
|
77
|
+
| **Tier 3** | **Rolling State & Trajectories** | Point-in-time entity/edge state deltas with windowed history (`prior_state`, `prior_step`, `revision_count`). |
|
|
78
|
+
| **Tier 4** | **Temporal Versioning & 1-Hop Coreference** | Strict `step < current_step` resolution, alias linking (`"the old wizard"` → `char_merlin`), and co-present vs. background separation. |
|
|
79
|
+
| **Tier 5** | **Gated Voice Bank** | Empirical historical dialogue anchors filtered by speaker and active register/tone, protected by a 2-stage anti-drift gate. |
|
|
80
|
+
| **Tier 6** | **Episodic Ledger & Epistemics** | N-ary plot events with causal provenance (`caused_by_episode_id`) and per-character knowledge (`direct`, `told`, `deceived`, `forgotten`, `suppressed`). |
|
|
81
|
+
|
|
82
|
+
### How It Fits in Your Loop
|
|
83
|
+
|
|
84
|
+
```text
|
|
85
|
+
Scene Text / Tick
|
|
86
|
+
│
|
|
87
|
+
▼
|
|
88
|
+
┌──────────────────────────────────────────────────────────┐
|
|
89
|
+
│ step_transaction(step, text, pov_entity_ids=[...]) │
|
|
90
|
+
│ 1. Retrieve Tiers 1–6 strictly at (step < current) │
|
|
91
|
+
│ 2. Project through POV lens (redact secrets/disguises) │
|
|
92
|
+
└──────────────────────────┬───────────────────────────────┘
|
|
93
|
+
│ formatted prompt block
|
|
94
|
+
▼
|
|
95
|
+
Your LLM / Game Loop
|
|
96
|
+
│ generated scene / delta
|
|
97
|
+
▼
|
|
98
|
+
┌──────────────────────────────────────────────────────────┐
|
|
99
|
+
│ Extract StepDelta + 2-Stage Anti-Drift Voice Gate │
|
|
100
|
+
│ Atomic commit to single-file SQLite lineage tree │
|
|
101
|
+
└──────────────────────────────────────────────────────────┘
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## How `canonarc` Compares
|
|
107
|
+
|
|
108
|
+
| Capability | Chatbot Memory (`mem0`, `Zep`, `LangMem`) | Storyworld / GraphRAG (`Graphiti`, `ComoRAG`) | `canonarc` |
|
|
109
|
+
| :--- | :--- | :--- | :--- |
|
|
110
|
+
| **Time Model** | Continuous wall-clock timestamps | Wall-clock or linear chapter order | **Discrete causal steps (`step: int`)** + flashback-safe `story_time` |
|
|
111
|
+
| **Branching & Rollback** | Linear history only | None or heavy subgraph copies | **Zero-copy SQLite lineage tree** (`0.09 ms` branch, `0.07 ms` undo) |
|
|
112
|
+
| **Character POV & Secrets** | Omniscient queries | Omniscient world graph | **Per-POV epistemic projection** (`direct`, `told`, `deceived`, disguise masking) |
|
|
113
|
+
| **Dialogue Voice Control** | None | Unfiltered prose retrieval (prone to drift) | **Tier 5 Voice Bank** (2-stage anti-drift gate + dyadic register filtering) |
|
|
114
|
+
| **State + Event Provenance** | Flat facts or key-value dicts | Nodes/edges or text chunks | **Tiers 1–4 State Graph** linked to **Tier 6 Episodes** via `caused_by_episode_id` |
|
|
115
|
+
| **Storage & Dependencies** | Cloud APIs / Vector DB + Graph DB | Neo4j / Kuzu / FalkorDB + Vector DB | **Single `.sqlite` file** (`pydantic`, `numpy`, `rapidfuzz` only) |
|
|
116
|
+
|
|
117
|
+
### When to Choose Something Else
|
|
118
|
+
`canonarc` is intentionally scoped to storyworlds, simulations, and discrete-step pipelines (see [Domains of Application](docs/domains-of-application.md)). Consider another tool if you need:
|
|
119
|
+
- **Continuous wall-clock enterprise chatbots or CRM logs**: Systems built around real-world validity timestamps (`t_valid` / `t_invalid`) like `Zep` or `Graphiti` are a better fit.
|
|
120
|
+
- **Million-document static corpus RAG or multi-hop analytical QA**: `canonarc` uses in-memory NumPy scoring over storyworld-scale histories and 1-hop graph expansion; dedicated vector stores or full graph databases (e.g., Neo4j) suit massive static corpora.
|
|
121
|
+
- **High-concurrency multi-writer distributed backends**: Single-file SQLite excels for local saves, game loops, and per-session sandboxes, not horizontally sharded multi-tenant writes.
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## Quickstart
|
|
126
|
+
|
|
127
|
+
### Installation
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
pip install canonarc
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
*(Requires Python 3.11+. Core dependencies: `pydantic>=2.0`, `numpy>=1.26`, `rapidfuzz>=3.0`, and stdlib `sqlite3`. To install from source: `pip install git+https://github.com/jovistos/canonarc.git`.)*
|
|
134
|
+
|
|
135
|
+
### 1. The Transactional LLM Loop (`step_transaction`)
|
|
136
|
+
|
|
137
|
+
For interactive game loops, visual novels, and automated LLM pipelines, `step_transaction()` handles spoiler-free retrieval, LLM extraction, anti-drift voice gating, and atomic commits in one block:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from canonarc import CanonArcEngine, OpenAICompatibleExtractor
|
|
141
|
+
|
|
142
|
+
engine = CanonArcEngine(
|
|
143
|
+
"story_save.sqlite",
|
|
144
|
+
extractor=OpenAICompatibleExtractor.from_gemini(), # or .from_lmstudio(), .from_deepseek()
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
with engine.step_transaction(step=85, text=scene_text, pov_entity_ids=["char_arthur"]) as tx:
|
|
148
|
+
# 1. Point-in-time context (clean on reruns, zero forward spoiler leakage)
|
|
149
|
+
prompt = engine.format_context(tx.context)
|
|
150
|
+
|
|
151
|
+
# 2. Generate the next scene or dialogue with your LLM
|
|
152
|
+
generated_scene = call_llm(prompt)
|
|
153
|
+
|
|
154
|
+
# 3. Extract StepDelta JSON + Gate 1/2 voice exemplars & commit atomically
|
|
155
|
+
tx.extract_and_commit(generated_scene)
|
|
156
|
+
# Or commit deterministic game-engine deltas directly:
|
|
157
|
+
# tx.commit(delta=my_step_delta, exemplars=candidate_lines)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### 2. Explicit World-State Walkthrough (No LLM Required)
|
|
161
|
+
|
|
162
|
+
You can also drive `canonarc` deterministically from a game engine or script:
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
from canonarc import (
|
|
166
|
+
CanonArcEngine, EntityRecord, StepDelta,
|
|
167
|
+
EntityDelta, EdgeDelta, EpisodeRecord, VoiceExemplar,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
engine = CanonArcEngine("story_save.sqlite") # or ":memory:"
|
|
171
|
+
|
|
172
|
+
# Seed entities & 1-hop alias (Step 0)
|
|
173
|
+
engine.register_entity(
|
|
174
|
+
EntityRecord(entity_id="char_arthur", canonical_name="Arthur", base_attributes={"title": "King", "gender": "M"}),
|
|
175
|
+
step=0,
|
|
176
|
+
)
|
|
177
|
+
engine.register_entity(
|
|
178
|
+
EntityRecord(entity_id="char_merlin", canonical_name="Merlin", base_attributes={"title": "Court Wizard", "gender": "M"}),
|
|
179
|
+
aliases=["the old wizard"],
|
|
180
|
+
step=0,
|
|
181
|
+
)
|
|
182
|
+
engine.register_entity(
|
|
183
|
+
EntityRecord(entity_id="char_mordred", canonical_name="Mordred", base_attributes={"title": "Knight", "gender": "M"}),
|
|
184
|
+
step=0,
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# Seed initial relationship (Step 10) & Voice Bank anchors (Step 15)
|
|
188
|
+
engine.commit_step(
|
|
189
|
+
step=10,
|
|
190
|
+
delta=StepDelta(edges=[
|
|
191
|
+
EdgeDelta(source_id="char_arthur", target_id="char_merlin", state={"register": "formal", "tone": "respectful"})
|
|
192
|
+
]),
|
|
193
|
+
)
|
|
194
|
+
engine.index_voice_exemplars(
|
|
195
|
+
step=15,
|
|
196
|
+
exemplars=[
|
|
197
|
+
VoiceExemplar(
|
|
198
|
+
speaker_id="char_arthur", step=15,
|
|
199
|
+
text="I beseech your counsel, venerable wizard, for the kingdom stands upon the precipice.",
|
|
200
|
+
metadata={"register": "formal", "tone": "respectful"}, quality_score=9.5,
|
|
201
|
+
),
|
|
202
|
+
VoiceExemplar(
|
|
203
|
+
speaker_id="char_arthur", step=15,
|
|
204
|
+
text="Enough riddles, old man — answer me plainly or leave this hall!",
|
|
205
|
+
metadata={"register": "informal", "tone": "furious"}, quality_score=9.2,
|
|
206
|
+
),
|
|
207
|
+
],
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
# Step 82: Argument occurs -> mood, stance, and causal episode committed together
|
|
211
|
+
engine.commit_step(
|
|
212
|
+
step=82,
|
|
213
|
+
delta=StepDelta(
|
|
214
|
+
entities=[EntityDelta(
|
|
215
|
+
entity_id="char_arthur", state={"mood": "furious"},
|
|
216
|
+
caused_by_episode_id="ep_step82_prophecy_dispute",
|
|
217
|
+
reason="Discovered Merlin concealed the prophecy",
|
|
218
|
+
)],
|
|
219
|
+
edges=[EdgeDelta(
|
|
220
|
+
source_id="char_arthur", target_id="char_merlin",
|
|
221
|
+
state={"register": "informal", "tone": "furious"},
|
|
222
|
+
caused_by_episode_id="ep_step82_prophecy_dispute",
|
|
223
|
+
reason="Concealed the dragon prophecy",
|
|
224
|
+
)],
|
|
225
|
+
episodes=[EpisodeRecord(
|
|
226
|
+
episode_id="ep_step82_prophecy_dispute",
|
|
227
|
+
predicate="argument",
|
|
228
|
+
summary="Arthur confronted Merlin over the concealed dragon prophecy in the council chamber.",
|
|
229
|
+
participants={"char_arthur": "actor", "char_merlin": "target"},
|
|
230
|
+
witnesses=["char_arthur", "char_merlin"],
|
|
231
|
+
salience=8.5,
|
|
232
|
+
)],
|
|
233
|
+
),
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
# Step 85: Unified Tier 1–6 retrieval ("the old wizard" resolves to char_merlin)
|
|
237
|
+
context = engine.retrieve_context(
|
|
238
|
+
step=85,
|
|
239
|
+
text='Arthur glared at the old wizard while Mordred watched. "Speak truth now!"',
|
|
240
|
+
mentions=["Arthur", "the old wizard", "Mordred"],
|
|
241
|
+
top_k_voice=3,
|
|
242
|
+
top_k_episodes=5,
|
|
243
|
+
)
|
|
244
|
+
print(engine.format_context(context))
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
**Rendered output of `engine.format_context(context)`:**
|
|
248
|
+
|
|
249
|
+
```markdown
|
|
250
|
+
### Active Scene Narrative Context (Step: 85)
|
|
251
|
+
|
|
252
|
+
#### Characters Present & State:
|
|
253
|
+
- **Arthur** (char_arthur): mood: furious [reason: Discovered Merlin concealed the prophecy]
|
|
254
|
+
- **Merlin** (char_merlin): mood: neutral
|
|
255
|
+
- **Mordred** (char_mordred): mood: neutral
|
|
256
|
+
|
|
257
|
+
#### Interpersonal Stances & Register:
|
|
258
|
+
- char_arthur → char_merlin: register=informal, tone=furious, trust=0.0 (because: Concealed the dragon prophecy)
|
|
259
|
+
|
|
260
|
+
#### Episodic Memory (Relevant Past Events):
|
|
261
|
+
- [Step 82 | argument | known to: char_arthur, char_merlin | ignorant: char_mordred] Arthur confronted Merlin over the concealed dragon prophecy in the council chamber.
|
|
262
|
+
|
|
263
|
+
#### Voice Bank (Historical Dialogue Anchors):
|
|
264
|
+
- char_arthur [informal, furious]: "Enough riddles, old man — answer me plainly or leave this hall!"
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
---
|
|
268
|
+
|
|
269
|
+
## Core Capabilities
|
|
270
|
+
|
|
271
|
+
### Anti-Metagaming, POV Projection & Deception
|
|
272
|
+
|
|
273
|
+
Project the entire 6-tier world state through a character's eyes so NPCs never act on secrets they didn't witness (see [Epistemic State, Disguises & POV Projection](docs/epistemics-and-pov.md)):
|
|
274
|
+
|
|
275
|
+
```python
|
|
276
|
+
# Query Step 85 strictly from Mordred's POV (absent at Step 82)
|
|
277
|
+
mordred_pov = engine.retrieve_context(
|
|
278
|
+
step=85,
|
|
279
|
+
text="Mordred observed Arthur and Merlin.",
|
|
280
|
+
mentions=["Arthur", "Merlin", "Mordred"],
|
|
281
|
+
pov_entity_ids=["char_mordred"],
|
|
282
|
+
)
|
|
283
|
+
# Mordred sees Arthur is furious, but the secret episode & causal reason are redacted:
|
|
284
|
+
# mordred_pov.episodes == []
|
|
285
|
+
# arthur.reason is None
|
|
286
|
+
|
|
287
|
+
# Feed Mordred a deceptive cover story at Step 86
|
|
288
|
+
engine.inform_entity(
|
|
289
|
+
step=86,
|
|
290
|
+
episode_id="ep_step82_prophecy_dispute",
|
|
291
|
+
entity_id="char_mordred",
|
|
292
|
+
epistemic="deceived",
|
|
293
|
+
believed_summary="Arthur reprimanded Merlin over a missing supply ledger.",
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
# Mordred recalls the cover story — and vector search embeds believed_summary, never the secret!
|
|
297
|
+
mordred_deceived = engine.retrieve_context(
|
|
298
|
+
step=87,
|
|
299
|
+
text="Mordred asked about the dispute.",
|
|
300
|
+
mentions=["Mordred", "Arthur"],
|
|
301
|
+
pov_entity_ids=["char_mordred"],
|
|
302
|
+
)
|
|
303
|
+
print(mordred_deceived.episodes[0].summary)
|
|
304
|
+
# -> "Arthur reprimanded Merlin over a missing supply ledger."
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
### Zero-Copy Branching & Fast Rollback
|
|
308
|
+
|
|
309
|
+
```python
|
|
310
|
+
# Fork an alternate timeline at Step 50 (zero data copying)
|
|
311
|
+
engine.branch(at_step=50, name="reconciliation_route")
|
|
312
|
+
engine.checkout("reconciliation_route")
|
|
313
|
+
|
|
314
|
+
# Inherits state up to Step 50, ignoring Step 82 on 'main'
|
|
315
|
+
branch_ctx = engine.retrieve_context(step=85, mentions=["Arthur", "Merlin"])
|
|
316
|
+
# branch_ctx.active_edges[0].state["register"] == "formal"
|
|
317
|
+
|
|
318
|
+
# Compare divergent timelines at Step 85
|
|
319
|
+
diff = engine.diff_timelines("main", "reconciliation_route", at_step=85)
|
|
320
|
+
|
|
321
|
+
# Atomically rewind 'main' back to Step 10 (revisions & episodes > 10 deleted)
|
|
322
|
+
engine.rollback_to(step=10, timeline_id="main")
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
### CLI Timeline Inspector
|
|
326
|
+
|
|
327
|
+
Inspect branching timelines, POV world state, diffs, and entity trajectories directly from `.sqlite` saves (pass `--json` to any subcommand for machine-readable output):
|
|
328
|
+
|
|
329
|
+
```bash
|
|
330
|
+
$ canonarc tree story_save.sqlite
|
|
331
|
+
main [head=86]
|
|
332
|
+
└─ reconciliation_route (fork@50) [head=50]
|
|
333
|
+
|
|
334
|
+
$ canonarc diff story_save.sqlite main reconciliation_route --step 85
|
|
335
|
+
Diff main vs reconciliation_route @ step 85:
|
|
336
|
+
Changed (2):
|
|
337
|
+
- char_arthur: {... 'mood': 'furious', 'reason': 'Discovered Merlin concealed the prophecy'} vs {... 'state': {}}
|
|
338
|
+
- char_arthur:stance->char_merlin: {'register': 'informal', 'tone': 'furious', ...} vs {'register': 'formal', 'tone': 'respectful'}
|
|
339
|
+
Identical keys: 3
|
|
340
|
+
|
|
341
|
+
# Additional commands:
|
|
342
|
+
canonarc inspect story_save.sqlite --timeline main --step 85 --pov char_arthur
|
|
343
|
+
canonarc history story_save.sqlite char_arthur --timeline main
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
---
|
|
347
|
+
|
|
348
|
+
## Performance & Benchmarks at a Glance
|
|
349
|
+
|
|
350
|
+
Engine algorithmic scaling micro-benchmarks from [`scripts/benchmark_engine_performance.py`](scripts/benchmark_engine_performance.py) (see [Benchmarks](docs/benchmarks.md) for full LLM extraction & long-horizon marathon tables):
|
|
351
|
+
|
|
352
|
+
| Metric (1,500 Steps, 120 Characters) | Result | Notes |
|
|
353
|
+
| :--- | :---: | :--- |
|
|
354
|
+
| **Zero-Copy `branch()`** | **`0.087 ms`** | Constant-time lineage fork |
|
|
355
|
+
| **1-Step Undo `rollback_to()`** | **`0.067 ms`** | `4.48 ms` for 50% deep rollback (-750 steps) |
|
|
356
|
+
| **`retrieve_context()` P50** | **`26.9 ms`** | **`21.3 ms`** after `consolidate_episodes()` |
|
|
357
|
+
| **SQLite Save File Size** | **`2.03 MB`** | **`436 KB`** (-78.5%) post-consolidation |
|
|
358
|
+
| **Deceived-POV Vector Isolation** | **`0%` leakage** | `100%` Recall@1 on `believed_summary`, adversarial secret queries blocked |
|
|
359
|
+
|
|
360
|
+
---
|
|
361
|
+
|
|
362
|
+
## Interactive Example Notebooks
|
|
363
|
+
|
|
364
|
+
Self-contained Jupyter notebooks in [`examples/`](examples/README.md) walk through each primary domain:
|
|
365
|
+
|
|
366
|
+
| Notebook | Domain | Preset | Key Capabilities Demonstrated |
|
|
367
|
+
| :--- | :--- | :--- | :--- |
|
|
368
|
+
| [`01_interactive_fiction_and_rpg.ipynb`](examples/01_interactive_fiction_and_rpg.ipynb) | Interactive Fiction, Visual Novels & RPGs | `InteractiveFictionPreset` | Tiers 1–6, 1-hop alias coreference, 2-stage anti-drift `IngestionGate`, `prior_state` trajectory, dramatic irony (`\| ignorant:`), `branch()`, `diff_timelines()`, `rollback_to()`, `export_snapshot()` |
|
|
369
|
+
| [`02_literary_translation.ipynb`](examples/02_literary_translation.ipynb) | Long-Form Literary Translation | `TranslationPreset` | Pure-English A/B comparison, transactional `step_transaction()` pipeline, verified `Vi`→`ti` register propagation, automated Tier 5 Voice Bank harvesting & anti-drift gating, flashback safety, linguistic glosses & QA audit |
|
|
370
|
+
| [`03_multi_agent_simulation.ipynb`](examples/03_multi_agent_simulation.ipynb) | Multi-Agent Autonomous Simulations | `SimulationPreset` | Custom `SchemaPolicy` & `EpisodicScoringPolicy`, per-tick directed affinity edges, partial observability (`pov_entity_ids`), secondhand gossip (`InformDelta`), `consolidate_episodes()` |
|
|
371
|
+
| [`04_mystery_and_social_deduction.ipynb`](examples/04_mystery_and_social_deduction.ipynb) | Mystery, Espionage & Social Deduction | `InteractiveFictionPreset` | Disguise & persona masking (`AliasRecord.known_to` → `masked:<id>`), `facade` vs. hidden `stance` edges, `private_state` redaction, `deceived` beliefs (`believed_summary` vector isolation), disguise piercing |
|
|
372
|
+
|
|
373
|
+
```bash
|
|
374
|
+
pip install -e ".[notebooks]"
|
|
375
|
+
jupyter lab examples/
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
---
|
|
379
|
+
|
|
380
|
+
## Built-In Adapters, Sessions & Lifecycle Hooks
|
|
381
|
+
|
|
382
|
+
- **Embedders (no extra SDKs required)** (`canonarc.embedders`): `OfflineNgramEmbedder` (with CJK tokenization & signed feature hashing), `CallableEmbedder`, `OpenAICompatibleEmbedder`, and `OllamaEmbedder` with `embed_batch()` and automatic embedder-mismatch detection (`on_embedder_mismatch="warn" | "raise" | "reindex" | "ignore"`).
|
|
383
|
+
- **Extractors (no extra SDKs required)** (`canonarc.extractors`): `CallableExtractor`, `OpenAICompatibleExtractor` (with `.from_lmstudio()`, `.from_gemini()`, `.from_deepseek()`), and content-addressed `CachedDeltaExtractor` with `TokenUsage` cost estimation.
|
|
384
|
+
- **Tier 6 Episodic Policy & Consolidation** (`canonarc.episodic`): Tunable `EpisodicScoringPolicy`, `DefaultEpisodeRanker`, flashback-safe `StepDelta(is_flashback=True)`, `"forgotten"` / `"suppressed"` epistemic updates, and `engine.consolidate_episodes(...)`.
|
|
385
|
+
- **Concurrency-Safe Sessions & Hooks** (`canonarc.hooks`): Use `with CanonArcEngine("save.sqlite") as engine:`, `engine.session("branch_a")`, `with engine.use_timeline("branch_a"):`, and `BaseEngineHooks` (`on_before_commit`, `on_after_commit`, `on_rollback`, `on_branch`, `on_gate_rejected`).
|
|
386
|
+
|
|
387
|
+
---
|
|
388
|
+
|
|
389
|
+
## Documentation
|
|
390
|
+
|
|
391
|
+
- [**The `canonarc` Handbook**](docs/handbook.md): End-to-end tutorial & architectural book covering ontology, recursive CTE lineage, anti-drift gates, epistemic POV projection, live LLM extraction, and worked examples.
|
|
392
|
+
- [**Architecture Guide**](docs/architecture.md): Deep dive into the 6-tier state superset, SQLite schema, and windowed recursive CTE.
|
|
393
|
+
- [**Epistemic State, Disguises & POV Projection**](docs/epistemics-and-pov.md): Guide to anti-metagaming, `"direct"` / `"told"` / `"deceived"` / `"forgotten"` modes, scoped disguises (`known_to`), and `facade` vs. `stance` edges.
|
|
394
|
+
- [**Causal Time Travel**](docs/time-travel.md): Lineage trees, copy-on-write branching, atomic rollback, non-linear flashbacks, and save-slot exports.
|
|
395
|
+
- [**Voice Bank & Anti-Drift**](docs/voice-bank.md): The 2-stage ingestion gate, multi-party dyadic register resolution, and embedder migration.
|
|
396
|
+
- [**Domain Presets**](docs/presets.md): Pre-built prompt formatters and `SchemaPolicy` configuration for Interactive Fiction, Localization, and Multi-Agent Simulations.
|
|
397
|
+
- [**Domains of Application**](docs/domains-of-application.md): Primary and emerging use cases, domain-to-capability matrix, and when to choose another tool.
|
|
398
|
+
- [**Synthetic Story & Engine Benchmarks**](docs/benchmarks.md): Multi-model extraction accuracy, epistemic leak metrics, engine scaling micro-benchmarks, and reproduction guide.
|
|
399
|
+
- [**API Reference**](docs/api-reference.md): Detailed reference for classes, methods, extractors, embedders, CLI commands, and Pydantic schemas.
|
|
400
|
+
|
|
401
|
+
---
|
|
402
|
+
|
|
403
|
+
## Development & Contributing
|
|
404
|
+
|
|
405
|
+
Contributions, bug reports, and new domain presets or adapters are welcome:
|
|
406
|
+
|
|
407
|
+
```bash
|
|
408
|
+
git clone https://github.com/jovistos/canonarc.git
|
|
409
|
+
cd canonarc
|
|
410
|
+
pip install -e ".[dev]"
|
|
411
|
+
|
|
412
|
+
# Run linter, strict type checker, and test suite
|
|
413
|
+
ruff check src tests
|
|
414
|
+
mypy src
|
|
415
|
+
pytest
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
---
|
|
419
|
+
|
|
420
|
+
## License
|
|
421
|
+
|
|
422
|
+
[MIT License](LICENSE). Free and open source.
|