agentdream 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.
- agentdream/__init__.py +60 -0
- agentdream/__main__.py +5 -0
- agentdream/_toml.py +286 -0
- agentdream/adapters/__init__.py +122 -0
- agentdream/adapters/base.py +63 -0
- agentdream/adapters/jsonstore.py +219 -0
- agentdream/adapters/markdown.py +476 -0
- agentdream/adapters/sqlite.py +146 -0
- agentdream/adapters/stancelog.py +191 -0
- agentdream/api.py +73 -0
- agentdream/backends/__init__.py +77 -0
- agentdream/backends/base.py +97 -0
- agentdream/backends/builtin.py +124 -0
- agentdream/blocking.py +128 -0
- agentdream/chunking.py +231 -0
- agentdream/claude_hook.py +594 -0
- agentdream/cli.py +444 -0
- agentdream/config.py +361 -0
- agentdream/context.py +212 -0
- agentdream/engine/__init__.py +47 -0
- agentdream/engine/deterministic.py +1012 -0
- agentdream/engine/llm.py +907 -0
- agentdream/jobs.py +386 -0
- agentdream/loaders.py +420 -0
- agentdream/mcp_server.py +194 -0
- agentdream/models.py +219 -0
- agentdream/pipeline.py +380 -0
- agentdream/redact.py +372 -0
- agentdream/report.py +194 -0
- agentdream/review.py +319 -0
- agentdream/scheduler.py +164 -0
- agentdream/text.py +486 -0
- agentdream/util.py +167 -0
- agentdream-0.1.0.dist-info/METADATA +494 -0
- agentdream-0.1.0.dist-info/RECORD +38 -0
- agentdream-0.1.0.dist-info/WHEEL +4 -0
- agentdream-0.1.0.dist-info/entry_points.txt +2 -0
- agentdream-0.1.0.dist-info/licenses/LICENSE +21 -0
agentdream/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""agentdream — local-first sleep-time memory consolidation ("dreaming") for any agent and any model.
|
|
2
|
+
|
|
3
|
+
from agentdream import dream
|
|
4
|
+
job = dream(memory="./mem", sessions=["./logs"], backend="deterministic")
|
|
5
|
+
print(job.report["counts"])
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
|
|
10
|
+
from .adapters import MemoryAdapter, available_adapters, get_adapter, register_adapter
|
|
11
|
+
from .api import dream, dream_async, make_config
|
|
12
|
+
from .backends import LLMBackend, available_backends, get_backend, register_backend
|
|
13
|
+
from .context import DreamCanceled, DreamConfig, DreamContext
|
|
14
|
+
from .jobs import DreamJob, JobNotFound
|
|
15
|
+
from .loaders import load_transcript, load_transcripts, register_loader
|
|
16
|
+
from .models import Evidence, MemoryEntry, Message, Operation, Transcript, apply_operations
|
|
17
|
+
from .pipeline import DreamLimitError, Pipeline, run_dream
|
|
18
|
+
from .redact import Redactor, redact
|
|
19
|
+
from .review import AcceptResult, ReviewError, accept, discard, restore
|
|
20
|
+
from .scheduler import Scheduler
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"AcceptResult",
|
|
24
|
+
"DreamCanceled",
|
|
25
|
+
"DreamConfig",
|
|
26
|
+
"DreamContext",
|
|
27
|
+
"DreamJob",
|
|
28
|
+
"DreamLimitError",
|
|
29
|
+
"Evidence",
|
|
30
|
+
"JobNotFound",
|
|
31
|
+
"LLMBackend",
|
|
32
|
+
"MemoryAdapter",
|
|
33
|
+
"MemoryEntry",
|
|
34
|
+
"Message",
|
|
35
|
+
"Operation",
|
|
36
|
+
"Pipeline",
|
|
37
|
+
"Redactor",
|
|
38
|
+
"ReviewError",
|
|
39
|
+
"Scheduler",
|
|
40
|
+
"Transcript",
|
|
41
|
+
"__version__",
|
|
42
|
+
"accept",
|
|
43
|
+
"apply_operations",
|
|
44
|
+
"available_adapters",
|
|
45
|
+
"available_backends",
|
|
46
|
+
"discard",
|
|
47
|
+
"dream",
|
|
48
|
+
"dream_async",
|
|
49
|
+
"get_adapter",
|
|
50
|
+
"get_backend",
|
|
51
|
+
"load_transcript",
|
|
52
|
+
"load_transcripts",
|
|
53
|
+
"make_config",
|
|
54
|
+
"redact",
|
|
55
|
+
"register_adapter",
|
|
56
|
+
"register_backend",
|
|
57
|
+
"register_loader",
|
|
58
|
+
"restore",
|
|
59
|
+
"run_dream",
|
|
60
|
+
]
|
agentdream/__main__.py
ADDED
agentdream/_toml.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""TOML loading without a hard dependency.
|
|
2
|
+
|
|
3
|
+
Python 3.11+ ships :mod:`tomllib`. On 3.10 we use ``tomli`` when it is installed and
|
|
4
|
+
otherwise fall back to :func:`mini_loads`, a small parser for the subset of TOML that
|
|
5
|
+
agentdream config files need: ``[table]`` / ``[a.b]`` headers, ``key = value`` with
|
|
6
|
+
bare/quoted (dotted) keys, basic and literal strings (single-line, plus basic ``\"\"\"``
|
|
7
|
+
multi-line), integers, floats, booleans, arrays (possibly multi-line, nested) and inline
|
|
8
|
+
tables, and ``#`` comments. Anything else raises :class:`TOMLError` with a line number.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TOMLError(ValueError):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def loads(text: str) -> dict[str, Any]:
|
|
22
|
+
try:
|
|
23
|
+
import tomllib # type: ignore[import-not-found,unused-ignore]
|
|
24
|
+
except ModuleNotFoundError: # Python 3.10
|
|
25
|
+
try:
|
|
26
|
+
import tomli as tomllib # type: ignore[import-not-found,no-redef,unused-ignore]
|
|
27
|
+
except ModuleNotFoundError:
|
|
28
|
+
return mini_loads(text)
|
|
29
|
+
try:
|
|
30
|
+
return tomllib.loads(text)
|
|
31
|
+
except tomllib.TOMLDecodeError as exc:
|
|
32
|
+
raise TOMLError(str(exc)) from exc
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ------------------------------------------------------------------ fallback parser
|
|
36
|
+
|
|
37
|
+
_BARE = re.compile(r"[A-Za-z0-9_\-]+")
|
|
38
|
+
_ESC = {"b": "\b", "t": "\t", "n": "\n", "f": "\f", "r": "\r", '"': '"', "\\": "\\"}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _Parser:
|
|
42
|
+
def __init__(self, text: str):
|
|
43
|
+
self.s = text.replace("\r\n", "\n")
|
|
44
|
+
self.i = 0
|
|
45
|
+
self.line = 1
|
|
46
|
+
|
|
47
|
+
# -- low level
|
|
48
|
+
def err(self, msg: str) -> TOMLError:
|
|
49
|
+
return TOMLError(f"line {self.line}: {msg}")
|
|
50
|
+
|
|
51
|
+
def peek(self) -> str:
|
|
52
|
+
return self.s[self.i] if self.i < len(self.s) else ""
|
|
53
|
+
|
|
54
|
+
def advance(self, n: int = 1) -> None:
|
|
55
|
+
for _ in range(n):
|
|
56
|
+
if self.i < len(self.s) and self.s[self.i] == "\n":
|
|
57
|
+
self.line += 1
|
|
58
|
+
self.i += 1
|
|
59
|
+
|
|
60
|
+
def skip_ws(self, newlines: bool = False) -> None:
|
|
61
|
+
while self.i < len(self.s):
|
|
62
|
+
ch = self.s[self.i]
|
|
63
|
+
if ch in " \t" or (newlines and ch == "\n"):
|
|
64
|
+
self.advance()
|
|
65
|
+
elif ch == "#":
|
|
66
|
+
while self.i < len(self.s) and self.s[self.i] != "\n":
|
|
67
|
+
self.advance()
|
|
68
|
+
else:
|
|
69
|
+
break
|
|
70
|
+
|
|
71
|
+
def expect_eol(self) -> None:
|
|
72
|
+
self.skip_ws()
|
|
73
|
+
if self.peek() not in ("", "\n"):
|
|
74
|
+
raise self.err(f"unexpected {self.peek()!r}")
|
|
75
|
+
|
|
76
|
+
# -- grammar
|
|
77
|
+
def parse(self) -> dict[str, Any]:
|
|
78
|
+
root: dict[str, Any] = {}
|
|
79
|
+
cur = root
|
|
80
|
+
while True:
|
|
81
|
+
self.skip_ws(newlines=True)
|
|
82
|
+
if self.i >= len(self.s):
|
|
83
|
+
return root
|
|
84
|
+
if self.peek() == "[":
|
|
85
|
+
if self.s.startswith("[[", self.i):
|
|
86
|
+
raise self.err("arrays of tables are not supported by the fallback parser (pip install tomli)")
|
|
87
|
+
self.advance()
|
|
88
|
+
self.skip_ws()
|
|
89
|
+
keys = self.key()
|
|
90
|
+
self.skip_ws()
|
|
91
|
+
if self.peek() != "]":
|
|
92
|
+
raise self.err("expected ']'")
|
|
93
|
+
self.advance()
|
|
94
|
+
self.expect_eol()
|
|
95
|
+
cur = root
|
|
96
|
+
for k in keys:
|
|
97
|
+
nxt = cur.setdefault(k, {})
|
|
98
|
+
if not isinstance(nxt, dict):
|
|
99
|
+
raise self.err(f"{k!r} is not a table")
|
|
100
|
+
cur = nxt
|
|
101
|
+
continue
|
|
102
|
+
keys = self.key()
|
|
103
|
+
self.skip_ws()
|
|
104
|
+
if self.peek() != "=":
|
|
105
|
+
raise self.err("expected '='")
|
|
106
|
+
self.advance()
|
|
107
|
+
self.skip_ws()
|
|
108
|
+
val = self.value()
|
|
109
|
+
tgt = cur
|
|
110
|
+
for k in keys[:-1]:
|
|
111
|
+
tgt = tgt.setdefault(k, {})
|
|
112
|
+
if not isinstance(tgt, dict):
|
|
113
|
+
raise self.err(f"{k!r} is not a table")
|
|
114
|
+
if keys[-1] in tgt:
|
|
115
|
+
raise self.err(f"duplicate key {keys[-1]!r}")
|
|
116
|
+
tgt[keys[-1]] = val
|
|
117
|
+
self.expect_eol()
|
|
118
|
+
|
|
119
|
+
def key(self) -> list[str]:
|
|
120
|
+
parts = []
|
|
121
|
+
while True:
|
|
122
|
+
self.skip_ws()
|
|
123
|
+
ch = self.peek()
|
|
124
|
+
if ch == '"':
|
|
125
|
+
parts.append(self.basic_string())
|
|
126
|
+
elif ch == "'":
|
|
127
|
+
parts.append(self.literal_string())
|
|
128
|
+
else:
|
|
129
|
+
m = _BARE.match(self.s, self.i)
|
|
130
|
+
if not m:
|
|
131
|
+
raise self.err("expected a key")
|
|
132
|
+
parts.append(m.group(0))
|
|
133
|
+
self.advance(len(m.group(0)))
|
|
134
|
+
self.skip_ws()
|
|
135
|
+
if self.peek() == ".":
|
|
136
|
+
self.advance()
|
|
137
|
+
continue
|
|
138
|
+
return parts
|
|
139
|
+
|
|
140
|
+
def value(self) -> Any:
|
|
141
|
+
ch = self.peek()
|
|
142
|
+
if self.s.startswith('"""', self.i):
|
|
143
|
+
return self.multiline_basic()
|
|
144
|
+
if ch == '"':
|
|
145
|
+
return self.basic_string()
|
|
146
|
+
if ch == "'":
|
|
147
|
+
return self.literal_string()
|
|
148
|
+
if ch == "[":
|
|
149
|
+
return self.array()
|
|
150
|
+
if ch == "{":
|
|
151
|
+
return self.inline_table()
|
|
152
|
+
m = re.compile(r"true|false|[+\-]?(?:inf|nan)|[0-9A-Za-z_+\-.:]+").match(self.s, self.i)
|
|
153
|
+
if not m:
|
|
154
|
+
raise self.err("expected a value")
|
|
155
|
+
tok = m.group(0)
|
|
156
|
+
self.advance(len(tok))
|
|
157
|
+
if tok == "true":
|
|
158
|
+
return True
|
|
159
|
+
if tok == "false":
|
|
160
|
+
return False
|
|
161
|
+
t = tok.replace("_", "")
|
|
162
|
+
try:
|
|
163
|
+
if re.fullmatch(r"[+\-]?\d+", t):
|
|
164
|
+
return int(t)
|
|
165
|
+
if re.fullmatch(r"0x[0-9a-fA-F]+", t):
|
|
166
|
+
return int(t, 16)
|
|
167
|
+
return float(t)
|
|
168
|
+
except ValueError:
|
|
169
|
+
raise self.err(f"unsupported value {tok!r} (dates are not supported by the fallback parser)") from None
|
|
170
|
+
|
|
171
|
+
def basic_string(self) -> str:
|
|
172
|
+
self.advance() # opening quote
|
|
173
|
+
out: list[str] = []
|
|
174
|
+
while True:
|
|
175
|
+
ch = self.peek()
|
|
176
|
+
if ch in ("", "\n"):
|
|
177
|
+
raise self.err("unterminated string")
|
|
178
|
+
self.advance()
|
|
179
|
+
if ch == '"':
|
|
180
|
+
return "".join(out)
|
|
181
|
+
if ch == "\\":
|
|
182
|
+
out.append(self.escape())
|
|
183
|
+
else:
|
|
184
|
+
out.append(ch)
|
|
185
|
+
|
|
186
|
+
def escape(self) -> str:
|
|
187
|
+
e = self.peek()
|
|
188
|
+
self.advance()
|
|
189
|
+
if e in _ESC:
|
|
190
|
+
return _ESC[e]
|
|
191
|
+
if e in ("u", "U"):
|
|
192
|
+
n = 4 if e == "u" else 8
|
|
193
|
+
code = self.s[self.i:self.i + n]
|
|
194
|
+
self.advance(n)
|
|
195
|
+
try:
|
|
196
|
+
return chr(int(code, 16))
|
|
197
|
+
except ValueError:
|
|
198
|
+
raise self.err("bad unicode escape") from None
|
|
199
|
+
raise self.err(f"bad escape \\{e}")
|
|
200
|
+
|
|
201
|
+
def multiline_basic(self) -> str:
|
|
202
|
+
self.advance(3)
|
|
203
|
+
if self.peek() == "\n":
|
|
204
|
+
self.advance()
|
|
205
|
+
out: list[str] = []
|
|
206
|
+
while True:
|
|
207
|
+
if self.i >= len(self.s):
|
|
208
|
+
raise self.err("unterminated multi-line string")
|
|
209
|
+
if self.s.startswith('"""', self.i):
|
|
210
|
+
self.advance(3)
|
|
211
|
+
return "".join(out)
|
|
212
|
+
ch = self.peek()
|
|
213
|
+
self.advance()
|
|
214
|
+
if ch == "\\":
|
|
215
|
+
if self.peek() == "\n": # line-ending backslash: trim newline + leading whitespace
|
|
216
|
+
self.skip_ws(newlines=True)
|
|
217
|
+
continue
|
|
218
|
+
out.append(self.escape())
|
|
219
|
+
else:
|
|
220
|
+
out.append(ch)
|
|
221
|
+
|
|
222
|
+
def literal_string(self) -> str:
|
|
223
|
+
if self.s.startswith("'''", self.i):
|
|
224
|
+
end = self.s.find("'''", self.i + 3)
|
|
225
|
+
if end < 0:
|
|
226
|
+
raise self.err("unterminated multi-line string")
|
|
227
|
+
body = self.s[self.i + 3:end]
|
|
228
|
+
self.advance(end + 3 - self.i)
|
|
229
|
+
return body[1:] if body.startswith("\n") else body
|
|
230
|
+
end = self.s.find("'", self.i + 1)
|
|
231
|
+
nl = self.s.find("\n", self.i + 1)
|
|
232
|
+
if end < 0 or (0 <= nl < end):
|
|
233
|
+
raise self.err("unterminated string")
|
|
234
|
+
body = self.s[self.i + 1:end]
|
|
235
|
+
self.advance(end + 1 - self.i)
|
|
236
|
+
return body
|
|
237
|
+
|
|
238
|
+
def array(self) -> list[Any]:
|
|
239
|
+
self.advance()
|
|
240
|
+
out: list[Any] = []
|
|
241
|
+
while True:
|
|
242
|
+
self.skip_ws(newlines=True)
|
|
243
|
+
if self.peek() == "]":
|
|
244
|
+
self.advance()
|
|
245
|
+
return out
|
|
246
|
+
out.append(self.value())
|
|
247
|
+
self.skip_ws(newlines=True)
|
|
248
|
+
if self.peek() == ",":
|
|
249
|
+
self.advance()
|
|
250
|
+
elif self.peek() != "]":
|
|
251
|
+
raise self.err("expected ',' or ']' in array")
|
|
252
|
+
|
|
253
|
+
def inline_table(self) -> dict[str, Any]:
|
|
254
|
+
self.advance()
|
|
255
|
+
out: dict[str, Any] = {}
|
|
256
|
+
self.skip_ws()
|
|
257
|
+
if self.peek() == "}":
|
|
258
|
+
self.advance()
|
|
259
|
+
return out
|
|
260
|
+
while True:
|
|
261
|
+
keys = self.key()
|
|
262
|
+
self.skip_ws()
|
|
263
|
+
if self.peek() != "=":
|
|
264
|
+
raise self.err("expected '=' in inline table")
|
|
265
|
+
self.advance()
|
|
266
|
+
self.skip_ws()
|
|
267
|
+
tgt = out
|
|
268
|
+
for k in keys[:-1]:
|
|
269
|
+
tgt = tgt.setdefault(k, {})
|
|
270
|
+
tgt[keys[-1]] = self.value()
|
|
271
|
+
self.skip_ws()
|
|
272
|
+
if self.peek() == ",":
|
|
273
|
+
self.advance()
|
|
274
|
+
continue
|
|
275
|
+
if self.peek() == "}":
|
|
276
|
+
self.advance()
|
|
277
|
+
return out
|
|
278
|
+
raise self.err("expected ',' or '}' in inline table")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def mini_loads(text: str) -> dict[str, Any]:
|
|
282
|
+
"""Parse the TOML subset described in the module docstring."""
|
|
283
|
+
return _Parser(text).parse()
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
__all__ = ["TOMLError", "loads", "mini_loads"]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Memory store adapters + registry.
|
|
2
|
+
|
|
3
|
+
Third parties can register adapters either at runtime::
|
|
4
|
+
|
|
5
|
+
from agentdream.adapters import register_adapter
|
|
6
|
+
register_adapter("mystore", MyAdapter)
|
|
7
|
+
|
|
8
|
+
or via the ``agentdream.adapters`` entry-point group in their package metadata.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .base import AdapterError, MemoryAdapter
|
|
17
|
+
from .jsonstore import JSONAdapter
|
|
18
|
+
from .markdown import MarkdownAdapter
|
|
19
|
+
from .sqlite import SQLiteAdapter, create_sqlite_store
|
|
20
|
+
|
|
21
|
+
_REGISTRY: dict[str, type[MemoryAdapter]] = {}
|
|
22
|
+
_ENTRY_POINTS_LOADED = False
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def register_adapter(name: str, cls: type[MemoryAdapter]) -> None:
|
|
26
|
+
_REGISTRY[name] = cls
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _load_entry_points() -> None:
|
|
30
|
+
global _ENTRY_POINTS_LOADED
|
|
31
|
+
if _ENTRY_POINTS_LOADED:
|
|
32
|
+
return
|
|
33
|
+
_ENTRY_POINTS_LOADED = True
|
|
34
|
+
try:
|
|
35
|
+
from importlib.metadata import entry_points
|
|
36
|
+
|
|
37
|
+
for ep in entry_points(group="agentdream.adapters"):
|
|
38
|
+
try:
|
|
39
|
+
register_adapter(ep.name, ep.load())
|
|
40
|
+
except Exception: # pragma: no cover - third party failure
|
|
41
|
+
continue
|
|
42
|
+
except Exception: # pragma: no cover
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _register_builtins() -> None:
|
|
47
|
+
register_adapter("stancelog", _LazyStancelog) # detection is prefix-only, so safe without the package
|
|
48
|
+
register_adapter("sqlite", SQLiteAdapter)
|
|
49
|
+
register_adapter("json", JSONAdapter)
|
|
50
|
+
register_adapter("markdown", MarkdownAdapter)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class _LazyStancelog(MemoryAdapter):
|
|
54
|
+
"""Proxy that imports the stancelog adapter only when actually used."""
|
|
55
|
+
|
|
56
|
+
name = "stancelog"
|
|
57
|
+
|
|
58
|
+
def __new__(cls, path, **options):
|
|
59
|
+
from .stancelog import StancelogAdapter, available
|
|
60
|
+
|
|
61
|
+
if not available():
|
|
62
|
+
raise AdapterError("the stancelog adapter needs the 'stancelog' package (pip install stancelog)")
|
|
63
|
+
return StancelogAdapter(path, **options)
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def detect(cls, path: Path) -> bool:
|
|
67
|
+
return str(path).startswith("stancelog:")
|
|
68
|
+
|
|
69
|
+
def load(self): # pragma: no cover - never instantiated
|
|
70
|
+
raise NotImplementedError
|
|
71
|
+
|
|
72
|
+
def write(self, entries, dest): # pragma: no cover
|
|
73
|
+
raise NotImplementedError
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
_register_builtins()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def available_adapters() -> list[str]:
|
|
80
|
+
_load_entry_points()
|
|
81
|
+
return list(_REGISTRY)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def get_adapter(path: str | Path, format: str | None = None, **options: Any) -> MemoryAdapter:
|
|
85
|
+
"""Return an adapter instance for ``path``, auto-detecting the format when not given."""
|
|
86
|
+
_load_entry_points()
|
|
87
|
+
if format:
|
|
88
|
+
if format in ("md", "text", "txt"):
|
|
89
|
+
format = "markdown"
|
|
90
|
+
if format in ("jsonl",):
|
|
91
|
+
format = "json"
|
|
92
|
+
cls = _REGISTRY.get(format)
|
|
93
|
+
if cls is None:
|
|
94
|
+
raise AdapterError(f"unknown memory format {format!r}; available: {', '.join(_REGISTRY)}")
|
|
95
|
+
return cls(path, **options)
|
|
96
|
+
p = Path(str(path))
|
|
97
|
+
if str(path).startswith("stancelog:"):
|
|
98
|
+
return _REGISTRY["stancelog"](path, **options)
|
|
99
|
+
if not p.exists():
|
|
100
|
+
raise AdapterError(f"memory store not found: {path}")
|
|
101
|
+
for _name, cls in _REGISTRY.items():
|
|
102
|
+
try:
|
|
103
|
+
if cls.detect(p):
|
|
104
|
+
return cls(p, **options)
|
|
105
|
+
except Exception:
|
|
106
|
+
continue
|
|
107
|
+
if p.is_dir():
|
|
108
|
+
return MarkdownAdapter(p, **options) # empty folder -> markdown store
|
|
109
|
+
raise AdapterError(f"could not detect memory store format for {path}")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
__all__ = [
|
|
113
|
+
"AdapterError",
|
|
114
|
+
"JSONAdapter",
|
|
115
|
+
"MarkdownAdapter",
|
|
116
|
+
"MemoryAdapter",
|
|
117
|
+
"SQLiteAdapter",
|
|
118
|
+
"available_adapters",
|
|
119
|
+
"create_sqlite_store",
|
|
120
|
+
"get_adapter",
|
|
121
|
+
"register_adapter",
|
|
122
|
+
]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Memory store adapter interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from ..models import MemoryEntry
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AdapterError(Exception):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class MemoryAdapter(ABC):
|
|
17
|
+
"""A memory store.
|
|
18
|
+
|
|
19
|
+
``load()`` reads entries without modifying the store. ``write(entries, dest)``
|
|
20
|
+
creates a NEW store at ``dest`` (which must not be the input location) using
|
|
21
|
+
the input store as a layout template where that makes sense.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
name: str = "base"
|
|
25
|
+
#: True when the store is a single file (json/sqlite) rather than a folder.
|
|
26
|
+
single_file: bool = False
|
|
27
|
+
|
|
28
|
+
def __init__(self, path: str | Path, **options: Any):
|
|
29
|
+
self.path = Path(path) if not isinstance(path, Path) else path
|
|
30
|
+
self.options = options
|
|
31
|
+
#: human-readable notes from loading (invalid encodings, skipped symlinks...); shown in the report
|
|
32
|
+
self.notices: list[str] = []
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def detect(cls, path: Path) -> bool: # pragma: no cover - overridden
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
@abstractmethod
|
|
39
|
+
def load(self) -> list[MemoryEntry]: ...
|
|
40
|
+
|
|
41
|
+
@abstractmethod
|
|
42
|
+
def write(self, entries: list[MemoryEntry], dest: str | Path) -> Path: ...
|
|
43
|
+
|
|
44
|
+
def sidecars(self, path: str | Path) -> list[Path]:
|
|
45
|
+
"""Extra files that belong to the store at ``path`` (journals, WAL...).
|
|
46
|
+
|
|
47
|
+
``accept`` backs them up and removes them when it swaps a new store in, so
|
|
48
|
+
stale state from the old store cannot leak into the new one.
|
|
49
|
+
"""
|
|
50
|
+
return []
|
|
51
|
+
|
|
52
|
+
def output_path(self, store_dir: str | Path) -> Path:
|
|
53
|
+
"""Where to put the new store inside a staging ``store_dir``."""
|
|
54
|
+
d = Path(store_dir)
|
|
55
|
+
return d / self.path.name if self.single_file else d
|
|
56
|
+
|
|
57
|
+
def _check_dest(self, dest: Path) -> None:
|
|
58
|
+
try:
|
|
59
|
+
same = dest.resolve() == self.path.resolve()
|
|
60
|
+
except OSError:
|
|
61
|
+
same = False
|
|
62
|
+
if same:
|
|
63
|
+
raise AdapterError(f"refusing to write over the input store {self.path}; write to a new location")
|