engram-mcp-server 0.6.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 (112) hide show
  1. engram/__init__.py +14 -0
  2. engram/__main__.py +20 -0
  3. engram/bundle/__init__.py +48 -0
  4. engram/bundle/exporter.py +230 -0
  5. engram/bundle/format.py +109 -0
  6. engram/bundle/importer.py +509 -0
  7. engram/cli/__init__.py +82 -0
  8. engram/cli/bundle.py +236 -0
  9. engram/cli/clone.py +120 -0
  10. engram/cli/consolidate.py +436 -0
  11. engram/cli/daemon.py +563 -0
  12. engram/cli/delete.py +213 -0
  13. engram/cli/doctor.py +239 -0
  14. engram/cli/init.py +123 -0
  15. engram/cli/llm.py +303 -0
  16. engram/cli/migrate.py +171 -0
  17. engram/cli/move_thought.py +333 -0
  18. engram/cli/reindex.py +134 -0
  19. engram/cli/serve.py +583 -0
  20. engram/cli/serve_multivault.py +244 -0
  21. engram/cli/sync.py +316 -0
  22. engram/cli/team_vault.py +1135 -0
  23. engram/config/__init__.py +44 -0
  24. engram/config/loader.py +338 -0
  25. engram/config/models.py +384 -0
  26. engram/consolidate/__init__.py +10 -0
  27. engram/consolidate/apply.py +400 -0
  28. engram/consolidate/clustering.py +156 -0
  29. engram/consolidate/guards.py +105 -0
  30. engram/consolidate/llm.py +149 -0
  31. engram/consolidate/models.py +270 -0
  32. engram/consolidate/pairs.py +50 -0
  33. engram/consolidate/passes.py +473 -0
  34. engram/consolidate/report.py +70 -0
  35. engram/consolidate/staleness.py +67 -0
  36. engram/daemon/__init__.py +34 -0
  37. engram/daemon/auth.py +106 -0
  38. engram/daemon/client.py +706 -0
  39. engram/daemon/fastmcp_dispatch.py +175 -0
  40. engram/daemon/log_rotation.py +106 -0
  41. engram/daemon/protocol.py +80 -0
  42. engram/daemon/server.py +500 -0
  43. engram/daemon/socket_paths.py +87 -0
  44. engram/daemon/spawn.py +186 -0
  45. engram/daemon/state.py +72 -0
  46. engram/diagnostics/__init__.py +24 -0
  47. engram/diagnostics/check_codes.py +227 -0
  48. engram/diagnostics/consolidate_checks.py +103 -0
  49. engram/diagnostics/daemon_checks.py +330 -0
  50. engram/diagnostics/doctor.py +745 -0
  51. engram/diagnostics/phase3_checks.py +426 -0
  52. engram/diagnostics/phase4_checks.py +346 -0
  53. engram/embedding/__init__.py +29 -0
  54. engram/embedding/fastembed.py +335 -0
  55. engram/embedding/model_hashes.py +77 -0
  56. engram/embedding/protocol.py +35 -0
  57. engram/errors.py +438 -0
  58. engram/llm/__init__.py +55 -0
  59. engram/llm/budget.py +228 -0
  60. engram/llm/citations.py +79 -0
  61. engram/llm/protocol.py +86 -0
  62. engram/llm/providers.py +469 -0
  63. engram/llm/resolver.py +246 -0
  64. engram/logging.py +117 -0
  65. engram/mcp/__init__.py +30 -0
  66. engram/mcp/llm_tools.py +377 -0
  67. engram/mcp/server.py +434 -0
  68. engram/mcp/tools.py +282 -0
  69. engram/migration/__init__.py +36 -0
  70. engram/migration/open_brain.py +599 -0
  71. engram/models/__init__.py +60 -0
  72. engram/models/frontmatter.py +171 -0
  73. engram/models/mcp.py +237 -0
  74. engram/models/thought.py +57 -0
  75. engram/multivault/__init__.py +47 -0
  76. engram/multivault/aggregator.py +365 -0
  77. engram/multivault/portability.py +112 -0
  78. engram/multivault/registry.py +290 -0
  79. engram/py.typed +0 -0
  80. engram/storage/__init__.py +14 -0
  81. engram/storage/archive.py +93 -0
  82. engram/storage/facade.py +681 -0
  83. engram/storage/markdown.py +398 -0
  84. engram/storage/reindex.py +400 -0
  85. engram/storage/sqlite.py +352 -0
  86. engram/storage/sqlite_queries.py +746 -0
  87. engram/sync/__init__.py +14 -0
  88. engram/sync/coordinator.py +819 -0
  89. engram/sync/gitops.py +628 -0
  90. engram/sync/identity.py +145 -0
  91. engram/sync/serve_hooks.py +85 -0
  92. engram/sync/startup_probes.py +545 -0
  93. engram/team/__init__.py +22 -0
  94. engram/team/capture_gate.py +94 -0
  95. engram/team/identity.py +242 -0
  96. engram/team/members.py +136 -0
  97. engram/team/policy.py +112 -0
  98. engram/team/push_queue.py +261 -0
  99. engram/team/routing.py +226 -0
  100. engram/team/server_hooks/__init__.py +14 -0
  101. engram/team/server_hooks/pre_receive.py +540 -0
  102. engram/utils/__init__.py +7 -0
  103. engram/utils/atomic_write.py +104 -0
  104. engram/utils/file_naming.py +143 -0
  105. engram/utils/fingerprint.py +43 -0
  106. engram/utils/lock.py +350 -0
  107. engram/utils/run_command.py +124 -0
  108. engram_mcp_server-0.6.0.dist-info/METADATA +289 -0
  109. engram_mcp_server-0.6.0.dist-info/RECORD +112 -0
  110. engram_mcp_server-0.6.0.dist-info/WHEEL +4 -0
  111. engram_mcp_server-0.6.0.dist-info/entry_points.txt +2 -0
  112. engram_mcp_server-0.6.0.dist-info/licenses/LICENSE +201 -0
engram/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """engram - personal AI memory backend.
2
+
3
+ A local-first MCP server with markdown source-of-truth, SQLite + sqlite-vec
4
+ vector search, and Open Brain-compatible MCP tool surface.
5
+
6
+ The engram thesis: portable, sovereign, protocol-compatible. See the
7
+ project README for the long-form rationale.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ __version__ = "0.6.0"
13
+
14
+ __all__ = ["__version__"]
engram/__main__.py ADDED
@@ -0,0 +1,20 @@
1
+ """Allow ``python -m engram`` to invoke the same typer app as the ``engram`` script.
2
+
3
+ The proxy's spawn dance (``engram.daemon.client._spawn_daemon_process``)
4
+ re-execs the daemon as ``sys.executable -m engram daemon start ...``
5
+ because that path is stable: it uses the same Python interpreter the
6
+ proxy is running in, with the same site-packages, regardless of how
7
+ the user installed engram (``uv tool``, ``pip install -e``, virtualenv,
8
+ etc.).
9
+
10
+ Delegates to :data:`engram.cli.app` (the typer app the console-script
11
+ entry point in ``pyproject.toml`` also resolves to), so ``python -m
12
+ engram --version`` and ``engram --version`` are identical.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from engram.cli import app
18
+
19
+ if __name__ == "__main__":
20
+ app()
@@ -0,0 +1,48 @@
1
+ """Bundle export/import (friend-share via snapshots, not git-pull).
2
+
3
+ Friend-share runs through ``engram export`` -> transport channel ->
4
+ ``engram import``, NOT live git-pull from a friend's vault. A friend's
5
+ git history is attacker-influenceable, and the bundle import gate is the
6
+ only place ``06-SECURITY.md`` lines 31-44 (path-traversal refusal,
7
+ per-file 1 MB, per-bundle 4 GB streaming, ``yaml.safe_load`` only,
8
+ id-collision refusal, ``portability=block`` filtering) can be applied
9
+ to friend content.
10
+
11
+ This package surfaces three things:
12
+
13
+ * :class:`BundleManifest` (in :mod:`format`): the on-disk
14
+ ``manifest.json`` schema, schema_version=1.
15
+ * :class:`BundleExporter` (in :mod:`exporter`): streams a tar.gz of
16
+ ``thoughts/`` + ``manifest.json`` to disk under per-file and total
17
+ size caps; manifest is written LAST so a partial bundle has no
18
+ manifest and is detectable.
19
+ * :class:`BundleImporter` (in :mod:`importer`): the bundle reception
20
+ gate; staged-then-merged with id-collision pre-flight + bundle_id
21
+ cycle detection.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from engram.bundle.exporter import BundleExporter, BundleExportResult
27
+ from engram.bundle.format import (
28
+ BUNDLE_MANIFEST_FILENAME,
29
+ BUNDLE_SCHEMA_VERSION,
30
+ BUNDLE_THOUGHTS_DIR,
31
+ MAX_PER_FILE_BYTES,
32
+ MAX_TOTAL_BYTES,
33
+ BundleManifest,
34
+ )
35
+ from engram.bundle.importer import BundleImporter, BundleImportResult
36
+
37
+ __all__ = [
38
+ "BUNDLE_MANIFEST_FILENAME",
39
+ "BUNDLE_SCHEMA_VERSION",
40
+ "BUNDLE_THOUGHTS_DIR",
41
+ "MAX_PER_FILE_BYTES",
42
+ "MAX_TOTAL_BYTES",
43
+ "BundleExportResult",
44
+ "BundleExporter",
45
+ "BundleImportResult",
46
+ "BundleImporter",
47
+ "BundleManifest",
48
+ ]
@@ -0,0 +1,230 @@
1
+ """Bundle exporter.
2
+
3
+ Streams a tar.gz archive of a vault's thoughts plus a ``manifest.json`` to
4
+ disk:
5
+
6
+ * Each thought file's bytes-on-disk are checked against
7
+ :data:`engram.bundle.format.MAX_PER_FILE_BYTES` (1 MB) and refused
8
+ with :class:`engram.errors.BundleImportError` if oversized.
9
+ * A rolling counter sums the cumulative bytes-written; if it would
10
+ exceed :data:`engram.bundle.format.MAX_TOTAL_BYTES` (4 GB) the export
11
+ aborts before the next file write.
12
+ * Only thoughts whose ``portability`` is in the requested filter list
13
+ are included. The default filter is ``["portable"]``; the CLI
14
+ command exposes a repeatable ``--portability`` flag.
15
+ * Atomic via temp-then-rename: writes go to ``<output>.tmp``; on
16
+ successful close the temp file is renamed onto ``<output>``.
17
+ * The manifest is written LAST inside the tar so a partial bundle
18
+ (writer crashed mid-stream) lacks a manifest. The importer's first
19
+ read is the manifest; missing manifest -> hard refuse without
20
+ opening any other member.
21
+
22
+ This skips git-related side effects entirely - a bundle is a
23
+ point-in-time snapshot. Live updates use ``engram clone-vault`` plus
24
+ pull, not bundle re-export.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import contextlib
30
+ import io
31
+ import logging
32
+ import tarfile
33
+ from collections.abc import Iterable
34
+ from dataclasses import dataclass, field
35
+ from pathlib import Path
36
+ from typing import TYPE_CHECKING
37
+
38
+ from uuid_extensions import uuid7
39
+
40
+ from engram.bundle.format import (
41
+ BUNDLE_MANIFEST_FILENAME,
42
+ BUNDLE_THOUGHTS_DIR,
43
+ MAX_PER_FILE_BYTES,
44
+ MAX_TOTAL_BYTES,
45
+ BundleManifest,
46
+ now_utc,
47
+ )
48
+ from engram.errors import BundleImportError, VaultError
49
+ from engram.models.frontmatter import Portability
50
+
51
+ if TYPE_CHECKING:
52
+ from uuid import UUID
53
+
54
+ from engram.storage.facade import VaultStorage
55
+
56
+ _log = logging.getLogger("engram.bundle.exporter")
57
+
58
+
59
+ @dataclass(slots=True)
60
+ class BundleExportResult:
61
+ """Summary returned by :meth:`BundleExporter.export_to`."""
62
+
63
+ bundle_path: Path
64
+ manifest: BundleManifest
65
+ bytes_written: int = 0
66
+ skipped_oversized: list[str] = field(default_factory=list)
67
+ skipped_outside_filter: int = 0
68
+
69
+
70
+ class BundleExporter:
71
+ """Stream a vault's portable thoughts into a tar.gz bundle.
72
+
73
+ Construction is cheap; call :meth:`export_to` to actually write.
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ *,
79
+ storage: VaultStorage,
80
+ portability_filter: Iterable[Portability] = ("portable",),
81
+ source_user: str = "engram-user",
82
+ embedding_model: str | None = None,
83
+ ) -> None:
84
+ """Bind exporter to a source vault + portability filter."""
85
+ self.storage = storage
86
+ self.portability_filter: tuple[Portability, ...] = tuple(portability_filter)
87
+ if not self.portability_filter:
88
+ msg = "BundleExporter requires at least one portability tier in the filter"
89
+ raise VaultError(msg)
90
+ if "block" in self.portability_filter:
91
+ msg = "BundleExporter refuses portability='block'; bundles are friend-share only"
92
+ raise VaultError(msg)
93
+ self.source_user = source_user
94
+ self.embedding_model = embedding_model or "unknown"
95
+
96
+ def _new_bundle_id(self) -> UUID:
97
+ from uuid import UUID
98
+
99
+ return UUID(str(uuid7()))
100
+
101
+ def export_to(self, output_path: Path | str) -> BundleExportResult:
102
+ """Write the bundle to ``output_path`` and return a summary.
103
+
104
+ The output path must NOT already exist (refuses to overwrite). On
105
+ success the file is renamed atomically from ``<path>.tmp``.
106
+
107
+ Raises:
108
+ BundleImportError: when a single thought file exceeds
109
+ :data:`MAX_PER_FILE_BYTES` or the cumulative bundle size
110
+ would exceed :data:`MAX_TOTAL_BYTES`.
111
+ VaultError: when the output path already exists.
112
+ """
113
+ output_path = Path(output_path).expanduser()
114
+ if output_path.exists():
115
+ msg = (
116
+ f"refusing to overwrite existing bundle path: {output_path}; "
117
+ "remove it or pick a different --output"
118
+ )
119
+ raise VaultError(msg)
120
+
121
+ tmp_path = output_path.with_suffix(output_path.suffix + ".tmp")
122
+ if tmp_path.exists():
123
+ tmp_path.unlink()
124
+
125
+ bundle_id = self._new_bundle_id()
126
+ # Iterate eligible thoughts FIRST so the manifest's thought_count
127
+ # is accurate and the size accounting can fail cleanly.
128
+ thoughts, skipped_outside_filter = self._collect_eligible_thoughts()
129
+
130
+ manifest = BundleManifest(
131
+ schema_version=1,
132
+ source_user=self.source_user,
133
+ source_vault=self.storage.vault_name,
134
+ exported_at=now_utc(),
135
+ thought_count=len(thoughts),
136
+ portability_filter=list(self.portability_filter),
137
+ embedding_model=self.embedding_model,
138
+ bundle_id=bundle_id,
139
+ )
140
+
141
+ result = BundleExportResult(
142
+ bundle_path=output_path,
143
+ manifest=manifest,
144
+ skipped_outside_filter=skipped_outside_filter,
145
+ )
146
+
147
+ try:
148
+ with tarfile.open(str(tmp_path), mode="w|gz") as tar:
149
+ for rel_path, abs_path in thoughts:
150
+ file_size = abs_path.stat().st_size
151
+ if file_size > MAX_PER_FILE_BYTES:
152
+ result.skipped_oversized.append(str(rel_path))
153
+ _log.warning(
154
+ "bundle export skipping oversized file %s (%d bytes > %d limit)",
155
+ rel_path,
156
+ file_size,
157
+ MAX_PER_FILE_BYTES,
158
+ )
159
+ continue
160
+ if result.bytes_written + file_size > MAX_TOTAL_BYTES:
161
+ msg = (
162
+ f"bundle export would exceed {MAX_TOTAL_BYTES} bytes "
163
+ f"after adding {rel_path}; aborting"
164
+ )
165
+ raise BundleImportError(msg)
166
+ member_name = f"{BUNDLE_THOUGHTS_DIR}/{rel_path.as_posix()}"
167
+ tar.add(str(abs_path), arcname=member_name)
168
+ result.bytes_written += file_size
169
+
170
+ manifest_bytes = manifest.to_json().encode("utf-8")
171
+ manifest_info = tarfile.TarInfo(name=BUNDLE_MANIFEST_FILENAME)
172
+ manifest_info.size = len(manifest_bytes)
173
+ manifest_info.mtime = int(manifest.exported_at.timestamp())
174
+ tar.addfile(manifest_info, _bytes_io(manifest_bytes))
175
+ result.bytes_written += len(manifest_bytes)
176
+ except BaseException:
177
+ with _suppress_oserror():
178
+ tmp_path.unlink(missing_ok=True)
179
+ raise
180
+
181
+ tmp_path.rename(output_path)
182
+ return result
183
+
184
+ def _collect_eligible_thoughts(self) -> tuple[list[tuple[Path, Path]], int]:
185
+ """Iterate the storage and pick thoughts in the portability filter.
186
+
187
+ Returns ``(eligible, skipped_count)`` where ``eligible`` is a
188
+ list of ``(repo_relative_path, absolute_path)`` tuples and the
189
+ skipped count is non-eligible thoughts (typically ``block`` or
190
+ ``sensitive`` rows that fall outside the filter).
191
+ """
192
+ from engram.models.mcp import Filter # noqa: F401
193
+
194
+ eligible: list[tuple[Path, Path]] = []
195
+ skipped = 0
196
+ # ``list_thoughts`` paginates; iterate in chunks of 500 so very
197
+ # large vaults still work without loading the whole row set.
198
+ offset = 0
199
+ page_size = 500
200
+ while True:
201
+ rows, total = self.storage.list_thoughts(
202
+ limit=page_size,
203
+ offset=offset,
204
+ filter_=None,
205
+ sort="created_at_asc",
206
+ )
207
+ for thought in rows:
208
+ if thought.portability not in self.portability_filter:
209
+ skipped += 1
210
+ continue
211
+ abs_path = thought.file_path
212
+ if not abs_path.exists():
213
+ skipped += 1
214
+ continue
215
+ rel_path = abs_path.relative_to(self.storage.thoughts_dir)
216
+ eligible.append((rel_path, abs_path))
217
+ offset += len(rows)
218
+ if offset >= total or not rows:
219
+ break
220
+ return eligible, skipped
221
+
222
+
223
+ def _bytes_io(data: bytes) -> io.BytesIO:
224
+ """Return a binary file-like object suitable for tarfile.addfile."""
225
+ return io.BytesIO(data)
226
+
227
+
228
+ def _suppress_oserror() -> contextlib.AbstractContextManager[None]:
229
+ """contextlib.suppress(OSError) without forcing module-level import."""
230
+ return contextlib.suppress(OSError)
@@ -0,0 +1,109 @@
1
+ """Bundle format Pydantic model + on-disk constants.
2
+
3
+ The on-disk format is a single ``.tar.gz`` containing:
4
+
5
+ * ``manifest.json`` at the archive root - this file. Read first; refused
6
+ if ``schema_version`` is not 1.
7
+ * ``thoughts/<rel-path>.md`` - one markdown file per exported thought.
8
+ ``<rel-path>`` mirrors the source vault's directory layout (e.g.
9
+ ``Pattern/2026/05/05/<id>.md``); the importer treats this as
10
+ data and re-anchors under the target vault's ``thoughts_dir``.
11
+
12
+ Per ``06-SECURITY.md`` lines 31-44, the bundle reception gate enforces:
13
+
14
+ * Per-file ceiling :data:`MAX_PER_FILE_BYTES` (1 MB).
15
+ * Total bundle ceiling :data:`MAX_TOTAL_BYTES` (4 GB).
16
+ * No ``..`` segments in member names; no absolute paths.
17
+ * ``yaml.safe_load`` only (already enforced upstream by the markdown
18
+ reader; the importer additionally re-validates schema before merge).
19
+ * Refuse duplicate ``id`` against existing thoughts in the target
20
+ vault.
21
+ * Reject members with ``portability: block`` (defense-in-depth - the
22
+ exporter shouldn't include them but a malicious / mistaken friend
23
+ push by hand still gets filtered here).
24
+
25
+ The bundle format is currently ``schema_version=1`` only; the importer
26
+ refuses anything else (forward-incompatible by design).
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ from datetime import UTC, datetime
33
+ from pathlib import Path
34
+ from typing import Any, Literal
35
+ from uuid import UUID
36
+
37
+ from pydantic import BaseModel, ConfigDict, Field
38
+
39
+ from engram.models.frontmatter import Portability
40
+
41
+ #: Per-file size ceiling enforced at both export and import sides.
42
+ MAX_PER_FILE_BYTES: int = 1 * 1024 * 1024 # 1 MB
43
+ #: Total bundle size ceiling. Enforced via streaming counter at import
44
+ #: side (tar header sizes are summed before extraction).
45
+ MAX_TOTAL_BYTES: int = 4 * 1024 * 1024 * 1024 # 4 GB
46
+ #: Required prefix for every member in the archive (path traversal gate).
47
+ BUNDLE_THOUGHTS_DIR: str = "thoughts"
48
+ #: Manifest filename at archive root.
49
+ BUNDLE_MANIFEST_FILENAME: str = "manifest.json"
50
+ #: Current schema version. Importer refuses anything else.
51
+ BUNDLE_SCHEMA_VERSION: int = 1
52
+
53
+
54
+ class BundleManifest(BaseModel):
55
+ """Top-level metadata for a bundle.
56
+
57
+ Stable shape for the v1 lifetime; field additions are non-breaking.
58
+ """
59
+
60
+ model_config = ConfigDict(extra="forbid")
61
+
62
+ schema_version: Literal[1] = 1
63
+ #: Logical user identifier on the export side. Used for provenance,
64
+ #: not for cycle detection (cycles are detected by ``bundle_id``
65
+ #: chain so multi-machine same-user imports work).
66
+ source_user: str = Field(min_length=1)
67
+ #: Vault name on the export side (provenance only).
68
+ source_vault: str = Field(min_length=1)
69
+ #: ISO-8601 UTC timestamp of when the bundle was created.
70
+ exported_at: datetime
71
+ thought_count: int = Field(ge=0)
72
+ portability_filter: list[Portability] = Field(
73
+ default_factory=lambda: ["portable"] # type: ignore[arg-type]
74
+ )
75
+ embedding_model: str = Field(min_length=1)
76
+ #: UUID-v7 mint at export time. The importer walks every existing
77
+ #: thought's ``source: bundle:<id>`` chain looking for this id; if
78
+ #: present, it's a cycle and the bundle is refused.
79
+ bundle_id: UUID
80
+
81
+ @property
82
+ def bundle_source_tag(self) -> str:
83
+ """Return the ``source:`` value imported thoughts inherit."""
84
+ return f"bundle:{self.bundle_id}"
85
+
86
+ def to_json(self) -> str:
87
+ """Render to a stable JSON string for the on-disk manifest."""
88
+ # mode="json" emits ISO timestamps + UUIDs as strings.
89
+ payload: dict[str, Any] = self.model_dump(mode="json")
90
+ return json.dumps(payload, indent=2, sort_keys=True)
91
+
92
+ @classmethod
93
+ def from_json(cls, raw: str) -> BundleManifest:
94
+ """Parse a JSON manifest blob; raises ValidationError on bad input."""
95
+ data = json.loads(raw)
96
+ if not isinstance(data, dict):
97
+ msg = f"manifest.json must be a JSON object, got {type(data).__name__}"
98
+ raise TypeError(msg)
99
+ return cls.model_validate(data)
100
+
101
+
102
+ def manifest_path(extracted_root: Path) -> Path:
103
+ """Return the path to ``manifest.json`` under an extracted bundle root."""
104
+ return extracted_root / BUNDLE_MANIFEST_FILENAME
105
+
106
+
107
+ def now_utc() -> datetime:
108
+ """Wall-clock now, UTC. Test seam."""
109
+ return datetime.now(UTC)