canonarc 0.1.0__py3-none-any.whl

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/__init__.py ADDED
@@ -0,0 +1,119 @@
1
+ from __future__ import annotations
2
+
3
+ from .embedders import (
4
+ CallableEmbedder,
5
+ Embedder,
6
+ EmbedderMismatchError,
7
+ OfflineNgramEmbedder,
8
+ OllamaEmbedder,
9
+ OpenAICompatibleEmbedder,
10
+ embed_texts_batch,
11
+ get_embedder_info,
12
+ )
13
+ from .engine import (
14
+ DefaultLexicalResolver,
15
+ DeltaExtractor,
16
+ MentionResolver,
17
+ CanonArcEngine,
18
+ StepTransaction,
19
+ TimelineSession,
20
+ )
21
+ from .episodic import (
22
+ DEFAULT_EPISODIC_POLICY,
23
+ DefaultEpisodeRanker,
24
+ EpisodeRanker,
25
+ EpisodicScoringPolicy,
26
+ )
27
+ from .extractors import (
28
+ CachedDeltaExtractor,
29
+ CallableExtractor,
30
+ MODEL_PRICING_PER_1M_USD,
31
+ OpenAICompatibleExtractor,
32
+ TokenUsage,
33
+ get_model_pricing_per_1m_usd,
34
+ load_dotenv,
35
+ resolve_lmstudio_model,
36
+ )
37
+ from .hooks import BaseEngineHooks, EngineHooks
38
+ from .models import (
39
+ AliasRecord,
40
+ DialogueCandidate,
41
+ DirectedEdgeRecord,
42
+ EdgeDelta,
43
+ EntityDelta,
44
+ EntityRecord,
45
+ EpisodeRecord,
46
+ EpistemicMode,
47
+ InformDelta,
48
+ ResolvedMention,
49
+ StepContext,
50
+ StepDelta,
51
+ TimelineInfo,
52
+ VoiceExemplar,
53
+ )
54
+ from .presets import (
55
+ DEFAULT_SCHEMA_POLICY,
56
+ DomainPreset,
57
+ InteractiveFictionPreset,
58
+ SchemaPolicy,
59
+ SimulationPreset,
60
+ TranslationPreset,
61
+ )
62
+ from .store import CausalStore, MemoryStore, TimelineBranchConflictError
63
+ from .voice import IngestionGate, VoiceBank
64
+
65
+ __all__ = [
66
+ "AliasRecord",
67
+ "BaseEngineHooks",
68
+ "CachedDeltaExtractor",
69
+ "CallableEmbedder",
70
+ "CallableExtractor",
71
+ "CausalStore",
72
+ "DEFAULT_EPISODIC_POLICY",
73
+ "DEFAULT_SCHEMA_POLICY",
74
+ "DefaultEpisodeRanker",
75
+ "DefaultLexicalResolver",
76
+ "DeltaExtractor",
77
+ "DialogueCandidate",
78
+ "DirectedEdgeRecord",
79
+ "DomainPreset",
80
+ "EdgeDelta",
81
+ "Embedder",
82
+ "EmbedderMismatchError",
83
+ "EngineHooks",
84
+ "EntityDelta",
85
+ "EntityRecord",
86
+ "EpisodeRanker",
87
+ "EpisodeRecord",
88
+ "EpisodicScoringPolicy",
89
+ "EpistemicMode",
90
+ "InformDelta",
91
+ "IngestionGate",
92
+ "InteractiveFictionPreset",
93
+ "MODEL_PRICING_PER_1M_USD",
94
+ "MemoryStore",
95
+ "MentionResolver",
96
+ "CanonArcEngine",
97
+ "OfflineNgramEmbedder",
98
+ "OllamaEmbedder",
99
+ "OpenAICompatibleEmbedder",
100
+ "OpenAICompatibleExtractor",
101
+ "ResolvedMention",
102
+ "SchemaPolicy",
103
+ "SimulationPreset",
104
+ "StepContext",
105
+ "StepDelta",
106
+ "StepTransaction",
107
+ "TimelineBranchConflictError",
108
+ "TimelineInfo",
109
+ "TimelineSession",
110
+ "TokenUsage",
111
+ "TranslationPreset",
112
+ "VoiceBank",
113
+ "VoiceExemplar",
114
+ "embed_texts_batch",
115
+ "get_embedder_info",
116
+ "get_model_pricing_per_1m_usd",
117
+ "load_dotenv",
118
+ "resolve_lmstudio_model",
119
+ ]
canonarc/cli.py ADDED
@@ -0,0 +1,159 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from typing import Any, Sequence
7
+
8
+ from .engine import CanonArcEngine
9
+ from .models import TimelineInfo
10
+
11
+
12
+ def _render_tree(timelines: Sequence[TimelineInfo]) -> str:
13
+ if not timelines:
14
+ return "(no timelines)"
15
+ children: dict[str | None, list[TimelineInfo]] = {}
16
+ for tl in timelines:
17
+ children.setdefault(tl.parent_id, []).append(tl)
18
+ for group in children.values():
19
+ group.sort(key=lambda t: (t.fork_step or 0, t.timeline_id))
20
+
21
+ lines: list[str] = []
22
+
23
+ def _walk(node: TimelineInfo, prefix: str, is_last: bool, is_root: bool) -> None:
24
+ if is_root:
25
+ connector = ""
26
+ next_prefix = ""
27
+ else:
28
+ connector = "└─ " if is_last else "├─ "
29
+ next_prefix = prefix + (" " if is_last else "│ ")
30
+ fork_info = f" (fork@{node.fork_step})" if node.fork_step is not None else ""
31
+ lines.append(f"{prefix}{connector}{node.timeline_id}{fork_info} [head={node.head_step}]")
32
+ kids = children.get(node.timeline_id, [])
33
+ for idx, child in enumerate(kids):
34
+ _walk(child, next_prefix, idx == len(kids) - 1, False)
35
+
36
+ roots = children.get(None, [])
37
+ for idx, root in enumerate(roots):
38
+ _walk(root, "", idx == len(roots) - 1, True)
39
+ return "\n".join(lines)
40
+
41
+
42
+ def _cmd_tree(args: argparse.Namespace) -> int:
43
+ with CanonArcEngine(args.db_path, on_embedder_mismatch="ignore") as engine:
44
+ timelines = engine.list_timelines()
45
+ if args.json:
46
+ print(json.dumps([t.model_dump() for t in timelines], indent=2))
47
+ else:
48
+ print(_render_tree(timelines))
49
+ return 0
50
+
51
+
52
+ def _cmd_inspect(args: argparse.Namespace) -> int:
53
+ with CanonArcEngine(args.db_path, timeline_id=args.timeline) as engine:
54
+ tl_info = engine.store.get_timeline(args.timeline)
55
+ if tl_info is None:
56
+ print(f"Error: timeline '{args.timeline}' not found.", file=sys.stderr)
57
+ return 1
58
+ target_step = args.step if args.step is not None else tl_info.head_step
59
+ inclusive = args.step is None or bool(args.inclusive)
60
+ ctx = engine.retrieve_context(
61
+ target_step,
62
+ text=args.text or "",
63
+ pov_entity_ids=args.pov or None,
64
+ inclusive=inclusive,
65
+ timeline_id=args.timeline,
66
+ fallback_on_empty_mentions="all" if not args.text else "pov_only",
67
+ )
68
+ if args.json:
69
+ print(json.dumps(ctx.model_dump(), indent=2))
70
+ else:
71
+ print(engine.format_context(ctx))
72
+ return 0
73
+
74
+
75
+ def _cmd_diff(args: argparse.Namespace) -> int:
76
+ with CanonArcEngine(args.db_path, on_embedder_mismatch="ignore") as engine:
77
+ diff = engine.diff_timelines(args.timeline_a, args.timeline_b, at_step=args.step)
78
+ if args.json:
79
+ print(json.dumps(diff, indent=2))
80
+ else:
81
+ print(f"Diff {args.timeline_a} vs {args.timeline_b} @ step {args.step}:")
82
+ print(f" Only in {args.timeline_a}: {diff['only_in_a']}")
83
+ print(f" Only in {args.timeline_b}: {diff['only_in_b']}")
84
+ print(f" Changed ({len(diff['changed'])}):")
85
+ for item in diff["changed"]:
86
+ print(f" - {item['subject_key']}: {item['timeline_a']} vs {item['timeline_b']}")
87
+ print(f" Identical keys: {len(diff['identical'])}")
88
+ return 0
89
+
90
+
91
+ def _cmd_history(args: argparse.Namespace) -> int:
92
+ with CanonArcEngine(args.db_path, timeline_id=args.timeline, on_embedder_mismatch="ignore") as engine:
93
+ hist = engine.get_history(args.subject_key, timeline_id=args.timeline, record_type=args.type)
94
+ if args.json:
95
+ print(json.dumps(hist, indent=2))
96
+ else:
97
+ if not hist:
98
+ print(f"No revisions found for '{args.subject_key}' on '{args.timeline}'.")
99
+ return 0
100
+ for item in hist:
101
+ end_step = item["valid_to_step"] if item["valid_to_step"] is not None else "HEAD"
102
+ tomb = " [TOMBSTONE]" if item["is_tombstone"] else ""
103
+ print(
104
+ f"[{item['valid_from_step']}..{end_step}] ({item['timeline_id']} / {item['record_type']}){tomb}: "
105
+ f"{json.dumps(item['payload'], ensure_ascii=False)}"
106
+ )
107
+ return 0
108
+
109
+
110
+ def build_parser() -> argparse.ArgumentParser:
111
+ parser = argparse.ArgumentParser(
112
+ prog="canonarc",
113
+ description="Inspect and diff canonarc SQLite timeline databases.",
114
+ )
115
+ sub = parser.add_subparsers(dest="command", required=True)
116
+
117
+ p_tree = sub.add_parser("tree", help="Render the branching timeline tree.")
118
+ p_tree.add_argument("db_path", help="Path to SQLite database file.")
119
+ p_tree.add_argument("--json", action="store_true", help="Output JSON.")
120
+ p_tree.set_defaults(func=_cmd_tree)
121
+
122
+ p_inspect = sub.add_parser("inspect", help="Inspect world state at a timeline step.")
123
+ p_inspect.add_argument("db_path", help="Path to SQLite database file.")
124
+ p_inspect.add_argument("--timeline", default="main", help="Timeline ID (default: main).")
125
+ p_inspect.add_argument("--step", type=int, default=None, help="Step to inspect (default: head).")
126
+ p_inspect.add_argument("--inclusive", action="store_true", help="Include changes at --step.")
127
+ p_inspect.add_argument("--pov", action="append", default=[], help="POV entity_id (repeatable).")
128
+ p_inspect.add_argument("--text", default="", help="Optional scene cue text.")
129
+ p_inspect.add_argument("--json", action="store_true", help="Output JSON.")
130
+ p_inspect.set_defaults(func=_cmd_inspect)
131
+
132
+ p_diff = sub.add_parser("diff", help="Diff active world state between two timelines.")
133
+ p_diff.add_argument("db_path", help="Path to SQLite database file.")
134
+ p_diff.add_argument("timeline_a", help="First timeline ID.")
135
+ p_diff.add_argument("timeline_b", help="Second timeline ID.")
136
+ p_diff.add_argument("--step", type=int, required=True, help="Step at which to compare.")
137
+ p_diff.add_argument("--json", action="store_true", help="Output JSON.")
138
+ p_diff.set_defaults(func=_cmd_diff)
139
+
140
+ p_hist = sub.add_parser("history", help="Print revision trajectory for a subject_key.")
141
+ p_hist.add_argument("db_path", help="Path to SQLite database file.")
142
+ p_hist.add_argument("subject_key", help="Subject key (e.g. char_arthur).")
143
+ p_hist.add_argument("--timeline", default="main", help="Timeline ID (default: main).")
144
+ p_hist.add_argument("--type", default=None, help="Record type filter (entity|edge|alias).")
145
+ p_hist.add_argument("--json", action="store_true", help="Output JSON.")
146
+ p_hist.set_defaults(func=_cmd_history)
147
+
148
+ return parser
149
+
150
+
151
+ def main(argv: Sequence[str] | None = None) -> int:
152
+ parser = build_parser()
153
+ args = parser.parse_args(list(argv) if argv is not None else None)
154
+ func: Any = args.func
155
+ return int(func(args))
156
+
157
+
158
+ if __name__ == "__main__":
159
+ raise SystemExit(main())
canonarc/embedders.py ADDED
@@ -0,0 +1,233 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import urllib.request
6
+ import zlib
7
+ from typing import Any, Callable, Protocol, Sequence
8
+
9
+ import numpy as np
10
+
11
+ # CJK Unified Ideographs, Extension A, Hiragana, Katakana, Hangul Syllables
12
+ _CJK_CHAR_RE = re.compile(r"[\u3040-\u309f\u30a0-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af]")
13
+ _TOKEN_UNIT_RE = re.compile(
14
+ r"[\u3040-\u309f\u30a0-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af]"
15
+ r"|[^\W\u3040-\u309f\u30a0-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af]+"
16
+ )
17
+
18
+
19
+ def _tokenize_units(text: str) -> tuple[list[str], bool]:
20
+ """Tokenizes text into linguistic units (CJK characters individually, non-CJK words via \\w+).
21
+
22
+ Returns (lowercased_units, is_cjk_dominant).
23
+ """
24
+ units = [m.lower() for m in _TOKEN_UNIT_RE.findall(text)]
25
+ if not units:
26
+ return [], False
27
+ cjk_count = sum(1 for u in units if len(u) == 1 and _CJK_CHAR_RE.match(u))
28
+ return units, (cjk_count / len(units)) >= 0.5
29
+
30
+
31
+ class EmbedderMismatchError(RuntimeError):
32
+ """Raised when an existing store's recorded embedder or vector dimension conflicts with the active embedder."""
33
+
34
+
35
+ class Embedder(Protocol):
36
+ """Protocol for dense or sparse text embedding."""
37
+
38
+ def embed_text(self, text: str) -> np.ndarray: ...
39
+
40
+
41
+ def get_embedder_info(embedder: Embedder) -> tuple[str, int | None]:
42
+ """Returns (embedder_id, known_dim) for metadata tracking and mismatch detection."""
43
+ explicit_id = getattr(embedder, "embedder_id", None)
44
+ if explicit_id:
45
+ embedder_id = str(explicit_id)
46
+ else:
47
+ cls_name = type(embedder).__qualname__
48
+ model = getattr(embedder, "model", None)
49
+ dim_attr = getattr(embedder, "dim", None)
50
+ if model is not None:
51
+ embedder_id = f"{cls_name}(model={model})"
52
+ elif dim_attr is not None:
53
+ embedder_id = f"{cls_name}(dim={dim_attr})"
54
+ else:
55
+ embedder_id = cls_name
56
+
57
+ raw_dim = getattr(embedder, "dim", None)
58
+ known_dim = int(raw_dim) if isinstance(raw_dim, int) and raw_dim > 0 else None
59
+ return embedder_id, known_dim
60
+
61
+
62
+ def embed_texts_batch(embedder: Embedder, texts: Sequence[str]) -> list[np.ndarray]:
63
+ """Embeds a sequence of texts using embed_batch() when supported, falling back to embed_text()."""
64
+ if not texts:
65
+ return []
66
+ batch_fn = getattr(embedder, "embed_batch", None)
67
+ if callable(batch_fn):
68
+ return [np.asarray(v, dtype=np.float32) for v in batch_fn(texts)]
69
+ return [np.asarray(embedder.embed_text(t), dtype=np.float32) for t in texts]
70
+
71
+
72
+ class OfflineNgramEmbedder:
73
+ """Zero-dependency offline character + word n-gram signed feature hashing embedder.
74
+
75
+ Uses Weinberger signed feature hashing with deterministic CRC32 across words,
76
+ individual CJK units, adjacent CJK character bigrams, and character 3-grams
77
+ so unrelated tokens have zero expected collision bias.
78
+ """
79
+
80
+ def __init__(self, dim: int = 128) -> None:
81
+ self.dim = dim
82
+
83
+ def embed_text(self, text: str) -> np.ndarray:
84
+ clean = " ".join(text.lower().split())
85
+ if not clean:
86
+ return np.zeros(self.dim, dtype=np.float32)
87
+
88
+ vec = np.zeros(self.dim, dtype=np.float32)
89
+ units, _ = _tokenize_units(clean)
90
+ for token in units:
91
+ h = zlib.crc32(token.encode("utf-8"))
92
+ sign = 1.0 if (h & 1) else -1.0
93
+ idx = (h >> 1) % self.dim
94
+ vec[idx] += sign * 1.0
95
+
96
+ # Adjacent CJK character bigrams (captures 2-character CJK compounds)
97
+ for i in range(len(clean) - 1):
98
+ c1, c2 = clean[i], clean[i + 1]
99
+ if _CJK_CHAR_RE.match(c1) and _CJK_CHAR_RE.match(c2):
100
+ h = zlib.crc32((c1 + c2).encode("utf-8"))
101
+ sign = 1.0 if (h & 1) else -1.0
102
+ idx = (h >> 1) % self.dim
103
+ vec[idx] += sign * 1.0
104
+
105
+ # Character 3-grams
106
+ for i in range(len(clean) - 2):
107
+ tri = clean[i : i + 3]
108
+ h = zlib.crc32(tri.encode("utf-8"))
109
+ sign = 1.0 if (h & 1) else -1.0
110
+ idx = (h >> 1) % self.dim
111
+ vec[idx] += sign * 0.5
112
+
113
+ norm = float(np.linalg.norm(vec))
114
+ if norm > 1e-6:
115
+ vec /= norm
116
+ return vec.astype(np.float32)
117
+
118
+ def embed_batch(self, texts: Sequence[str]) -> list[np.ndarray]:
119
+ return [self.embed_text(t) for t in texts]
120
+
121
+
122
+ class CallableEmbedder:
123
+ """Adapter wrapping a user-supplied embedding function (and optional batch function)."""
124
+
125
+ def __init__(
126
+ self,
127
+ fn: Callable[[str], Sequence[float] | np.ndarray],
128
+ *,
129
+ batch_fn: Callable[[Sequence[str]], Sequence[Sequence[float] | np.ndarray]] | None = None,
130
+ embedder_id: str | None = None,
131
+ dim: int | None = None,
132
+ ) -> None:
133
+ self._fn = fn
134
+ self._batch_fn = batch_fn
135
+ self.embedder_id = embedder_id
136
+ self.dim = dim
137
+
138
+ def embed_text(self, text: str) -> np.ndarray:
139
+ return np.asarray(self._fn(text), dtype=np.float32)
140
+
141
+ def embed_batch(self, texts: Sequence[str]) -> list[np.ndarray]:
142
+ if not texts:
143
+ return []
144
+ if self._batch_fn is not None:
145
+ return [np.asarray(v, dtype=np.float32) for v in self._batch_fn(texts)]
146
+ return [self.embed_text(t) for t in texts]
147
+
148
+
149
+ class OpenAICompatibleEmbedder:
150
+ """Zero-dependency HTTP embedder for OpenAI, LiteLLM, vLLM, or compatible /v1/embeddings endpoints."""
151
+
152
+ def __init__(
153
+ self,
154
+ *,
155
+ model: str = "text-embedding-3-small",
156
+ api_key: str | None = None,
157
+ base_url: str = "https://api.openai.com/v1",
158
+ timeout: float = 30.0,
159
+ headers: dict[str, str] | None = None,
160
+ dim: int | None = None,
161
+ ) -> None:
162
+ self.model = model
163
+ self.api_key = api_key
164
+ self.base_url = base_url.rstrip("/")
165
+ self.timeout = timeout
166
+ self.headers = dict(headers) if headers else {}
167
+ self.dim = dim
168
+
169
+ def _request(self, inputs: list[str]) -> list[np.ndarray]:
170
+ payload = json.dumps({"model": self.model, "input": inputs}).encode("utf-8")
171
+ req_headers = {"Content-Type": "application/json", **self.headers}
172
+ if self.api_key:
173
+ req_headers.setdefault("Authorization", f"Bearer {self.api_key}")
174
+ req = urllib.request.Request(
175
+ f"{self.base_url}/embeddings",
176
+ data=payload,
177
+ headers=req_headers,
178
+ method="POST",
179
+ )
180
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
181
+ body: dict[str, Any] = json.loads(resp.read().decode("utf-8"))
182
+ data = sorted(body.get("data", []), key=lambda item: int(item.get("index", 0)))
183
+ return [np.asarray(item["embedding"], dtype=np.float32) for item in data]
184
+
185
+ def embed_text(self, text: str) -> np.ndarray:
186
+ vectors = self._request([text])
187
+ return vectors[0] if vectors else np.zeros(0, dtype=np.float32)
188
+
189
+ def embed_batch(self, texts: Sequence[str]) -> list[np.ndarray]:
190
+ if not texts:
191
+ return []
192
+ return self._request(list(texts))
193
+
194
+
195
+ class OllamaEmbedder:
196
+ """Zero-dependency HTTP embedder for local Ollama /api/embed endpoints."""
197
+
198
+ def __init__(
199
+ self,
200
+ *,
201
+ model: str = "nomic-embed-text",
202
+ base_url: str = "http://localhost:11434",
203
+ timeout: float = 30.0,
204
+ dim: int | None = None,
205
+ ) -> None:
206
+ self.model = model
207
+ self.base_url = base_url.rstrip("/")
208
+ self.timeout = timeout
209
+ self.dim = dim
210
+
211
+ def _request(self, inputs: list[str]) -> list[np.ndarray]:
212
+ payload = json.dumps({"model": self.model, "input": inputs}).encode("utf-8")
213
+ req = urllib.request.Request(
214
+ f"{self.base_url}/api/embed",
215
+ data=payload,
216
+ headers={"Content-Type": "application/json"},
217
+ method="POST",
218
+ )
219
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
220
+ body: dict[str, Any] = json.loads(resp.read().decode("utf-8"))
221
+ embeddings = body.get("embeddings")
222
+ if embeddings is None and "embedding" in body:
223
+ embeddings = [body["embedding"]]
224
+ return [np.asarray(vec, dtype=np.float32) for vec in (embeddings or ())]
225
+
226
+ def embed_text(self, text: str) -> np.ndarray:
227
+ vectors = self._request([text])
228
+ return vectors[0] if vectors else np.zeros(0, dtype=np.float32)
229
+
230
+ def embed_batch(self, texts: Sequence[str]) -> list[np.ndarray]:
231
+ if not texts:
232
+ return []
233
+ return self._request(list(texts))