episteme-memory 0.40.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.
Files changed (68) hide show
  1. episteme/__init__.py +6 -0
  2. episteme/__main__.py +122 -0
  3. episteme/activity.py +260 -0
  4. episteme/backup.py +163 -0
  5. episteme/docs/__init__.py +21 -0
  6. episteme/docs/hashing.py +55 -0
  7. episteme/docs/inbox.py +73 -0
  8. episteme/docs/removal.py +94 -0
  9. episteme/docs/schema.py +204 -0
  10. episteme/docs/status.py +163 -0
  11. episteme/docs/writing.py +310 -0
  12. episteme/engine.py +692 -0
  13. episteme/errors.py +29 -0
  14. episteme/filters.py +90 -0
  15. episteme/hookmode.py +135 -0
  16. episteme/index/__init__.py +24 -0
  17. episteme/index/ingest.py +200 -0
  18. episteme/index/query.py +120 -0
  19. episteme/index/schema.py +56 -0
  20. episteme/index/store.py +582 -0
  21. episteme/index/text.py +164 -0
  22. episteme/index/values.py +57 -0
  23. episteme/links.py +106 -0
  24. episteme/maintenance.py +293 -0
  25. episteme/markdown.py +595 -0
  26. episteme/memory/__init__.py +62 -0
  27. episteme/memory/files.py +88 -0
  28. episteme/memory/reviewing.py +473 -0
  29. episteme/memory/revising.py +331 -0
  30. episteme/memory/schema.py +431 -0
  31. episteme/memory/scoring.py +55 -0
  32. episteme/memory/secrets.py +249 -0
  33. episteme/memory/surfacing.py +182 -0
  34. episteme/memory/task.py +281 -0
  35. episteme/memory/templates.py +157 -0
  36. episteme/memory/welcoming.py +254 -0
  37. episteme/memory/writing.py +597 -0
  38. episteme/messages/__init__.py +25 -0
  39. episteme/messages/store.py +711 -0
  40. episteme/names.py +28 -0
  41. episteme/perms.py +35 -0
  42. episteme/plans/__init__.py +29 -0
  43. episteme/plans/store.py +485 -0
  44. episteme/prompting.py +505 -0
  45. episteme/server.py +308 -0
  46. episteme/session/__init__.py +44 -0
  47. episteme/session/actions.py +145 -0
  48. episteme/session/capture.py +339 -0
  49. episteme/session/gate.py +64 -0
  50. episteme/session/store.py +539 -0
  51. episteme/tools/__init__.py +1 -0
  52. episteme/tools/args.py +41 -0
  53. episteme/tools/docs.py +188 -0
  54. episteme/tools/hooks.py +458 -0
  55. episteme/tools/memories.py +294 -0
  56. episteme/tools/messages.py +386 -0
  57. episteme/tools/plans.py +167 -0
  58. episteme/tools/reading.py +247 -0
  59. episteme/tools/recall.py +178 -0
  60. episteme/tools/session.py +263 -0
  61. episteme/untrusted.py +58 -0
  62. episteme/vault.py +792 -0
  63. episteme/worktree.py +38 -0
  64. episteme_memory-0.40.0.dist-info/METADATA +214 -0
  65. episteme_memory-0.40.0.dist-info/RECORD +68 -0
  66. episteme_memory-0.40.0.dist-info/WHEEL +4 -0
  67. episteme_memory-0.40.0.dist-info/entry_points.txt +3 -0
  68. episteme_memory-0.40.0.dist-info/licenses/LICENSE +21 -0
episteme/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """episteme: an MCP server over an Obsidian-compatible Markdown vault."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ # Read from the installed package, so pyproject.toml stays the only place that sets it.
6
+ __version__ = version("episteme-memory")
episteme/__main__.py ADDED
@@ -0,0 +1,122 @@
1
+ """Entry point: parse --vault and --project, validate and start the stdio server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import contextlib
7
+ import os
8
+ import sqlite3
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from episteme.errors import StartupError
13
+ from episteme.perms import FILE_MODE, make_private_dir
14
+ from episteme.vault import CONFIG_FILE
15
+
16
+ DEFAULT_TOML = """\
17
+ # Vault global de episteme, creado al arrancar sin --vault ni EPISTEME_VAULT.
18
+ # Una ruta que no está en ninguna zona es de solo lectura.
19
+
20
+ [zones."memory"]
21
+ mode = "memory"
22
+
23
+ # Estado de la sesión: solo lo escribe el tool session (se añade aunque no se declare).
24
+ [zones."sesiones"]
25
+ mode = "session"
26
+
27
+ # Estado de la sesión (descomenta para cambiar).
28
+ # [session]
29
+ # extract = true # orden de extracción tras /clear, compact sin gate y al retomar
30
+ # compact_state = true # el resumen de compactación escribe el estado de la sesión
31
+ # archive_days = 7 # días sin guardar antes de archivar el estado (entero >= 1)
32
+ # nudge_every = 0 # mensajes sin guardar antes del aviso (entero >= 0; 0 lo apaga)
33
+
34
+ # Mantención al abrir la primera sesión del periodo (descomenta para cambiar).
35
+ # [maintenance]
36
+ # every_days = 1 # periodo en días (entero >= 1)
37
+ # notify = true # avisa de pendientes de review (solo lectura)
38
+ # archive_expired = false # archiva las memorias vencidas
39
+
40
+ # Respaldo .tar.gz del vault; sin esta tabla no hay respaldo (dir es obligatorio).
41
+ # [backup]
42
+ # dir = "~/backups/episteme" # ruta absoluta, fuera del vault
43
+ # keep = 14 # respaldos que se conservan (entero >= 1)
44
+ """
45
+
46
+
47
+ def _check_fts5() -> None:
48
+ try:
49
+ with contextlib.closing(sqlite3.connect(":memory:")) as conn:
50
+ conn.execute("create virtual table t using fts5(x)")
51
+ except sqlite3.OperationalError as exc:
52
+ raise StartupError(
53
+ "this Python's SQLite has no FTS5 support. Use a Python build with FTS5."
54
+ ) from exc
55
+
56
+
57
+ def default_vault() -> Path:
58
+ return Path.home() / ".episteme"
59
+
60
+
61
+ def resolve_vault(arg: str | None) -> Path:
62
+ """Return the vault from ``--vault``, ``EPISTEME_VAULT`` or ``~/.episteme``.
63
+
64
+ An explicit path must already be a vault; only the default one is created when missing.
65
+ """
66
+ raw = arg or os.environ.get("EPISTEME_VAULT") or _default_vault_raw()
67
+ return _check_vault_path(raw)
68
+
69
+
70
+ def _default_vault_raw() -> str:
71
+ """The default vault path as a string, creating it (owner-only) when missing."""
72
+ path = default_vault()
73
+ if not path.exists():
74
+ make_private_dir(path)
75
+ fd = os.open(path / CONFIG_FILE, os.O_WRONLY | os.O_CREAT | os.O_EXCL, FILE_MODE)
76
+ with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh:
77
+ fh.write(DEFAULT_TOML)
78
+ return str(path)
79
+
80
+
81
+ def _check_vault_path(raw: str) -> Path:
82
+ """The vault at ``raw`` once it is absolute, an existing directory and has the config."""
83
+ path = Path(raw)
84
+ if not path.is_absolute():
85
+ raise StartupError(f'vault path "{raw}" is not absolute. Pass an absolute path.')
86
+ if not path.is_dir():
87
+ raise StartupError(f'vault path "{raw}" does not exist or is not a directory.')
88
+ if not (path / CONFIG_FILE).is_file():
89
+ raise StartupError(
90
+ f'"{raw}" has no {CONFIG_FILE}. '
91
+ "Create it at the vault root to mark the folder as a vault."
92
+ )
93
+ return path
94
+
95
+
96
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
97
+ parser = argparse.ArgumentParser(
98
+ prog="episteme", description="MCP server for an episteme Markdown vault."
99
+ )
100
+ parser.add_argument(
101
+ "--vault", help="absolute path of the vault (or EPISTEME_VAULT; default ~/.episteme)"
102
+ )
103
+ parser.add_argument("--project", help="default project for memory tools, e.g. fabrik")
104
+ return parser.parse_args(argv)
105
+
106
+
107
+ def main(argv: list[str] | None = None) -> None:
108
+ args = parse_args(argv)
109
+ try:
110
+ vault = resolve_vault(args.vault)
111
+ _check_fts5()
112
+ from episteme.server import build_server
113
+
114
+ server = build_server(vault, args.project)
115
+ except StartupError as exc:
116
+ print(f"episteme: {exc}", file=sys.stderr)
117
+ sys.exit(2)
118
+ server.run("stdio")
119
+
120
+
121
+ if __name__ == "__main__":
122
+ main()
episteme/activity.py ADDED
@@ -0,0 +1,260 @@
1
+ """Activity log: one row per tool call in ``<vault>/.index/activity.db``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import sqlite3
9
+ from datetime import UTC, datetime, timedelta
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from episteme.memory.secrets import redact_secrets
14
+ from episteme.perms import make_private_dir, restrict_db
15
+ from episteme.vault import INDEX_DIR
16
+
17
+ SCHEMA_VERSION = 2
18
+ RETENTION_DAYS = 180
19
+ MAX_PATHS = 30
20
+ MAX_STRING = 200
21
+ MAX_DEPTH = 4 # nesting kept in a logged argument; deeper containers become "[...]"
22
+ MAX_ITEMS = 50 # items kept per logged list or dict
23
+ MAX_WALK_DEPTH = 3
24
+ CONNECT_TIMEOUT_S = 5.0
25
+ BUSY_TIMEOUT_MS = 5000
26
+ ARG_KEYS = (
27
+ "mode", "action", "type", "path", "note", "notes", "file", "relative_path", "query",
28
+ "tags", "status", "zone", "heading", "lines", "limit", "match", "title", "task",
29
+ "trigger", "source", "reason", "origin", "slug", "to", "urgent",
30
+ ) # fmt: skip
31
+ _MD_IN_PARENS = re.compile(r"\(([^()\s]+\.md)\)")
32
+
33
+ _SCHEMA = """
34
+ create table calls (
35
+ id integer primary key,
36
+ at text, pid integer, session text, tool text, hook_event text, project text,
37
+ args text, paths text, chars integer, ms integer, ok integer, client text
38
+ );
39
+ create index calls_at on calls (at);
40
+ create index calls_tool on calls (tool);
41
+ """
42
+
43
+
44
+ def _clip(value: Any, depth: int = 0) -> Any:
45
+ """``value`` with credentials redacted, strings cut and containers capped."""
46
+ if isinstance(value, str):
47
+ return redact_secrets(value)[:MAX_STRING]
48
+ if isinstance(value, (list, tuple, dict)):
49
+ return _clip_container(value, depth)
50
+ return value
51
+
52
+
53
+ def _clip_container(value: list[Any] | tuple[Any, ...] | dict[Any, Any], depth: int) -> Any:
54
+ if depth >= MAX_DEPTH:
55
+ return "[...]"
56
+ if isinstance(value, dict):
57
+ items = list(value.items())[:MAX_ITEMS]
58
+ return {_clip(str(k), depth + 1): _clip(v, depth + 1) for k, v in items}
59
+ return [_clip(v, depth + 1) for v in value[:MAX_ITEMS]]
60
+
61
+
62
+ def _walk(node: Any, depth: int, found: list[str]) -> None:
63
+ if depth > MAX_WALK_DEPTH:
64
+ return
65
+ if isinstance(node, dict):
66
+ _walk_dict(node, depth, found)
67
+ elif isinstance(node, list):
68
+ _walk_list(node, depth, found)
69
+
70
+
71
+ def _collect_key(key: str, value: Any, found: list[str]) -> bool:
72
+ """Collect the strings under a ``path``/``paths`` key; False for any other key or shape."""
73
+ if key == "path" and isinstance(value, str):
74
+ found.append(value)
75
+ return True
76
+ if key == "paths" and isinstance(value, list):
77
+ found.extend(v for v in value if isinstance(v, str))
78
+ return True
79
+ return False
80
+
81
+
82
+ def _walk_dict(node: dict[str, Any], depth: int, found: list[str]) -> None:
83
+ for key, value in node.items():
84
+ if not _collect_key(key, value, found):
85
+ _walk(value, depth + 1, found)
86
+
87
+
88
+ def _walk_list(node: list[Any], depth: int, found: list[str]) -> None:
89
+ for item in node:
90
+ _walk(item, depth + 1, found)
91
+
92
+
93
+ def extract_paths(text: str) -> list[str]:
94
+ """Vault paths that appear in a tool result (JSON ``path``/``paths`` or ``(x.md)``)."""
95
+ found: list[str] = []
96
+ if text.lstrip().startswith(("{", "[")):
97
+ try:
98
+ _walk(json.loads(text), 0, found)
99
+ except ValueError:
100
+ # Not valid JSON after all: the ``(x.md)`` scan below still applies.
101
+ pass
102
+ found.extend(_MD_IN_PARENS.findall(text))
103
+ return list(dict.fromkeys(found))[:MAX_PATHS]
104
+
105
+
106
+ def _read_paths(text: str) -> list[str]:
107
+ """The notes a ``read`` result opened: its top ``path`` or each entry of ``notes``.
108
+
109
+ The neighbours under ``links`` and the ``(x.md)`` links in the body were not read.
110
+ """
111
+ try:
112
+ data = json.loads(text)
113
+ except ValueError:
114
+ return []
115
+ if not isinstance(data, dict):
116
+ return []
117
+ entries = data["notes"] if isinstance(data.get("notes"), list) else [data]
118
+ found = [e["path"] for e in entries if isinstance(e, dict) and isinstance(e.get("path"), str)]
119
+ return list(dict.fromkeys(found))[:MAX_PATHS]
120
+
121
+
122
+ def call_paths(tool: str, text: str) -> list[str]:
123
+ """Vault paths to log for one call: the notes read for ``read``, every path otherwise."""
124
+ return _read_paths(text) if tool == "read" else extract_paths(text)
125
+
126
+
127
+ def used_paths(db_path: Path, since: datetime) -> set[str]:
128
+ """Paths delivered by ``read`` or ``context`` since ``since``; empty if the log is unreadable.
129
+
130
+ Opens the log read-only, so it never creates the database.
131
+ """
132
+ if not db_path.is_file():
133
+ return set()
134
+ cutoff = since.astimezone(UTC).isoformat(timespec="seconds")
135
+ try:
136
+ conn = sqlite3.connect(
137
+ f"{db_path.resolve().as_uri()}?mode=ro", uri=True, timeout=CONNECT_TIMEOUT_S
138
+ )
139
+ try:
140
+ rows = conn.execute(
141
+ "select paths from calls where tool in ('read', 'context') and at >= ?",
142
+ (cutoff,),
143
+ ).fetchall()
144
+ finally:
145
+ conn.close()
146
+ found: set[str] = set()
147
+ for (raw,) in rows:
148
+ found.update(p for p in json.loads(raw or "[]") if isinstance(p, str))
149
+ except (sqlite3.Error, ValueError, OSError):
150
+ return set()
151
+ return found
152
+
153
+
154
+ def _text(value: Any) -> str | None:
155
+ """A non-empty string argument, redacted when it looks like a credential."""
156
+ if not isinstance(value, str) or not value:
157
+ return None
158
+ return _clip(value)
159
+
160
+
161
+ def _migrate(conn: sqlite3.Connection) -> None:
162
+ """Bring ``calls`` to ``SCHEMA_VERSION``: v1 gains ``client`` in place, older is rebuilt."""
163
+ version = conn.execute("pragma user_version").fetchone()[0]
164
+ if version >= SCHEMA_VERSION:
165
+ return
166
+ # One transaction: a crash never leaves the new column without its user_version.
167
+ conn.execute("begin immediate")
168
+ try:
169
+ if version == 1:
170
+ conn.execute("alter table calls add column client text")
171
+ else:
172
+ conn.execute("drop table if exists calls")
173
+ for statement in filter(str.strip, _SCHEMA.split(";")):
174
+ conn.execute(statement)
175
+ conn.execute(f"pragma user_version = {SCHEMA_VERSION}")
176
+ conn.execute("commit")
177
+ except Exception:
178
+ conn.execute("rollback")
179
+ raise
180
+
181
+
182
+ class Activity:
183
+ """Best-effort call log; ``record`` never raises."""
184
+
185
+ def __init__(self, vault_root: Path) -> None:
186
+ self.db_path = Path(vault_root) / INDEX_DIR / "activity.db"
187
+ self._conn: sqlite3.Connection | None = None
188
+ self._pruned = False
189
+
190
+ def _connect(self) -> sqlite3.Connection:
191
+ if self._conn is None:
192
+ make_private_dir(self.db_path.parent)
193
+ conn = sqlite3.connect(
194
+ self.db_path,
195
+ timeout=CONNECT_TIMEOUT_S,
196
+ isolation_level=None,
197
+ check_same_thread=False,
198
+ )
199
+ try:
200
+ conn.execute("pragma journal_mode = wal")
201
+ conn.execute(f"pragma busy_timeout = {BUSY_TIMEOUT_MS}")
202
+ restrict_db(self.db_path)
203
+ _migrate(conn)
204
+ except Exception:
205
+ conn.close()
206
+ raise
207
+ self._conn = conn
208
+ return self._conn
209
+
210
+ def record(
211
+ self,
212
+ tool: str,
213
+ arguments: dict[str, Any] | None,
214
+ text: str,
215
+ ms: int,
216
+ ok: bool,
217
+ client: str | None = None,
218
+ session: str | None = None,
219
+ ) -> None:
220
+ """Log one call; ``session`` is used when ``arguments`` carry none (agy's ``_meta``)."""
221
+ try:
222
+ if os.environ.get("EPISTEME_ACTIVITY") == "0":
223
+ return
224
+ arguments = arguments if isinstance(arguments, dict) else {}
225
+ conn = self._connect()
226
+ now = datetime.now(UTC)
227
+ if not self._pruned:
228
+ self._pruned = True
229
+ cutoff = (now - timedelta(days=RETENTION_DAYS)).isoformat(timespec="seconds")
230
+ conn.execute("delete from calls where at < ?", (cutoff,))
231
+ args = {k: _clip(arguments[k]) for k in ARG_KEYS if k in arguments}
232
+ text = text or ""
233
+ conn.execute(
234
+ "insert into calls (at, pid, session, tool, hook_event, project, args,"
235
+ " paths, chars, ms, ok, client) values (?,?,?,?,?,?,?,?,?,?,?,?)",
236
+ (
237
+ now.isoformat(timespec="seconds"),
238
+ os.getpid(),
239
+ _text(arguments.get("session")) or _text(session),
240
+ tool,
241
+ _text(arguments.get("hook_event")),
242
+ _text(arguments.get("project")),
243
+ json.dumps(args, ensure_ascii=False, default=str),
244
+ json.dumps(call_paths(tool, text), ensure_ascii=False),
245
+ len(text),
246
+ int(ms),
247
+ 1 if ok else 0,
248
+ _text(client),
249
+ ),
250
+ )
251
+ except Exception: # nosec B110
252
+ pass
253
+
254
+ def close(self) -> None:
255
+ if self._conn is not None:
256
+ try:
257
+ self._conn.close()
258
+ except Exception: # nosec B110
259
+ pass
260
+ self._conn = None
episteme/backup.py ADDED
@@ -0,0 +1,163 @@
1
+ """Rotating ``.tar.gz`` backups of a vault's writable zones and its config file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ import hashlib
7
+ import logging
8
+ import os
9
+ import sqlite3
10
+ import stat
11
+ import tarfile
12
+ import tempfile
13
+ import time
14
+ from pathlib import Path
15
+
16
+ from episteme.perms import make_private_dir
17
+ from episteme.vault import CONFIG_FILE, DOCS, READ_ONLY, Vault
18
+
19
+ PREFIX = "episteme-"
20
+ SUFFIX = ".tar.gz"
21
+ STALE_TMP_SECONDS = 3600
22
+ SEAL_LENGTH = 12
23
+ STAMP_FORMAT = "%Y%m%dT%H%M%SZ"
24
+ TMP_PREFIX = ".episteme-backup-"
25
+ TMP_GLOB = f"{TMP_PREFIX}*.tmp"
26
+ # Docs zones hold third-party pages that /episteme-docs:docs can download again.
27
+ SKIPPED_MODES = (READ_ONLY, DOCS)
28
+ MESSAGES_DB = ".index/messages.db"
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def _members(vault: Vault) -> list[tuple[str, os.stat_result]]:
33
+ """Notes of the backed-up zones plus the config file, sorted by relative path."""
34
+ found = [
35
+ (rel, st) for rel, st in vault.iter_notes() if vault.mode_for(rel) not in SKIPPED_MODES
36
+ ]
37
+ try:
38
+ config = (vault.root / CONFIG_FILE).lstat()
39
+ except OSError:
40
+ config = None # A vault without its config file is still backed up: only notes go in.
41
+ if config is not None and stat.S_ISREG(config.st_mode):
42
+ found.append((CONFIG_FILE, config))
43
+ return sorted(found, key=lambda item: item[0])
44
+
45
+
46
+ def _messages_files(vault: Vault) -> list[tuple[str, os.stat_result]]:
47
+ """``messages.db`` and its WAL, as stat entries for the seal (cheap: nothing is read)."""
48
+ found = []
49
+ for rel in (MESSAGES_DB, f"{MESSAGES_DB}-wal"):
50
+ try:
51
+ found.append((rel, (vault.root / rel).stat()))
52
+ except OSError:
53
+ continue # Absent: the vault has no message database (or no WAL right now).
54
+ return found
55
+
56
+
57
+ def _seal(members: list[tuple[str, os.stat_result]]) -> str:
58
+ lines = sorted(f"{rel}\0{st.st_mtime_ns}\0{st.st_size}" for rel, st in members)
59
+ return hashlib.sha256("\n".join(lines).encode("utf-8")).hexdigest()[:SEAL_LENGTH]
60
+
61
+
62
+ def _copy_messages(vault: Vault, tmp_dir: Path) -> Path | None:
63
+ """Consistent copy of ``messages.db`` (SQLite online backup) in ``tmp_dir``.
64
+
65
+ None if the database is absent, locked or corrupt: the notes are backed up anyway.
66
+ """
67
+ src = vault.root / MESSAGES_DB
68
+ if not src.is_file():
69
+ return None
70
+ copy = tmp_dir / "messages.db"
71
+ try:
72
+ source = sqlite3.connect(f"{src.as_uri()}?mode=ro", uri=True)
73
+ try:
74
+ target = sqlite3.connect(copy)
75
+ try:
76
+ source.backup(target)
77
+ finally:
78
+ target.close()
79
+ finally:
80
+ source.close()
81
+ except (sqlite3.Error, OSError) as exc:
82
+ logger.warning("backup: skipping %s, %s", MESSAGES_DB, exc)
83
+ return None
84
+ return copy
85
+
86
+
87
+ def run(vault: Vault, dest: Path, keep: int, now: dt.datetime | None = None) -> Path | None:
88
+ """Write a .tar.gz of the writable zones, episteme.toml and messages.db to dest.
89
+
90
+ None if unchanged.
91
+ """
92
+ members = _members(vault)
93
+ seal = _seal(members + _messages_files(vault))
94
+ dest = Path(dest)
95
+ if not dest.is_dir(): # an existing destination may be shared: leave its mode alone
96
+ make_private_dir(dest)
97
+
98
+ if _unchanged(dest, seal):
99
+ _rotate(dest, keep)
100
+ return None
101
+
102
+ stamp = (now or dt.datetime.now(dt.UTC)).strftime(STAMP_FORMAT)
103
+ # The database copy lives in the system temp dir, apart from the archives in ``dest``.
104
+ with tempfile.TemporaryDirectory(prefix="episteme-messages-") as tmp_dir:
105
+ snapshot = _copy_messages(vault, Path(tmp_dir))
106
+ if snapshot is None and (vault.root / MESSAGES_DB).is_file():
107
+ # The copy failed: seal without the database so that the next run retries it,
108
+ # but do not pile up identical database-less archives meanwhile.
109
+ seal = _seal(members)
110
+ if _unchanged(dest, seal):
111
+ _rotate(dest, keep)
112
+ return None
113
+ final = dest / f"{PREFIX}{stamp}-{seal}{SUFFIX}"
114
+ _write_archive(vault, members, dest, final, snapshot)
115
+
116
+ _rotate(dest, keep)
117
+ return final
118
+
119
+
120
+ def _unchanged(dest: Path, seal: str) -> bool:
121
+ """Whether the newest archive in ``dest`` already carries ``seal``."""
122
+ existing = sorted(p.name for p in dest.glob(f"{PREFIX}*{SUFFIX}"))
123
+ return bool(existing) and existing[-1].endswith(f"-{seal}{SUFFIX}")
124
+
125
+
126
+ def _write_archive(
127
+ vault: Vault,
128
+ members: list[tuple[str, os.stat_result]],
129
+ dest: Path,
130
+ final: Path,
131
+ snapshot: Path | None = None,
132
+ ) -> None:
133
+ """Write the members to a temp file in ``dest`` and move it to ``final``."""
134
+ fd, tmp_name = tempfile.mkstemp(dir=dest, prefix=TMP_PREFIX, suffix=".tmp")
135
+ os.close(fd)
136
+ tmp = Path(tmp_name)
137
+ try:
138
+ with tarfile.open(tmp, "w:gz") as tar:
139
+ for rel, _ in members:
140
+ try:
141
+ tar.add(vault.root / rel, arcname=rel)
142
+ except FileNotFoundError:
143
+ continue
144
+ if snapshot is not None:
145
+ tar.add(snapshot, arcname=MESSAGES_DB)
146
+ os.replace(tmp, final)
147
+ except BaseException:
148
+ tmp.unlink(missing_ok=True)
149
+ raise
150
+
151
+
152
+ def _rotate(dest: Path, keep: int) -> None:
153
+ archives = sorted(dest.glob(f"{PREFIX}*{SUFFIX}"), key=lambda p: p.name)
154
+ keep = max(keep, 1) # never delete the newest archive
155
+ for old in archives[: max(len(archives) - keep, 0)]:
156
+ old.unlink(missing_ok=True)
157
+ cutoff = time.time() - STALE_TMP_SECONDS
158
+ for tmp in dest.glob(TMP_GLOB):
159
+ try:
160
+ if tmp.stat().st_mtime < cutoff:
161
+ tmp.unlink()
162
+ except OSError:
163
+ continue # A stale temp file we cannot stat or remove is retried on the next backup.
@@ -0,0 +1,21 @@
1
+ """Docs suites: zones of third-party pages that only the ``docs`` tool (action write) changes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from episteme.docs.hashing import HASH_LEN, body_hash, page_body
6
+ from episteme.docs.inbox import INBOX_DIR, inbox_dir
7
+ from episteme.docs.removal import TRASH_DIR, docs_remove
8
+ from episteme.docs.status import docs_status
9
+ from episteme.docs.writing import docs_write
10
+
11
+ __all__ = [
12
+ "HASH_LEN",
13
+ "INBOX_DIR",
14
+ "TRASH_DIR",
15
+ "body_hash",
16
+ "docs_remove",
17
+ "docs_status",
18
+ "docs_write",
19
+ "inbox_dir",
20
+ "page_body",
21
+ ]
@@ -0,0 +1,55 @@
1
+ """The body hash of a suite note, shared with the skill's ``docs_check.py``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ from episteme.markdown import load_frontmatter, split_frontmatter
11
+
12
+ HASH_LEN = 16
13
+ PAGE_FRONTMATTER_RE = re.compile(
14
+ r"---[ \t]*\n(?:(?:[\w.-]+:.*|[ \t].*|- .*|#.*)?\n)*?---[ \t]*(?:\n|\Z)"
15
+ )
16
+
17
+
18
+ def _lines(text: str) -> str:
19
+ return text.replace("\r\n", "\n").replace("\r", "\n")
20
+
21
+
22
+ def body_hash(body: str) -> str:
23
+ """The first 16 hex digits of the SHA-256 of ``body`` with normalised line ends.
24
+
25
+ ``docs_check.py`` (plugin-docs/skills/docs/scripts) carries a copy: change both at once.
26
+ """
27
+ text = _lines(body).strip() + "\n"
28
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()[:HASH_LEN]
29
+
30
+
31
+ def page_body(text: str) -> str:
32
+ """``text`` without the YAML frontmatter block a downloaded page may start with.
33
+
34
+ Only a block whose lines all look like YAML (``key:``, indented, ``- item``, a comment
35
+ or blank) counts, so a page that opens with a thematic break keeps it. Line ends come
36
+ back normalised. ``docs_check.py`` carries a copy: change both at once.
37
+ """
38
+ text = _lines(text)
39
+ match = PAGE_FRONTMATTER_RE.match(text)
40
+ return text[match.end() :].lstrip("\n") if match else text
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class SplitNote:
45
+ frontmatter: dict[str, Any]
46
+ fm_valid: bool
47
+ body: str
48
+
49
+
50
+ def split_note(text: str) -> SplitNote:
51
+ """The frontmatter of a note and its body (what follows the frontmatter block)."""
52
+ lines = _lines(text).split("\n")
53
+ raw, end = split_frontmatter(lines)
54
+ fm, valid, _ = load_frontmatter(raw)
55
+ return SplitNote(fm, valid, "\n".join(lines[end:]))