keepm 0.2.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.
keepm/storage.py ADDED
@@ -0,0 +1,66 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import time
5
+ from pathlib import Path
6
+
7
+ from keepm.config import KeepMConfig
8
+
9
+
10
+ class MemoryStorage:
11
+ def __init__(self, config: KeepMConfig) -> None:
12
+ self.config = config
13
+
14
+ def require_safe_path(self, path: Path) -> Path:
15
+ resolved = path.expanduser().resolve()
16
+ root = self.config.memory_root.resolve()
17
+ if resolved == root or not resolved.is_relative_to(root):
18
+ raise ValueError(f"path is outside Memory root: {path}")
19
+ return resolved
20
+
21
+ def path_for(self, *, scope: str, filename: str) -> Path:
22
+ if Path(filename).name != filename or not filename.endswith(".md"):
23
+ raise ValueError("filename must be a Markdown basename")
24
+ root = (
25
+ self.config.global_root
26
+ if scope == "global"
27
+ else self.config.projects_root / scope
28
+ )
29
+ root.mkdir(parents=True, exist_ok=True)
30
+ return self.require_safe_path(root / filename)
31
+
32
+ def discover(self) -> tuple[Path, ...]:
33
+ if not self.config.memory_root.exists():
34
+ return ()
35
+ paths: set[Path] = set()
36
+ for path in self.config.memory_root.rglob("*.md"):
37
+ relative = path.relative_to(self.config.memory_root)
38
+ if any(part.startswith(".") for part in relative.parts):
39
+ continue
40
+ try:
41
+ paths.add(self.require_safe_path(path))
42
+ except ValueError:
43
+ continue
44
+ return tuple(sorted(paths))
45
+
46
+ def atomic_write(self, path: Path, content: str) -> Path:
47
+ target = self.require_safe_path(path)
48
+ target.parent.mkdir(parents=True, exist_ok=True)
49
+ temporary = target.with_name(f".{target.name}.{os.getpid()}.tmp")
50
+ try:
51
+ with temporary.open("w", encoding="utf-8", newline="\n") as handle:
52
+ handle.write(content)
53
+ handle.flush()
54
+ os.fsync(handle.fileno())
55
+ os.replace(temporary, target)
56
+ finally:
57
+ temporary.unlink(missing_ok=True)
58
+ return target
59
+
60
+ def soft_delete(self, path: Path) -> Path:
61
+ source = self.require_safe_path(path)
62
+ stamp = time.strftime("%Y%m%d-%H%M%S")
63
+ destination = self.config.trash_root / f"{stamp}-{time.time_ns()}-{source.name}"
64
+ destination.parent.mkdir(parents=True, exist_ok=True)
65
+ os.replace(source, destination)
66
+ return destination
keepm/sync.py ADDED
@@ -0,0 +1,230 @@
1
+ from __future__ import annotations
2
+
3
+ import datetime as dt
4
+ import hashlib
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+
8
+ from keepm.database import FileState, MemoryDatabase
9
+ from keepm.markdown import parse_memory
10
+ from keepm.models import MemoryDocument, SyncReport
11
+ from keepm.storage import MemoryStorage
12
+
13
+
14
+ def sha256_file(path: Path) -> str:
15
+ digest = hashlib.sha256()
16
+ with path.open("rb") as handle:
17
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
18
+ digest.update(chunk)
19
+ return digest.hexdigest()
20
+
21
+
22
+ def file_metadata(path: Path) -> tuple[int, int]:
23
+ stat = path.stat()
24
+ return stat.st_mtime_ns, stat.st_size
25
+
26
+
27
+ @dataclass(slots=True)
28
+ class _Counts:
29
+ new: int = 0
30
+ modified: int = 0
31
+ deleted: int = 0
32
+ moved: int = 0
33
+ unchanged: int = 0
34
+ errors: list[str] = field(default_factory=list)
35
+
36
+ def report(self) -> SyncReport:
37
+ return SyncReport(
38
+ new=self.new,
39
+ modified=self.modified,
40
+ deleted=self.deleted,
41
+ moved=self.moved,
42
+ unchanged=self.unchanged,
43
+ errors=tuple(self.errors),
44
+ )
45
+
46
+
47
+ class SyncEngine:
48
+ def __init__(self, storage: MemoryStorage, database: MemoryDatabase) -> None:
49
+ self.storage = storage
50
+ self.database = database
51
+
52
+ @property
53
+ def memory_root(self) -> Path:
54
+ return self.storage.config.memory_root.resolve()
55
+
56
+ def _expected_scope(self, path: Path) -> str:
57
+ relative = path.resolve().relative_to(self.memory_root)
58
+ if len(relative.parts) >= 2 and relative.parts[0] == "global":
59
+ return "global"
60
+ if len(relative.parts) >= 3 and relative.parts[0] == "projects":
61
+ return relative.parts[1]
62
+ raise ValueError(f"{path}: Markdown file is outside a global/project scope")
63
+
64
+ def _parse(self, path: Path) -> MemoryDocument:
65
+ document = parse_memory(path, path.read_text(encoding="utf-8"))
66
+ expected_scope = self._expected_scope(path)
67
+ if document.scope != expected_scope:
68
+ raise ValueError(
69
+ f"{path}: scope {document.scope!r} does not match directory "
70
+ f"scope {expected_scope!r}"
71
+ )
72
+ return document
73
+
74
+ def _record_error(
75
+ self,
76
+ path: Path,
77
+ error: Exception,
78
+ *,
79
+ mtime_ns: int,
80
+ size: int,
81
+ counts: _Counts,
82
+ ) -> None:
83
+ message = str(error)
84
+ self.database.mark_error(path, message, mtime_ns=mtime_ns, size=size)
85
+ counts.errors.append(message)
86
+
87
+ def _reconcile_existing(
88
+ self,
89
+ path: Path,
90
+ *,
91
+ state: FileState | None,
92
+ states_by_id: dict[str, FileState],
93
+ known_files: set[Path],
94
+ error_state: tuple[int, int] | None,
95
+ counts: _Counts,
96
+ moved_from: set[Path],
97
+ ) -> None:
98
+ try:
99
+ mtime_ns, size = file_metadata(path)
100
+ except OSError as error:
101
+ counts.errors.append(f"{path}: {error}")
102
+ return
103
+
104
+ if state and (state.mtime_ns, state.size) == (mtime_ns, size):
105
+ counts.unchanged += 1
106
+ return
107
+ if error_state == (mtime_ns, size):
108
+ counts.unchanged += 1
109
+ return
110
+
111
+ try:
112
+ checksum = sha256_file(path)
113
+ except OSError as error:
114
+ self._record_error(
115
+ path, error, mtime_ns=mtime_ns, size=size, counts=counts
116
+ )
117
+ return
118
+
119
+ if state and state.checksum == checksum:
120
+ self.database.update_file_metadata(path, mtime_ns=mtime_ns, size=size)
121
+ counts.unchanged += 1
122
+ return
123
+
124
+ try:
125
+ document = self._parse(path)
126
+ prior = states_by_id.get(document.id)
127
+ if prior and prior.path != path:
128
+ if prior.path in known_files or prior.path.exists():
129
+ raise ValueError(
130
+ f"{path}: duplicate memory id {document.id!r} also exists at "
131
+ f"{prior.path}"
132
+ )
133
+ moved_from.add(prior.path)
134
+ classification = "moved"
135
+ elif state:
136
+ classification = "modified"
137
+ else:
138
+ classification = "new"
139
+ self.database.upsert(
140
+ document,
141
+ mtime_ns=mtime_ns,
142
+ size=size,
143
+ checksum=checksum,
144
+ )
145
+ except Exception as error:
146
+ self._record_error(
147
+ path, error, mtime_ns=mtime_ns, size=size, counts=counts
148
+ )
149
+ return
150
+
151
+ if classification == "moved":
152
+ counts.moved += 1
153
+ elif classification == "modified":
154
+ counts.modified += 1
155
+ else:
156
+ counts.new += 1
157
+
158
+ def _finish(self, counts: _Counts) -> SyncReport:
159
+ self.database.set_state(
160
+ "last_reconcile", dt.datetime.now(dt.timezone.utc).isoformat()
161
+ )
162
+ return counts.report()
163
+
164
+ def quick_reconcile(self) -> SyncReport:
165
+ paths = set(self.storage.discover())
166
+ states = self.database.file_states()
167
+ states_by_id = {state.id: state for state in states.values()}
168
+ error_states = self.database.index_error_states()
169
+ counts = _Counts()
170
+ moved_from: set[Path] = set()
171
+
172
+ for path in sorted(paths):
173
+ self._reconcile_existing(
174
+ path,
175
+ state=states.get(path),
176
+ states_by_id=states_by_id,
177
+ known_files=paths,
178
+ error_state=error_states.get(path),
179
+ counts=counts,
180
+ moved_from=moved_from,
181
+ )
182
+
183
+ indexed_or_error_paths = set(states) | set(error_states)
184
+ for missing in sorted(indexed_or_error_paths - paths - moved_from):
185
+ self.database.delete_path(missing)
186
+ counts.deleted += 1
187
+ return self._finish(counts)
188
+
189
+ def reconcile_paths(self, paths: tuple[Path, ...] | list[Path]) -> SyncReport:
190
+ eligible: set[Path] = set()
191
+ counts = _Counts()
192
+ for candidate in paths:
193
+ try:
194
+ path = self.storage.require_safe_path(Path(candidate))
195
+ relative = path.relative_to(self.memory_root)
196
+ except (OSError, ValueError) as error:
197
+ counts.errors.append(str(error))
198
+ continue
199
+ if (
200
+ path.suffix.lower() != ".md"
201
+ or any(part.startswith(".") for part in relative.parts)
202
+ or path.name.startswith(".")
203
+ or path.name.endswith((".tmp", "~"))
204
+ ):
205
+ continue
206
+ eligible.add(path)
207
+
208
+ states = self.database.file_states()
209
+ states_by_id = {state.id: state for state in states.values()}
210
+ error_states = self.database.index_error_states()
211
+ existing = {path for path in eligible if path.is_file()}
212
+ moved_from: set[Path] = set()
213
+ for path in sorted(existing):
214
+ self._reconcile_existing(
215
+ path,
216
+ state=states.get(path),
217
+ states_by_id=states_by_id,
218
+ known_files=existing,
219
+ error_state=error_states.get(path),
220
+ counts=counts,
221
+ moved_from=moved_from,
222
+ )
223
+ for missing in sorted(eligible - existing - moved_from):
224
+ if self.database.delete_path(missing) or missing in error_states:
225
+ counts.deleted += 1
226
+ return self._finish(counts)
227
+
228
+ def full_rebuild(self) -> SyncReport:
229
+ self.database.clear()
230
+ return self.quick_reconcile()
keepm/watcher.py ADDED
@@ -0,0 +1,113 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import contextlib
5
+ from collections.abc import AsyncIterator, Callable, Iterable
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from keepm.config import KeepMConfig
10
+ from keepm.sync import SyncEngine
11
+
12
+ try:
13
+ from watchfiles import awatch as _awatch
14
+ except ImportError: # Covered by runtime diagnostics when dependencies are absent.
15
+ _awatch = None
16
+
17
+
18
+ def filter_watch_paths(root: Path, paths: Iterable[Path]) -> tuple[Path, ...]:
19
+ resolved_root = root.expanduser().resolve()
20
+ accepted: set[Path] = set()
21
+ for candidate in paths:
22
+ resolved = Path(candidate).expanduser().resolve()
23
+ if resolved == resolved_root or not resolved.is_relative_to(resolved_root):
24
+ continue
25
+ relative = resolved.relative_to(resolved_root)
26
+ if any(part.startswith(".") for part in relative.parts):
27
+ continue
28
+ if resolved.suffix.lower() != ".md":
29
+ continue
30
+ if resolved.name.endswith(("~", ".tmp", ".swp", ".swx")):
31
+ continue
32
+ accepted.add(resolved)
33
+ return tuple(sorted(accepted))
34
+
35
+
36
+ ChangeSource = Callable[..., AsyncIterator[set[tuple[Any, str]]]]
37
+
38
+
39
+ class WatcherService:
40
+ def __init__(
41
+ self,
42
+ config: KeepMConfig,
43
+ sync_engine: SyncEngine,
44
+ *,
45
+ change_source: ChangeSource | None = None,
46
+ ) -> None:
47
+ self.config = config
48
+ self.sync_engine = sync_engine
49
+ self._change_source = change_source
50
+ self._stop_event = asyncio.Event()
51
+ self._task: asyncio.Task[None] | None = None
52
+ self.last_error: str | None = None
53
+
54
+ @property
55
+ def running(self) -> bool:
56
+ return self._task is not None and not self._task.done()
57
+
58
+ async def _changes(self) -> AsyncIterator[set[tuple[Any, str]]]:
59
+ if self._change_source is not None:
60
+ async for changes in self._change_source(
61
+ self.config.memory_root,
62
+ debounce=250,
63
+ step=50,
64
+ stop_event=self._stop_event,
65
+ ):
66
+ yield changes
67
+ return
68
+ if _awatch is None:
69
+ raise RuntimeError(
70
+ "watchfiles is not installed; reconciliation remains available"
71
+ )
72
+ async for changes in _awatch(
73
+ self.config.memory_root,
74
+ debounce=250,
75
+ step=50,
76
+ stop_event=self._stop_event,
77
+ ):
78
+ yield changes
79
+
80
+ async def _run(self) -> None:
81
+ try:
82
+ async for changes in self._changes():
83
+ paths = filter_watch_paths(
84
+ self.config.memory_root,
85
+ (Path(raw_path) for _, raw_path in changes),
86
+ )
87
+ if paths:
88
+ self.sync_engine.reconcile_paths(paths)
89
+ except asyncio.CancelledError:
90
+ raise
91
+ except Exception as error:
92
+ self.last_error = str(error)
93
+
94
+ async def start(self) -> None:
95
+ if self.running:
96
+ return
97
+ self.last_error = None
98
+ self._stop_event = asyncio.Event()
99
+ self._task = asyncio.create_task(self._run(), name="keepm-watcher")
100
+
101
+ async def stop(self) -> None:
102
+ task = self._task
103
+ if task is None:
104
+ return
105
+ self._stop_event.set()
106
+ try:
107
+ await asyncio.wait_for(asyncio.shield(task), timeout=2.0)
108
+ except TimeoutError:
109
+ task.cancel()
110
+ with contextlib.suppress(asyncio.CancelledError):
111
+ await task
112
+ finally:
113
+ self._task = None
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: keepm
3
+ Version: 0.2.0
4
+ Summary: Local Markdown memory MCP for coding agents
5
+ Requires-Python: >=3.11
6
+ License-File: LICENSE
7
+ Requires-Dist: fastmcp<4,>=3
8
+ Requires-Dist: PyYAML<7,>=6
9
+ Requires-Dist: questionary<3,>=2
10
+ Requires-Dist: tomlkit<1,>=0.13
11
+ Requires-Dist: watchfiles<2,>=1
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest<9,>=8; extra == "dev"
14
+ Requires-Dist: pytest-asyncio<2,>=0.24; extra == "dev"
15
+ Dynamic: license-file
@@ -0,0 +1,22 @@
1
+ keepm/__init__.py,sha256=Zn1KFblwuFHiDRdRAiRnDBRkbPttWh44jKa5zG2ov0E,22
2
+ keepm/cli.py,sha256=50lCYJkHHauP9qVXx83bezwDeox7jckg2W4eB8A0YPs,490
3
+ keepm/config.py,sha256=N-1WjdZ6XJ4seJWiQjMBpjKl7vxCJTPgt4eQUvFWdAA,3268
4
+ keepm/database.py,sha256=hwUezvajqc_ZIetsGM6EjRtlhy3uLwVw9uHiqNiv4ns,21529
5
+ keepm/doctor.py,sha256=s7gqcN0aVEhu7HwFbCiM8uG8ofNGKPC8cYzAotS5QcA,4631
6
+ keepm/instructions.py,sha256=VEk_5gMiSjvS7pig0b7y9MmaI2xEXq6vWg7avKPx-JY,10124
7
+ keepm/integrations.py,sha256=QKAaAnAogW2sp6WGBx9I1xk8ZiJ5M1ZcbRvcSqmxLgg,10341
8
+ keepm/markdown.py,sha256=ZeBAETPoT1z3EtsZ-cG2-6qshU_7DrLriO3YpH1vP1Q,5177
9
+ keepm/models.py,sha256=UAAstgvHyruvF8WYx9qbyW7u93v_iUbhjj1Ry8394nE,911
10
+ keepm/projects.py,sha256=vJtehpw5ri-f0AMcCCS7c9r0aV1A0Ufv00crbM7RTxk,1858
11
+ keepm/server.py,sha256=A5aEjObKxl9mewmURSLj_t0cCZWi-ZAz1FJd8f9knQA,16320
12
+ keepm/service.py,sha256=qLJTlnv6Ams-1YA6l27dCIRvpyEQ2sHLL0HTozH0Gt8,11109
13
+ keepm/setup.py,sha256=9J6CTCpXx66_cUTYgQkn2nyMrYMbHZxJ19TnSLb1ooE,14910
14
+ keepm/storage.py,sha256=KZWotca2dE7iZJHJucm1Pio7s0Mvn6u4SA9upmVZnq8,2455
15
+ keepm/sync.py,sha256=JXgooFx6Sv1Z35t5iK02T1uSew8YO_OJ63LgMmFkX-8,7664
16
+ keepm/watcher.py,sha256=soGdL-FHCAqlR1QQPRtsChbBjgc9GF0Ak_K7gWdexzY,3597
17
+ keepm-0.2.0.dist-info/licenses/LICENSE,sha256=vmAY006NBQjCY34U3ZOt5kdawMHzWV2_pORX6iT1sRc,1093
18
+ keepm-0.2.0.dist-info/METADATA,sha256=bmG8sF2nw9xqScsQ5EUKxQad8G7hRKe8mJGpUTeDIwg,443
19
+ keepm-0.2.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
20
+ keepm-0.2.0.dist-info/entry_points.txt,sha256=zwJJeT9R8SlRRrNTj5Bla0osXjSw9ssQksITc4idbRs,41
21
+ keepm-0.2.0.dist-info/top_level.txt,sha256=aPACTlmnIV7jjD0wNea34jEJCdT6WDHMPeHgSTfVmGc,6
22
+ keepm-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ keepm = keepm.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Beijing Tinqiao Technology Co., Ltd.
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.
@@ -0,0 +1 @@
1
+ keepm