mipmem 1.0.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.
mipmem/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """MipMem — Zero-Dependency 4-Layer Mipmapped Cognitive Memory Engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = ["__version__"]
6
+ __version__ = "1.0.0"
mipmem/__main__.py ADDED
@@ -0,0 +1,17 @@
1
+ """Module entrypoint for `python3 -m mipmem` and `.pyz` zipapp execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import time
7
+
8
+
9
+ def _bootstrap() -> int:
10
+ boot_started = time.perf_counter()
11
+ from mipmem.cli import main
12
+
13
+ return main(sys.argv[1:], boot_started=boot_started)
14
+
15
+
16
+ if __name__ == "__main__":
17
+ raise SystemExit(_bootstrap())
@@ -0,0 +1 @@
1
+ """Agent-surface transcript, hook, slash-command, and plugin adapters for MipMem."""
@@ -0,0 +1,437 @@
1
+ """Read-only Antigravity CLI SQLite transcript harvester with JSONL fallback."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ import json
7
+ from pathlib import Path
8
+ import sqlite3
9
+ import time
10
+ from typing import Any, Optional, Union
11
+ from urllib.parse import quote, unquote
12
+
13
+ from mipmem.adapters.base import NormalizedConversation
14
+ from mipmem.core.diagnostics import (
15
+ ADAPTER_READ_FAILED,
16
+ CP_ADP_01,
17
+ RotatingJsonLogger,
18
+ )
19
+
20
+ _MAX_RECENT_PROMPTS = 10
21
+ _MAX_PROMPT_CHARS = 500
22
+ _MAX_RESPONSE_CHARS = 2000
23
+
24
+
25
+ def _discover_cli_db_path(transcript_path: Optional[Union[str, Path]]) -> Optional[Path]:
26
+ """Walk up from a CLI transcript path to locate conversation_summaries.db."""
27
+ if transcript_path is None:
28
+ return None
29
+ raw = str(transcript_path).strip()
30
+ if not raw:
31
+ return None
32
+ current = Path(raw).expanduser()
33
+ parent = current if current.is_dir() else current.parent
34
+ for _ in range(6):
35
+ candidate = parent / "conversation_summaries.db"
36
+ if candidate.is_file():
37
+ return candidate
38
+ if parent.parent == parent:
39
+ break
40
+ parent = parent.parent
41
+ return None
42
+
43
+
44
+ def _normalize_timestamp(raw: Any) -> str:
45
+ """Convert string ISO or numeric epoch timestamps into ISO-8601 UTC Z format."""
46
+ if raw is None:
47
+ return ""
48
+ if isinstance(raw, (int, float)) and not isinstance(raw, bool):
49
+ value = float(raw)
50
+ if value <= 0:
51
+ return ""
52
+ if value > 1e12:
53
+ value /= 1000.0
54
+ dt = datetime.fromtimestamp(value, tz=timezone.utc)
55
+ ms = dt.microsecond // 1000
56
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{ms:03d}Z"
57
+ text = str(raw).strip()
58
+ if not text:
59
+ return ""
60
+ if text.isdigit():
61
+ return _normalize_timestamp(int(text))
62
+ return text
63
+
64
+
65
+ def _parse_workspace_uris(raw: Any) -> list[str]:
66
+ """Decode JSON array or delimited workspace_uris into clean filesystem paths."""
67
+ if raw is None:
68
+ return []
69
+ candidates: list[Any]
70
+ if isinstance(raw, list):
71
+ candidates = raw
72
+ elif isinstance(raw, str):
73
+ stripped = raw.strip()
74
+ if not stripped:
75
+ return []
76
+ if stripped.startswith("["):
77
+ try:
78
+ decoded = json.loads(stripped)
79
+ candidates = decoded if isinstance(decoded, list) else [stripped]
80
+ except json.JSONDecodeError:
81
+ candidates = [part for part in stripped.replace("\n", ",").split(",")]
82
+ else:
83
+ candidates = [part for part in stripped.replace("\n", ",").split(",")]
84
+ else:
85
+ return []
86
+
87
+ paths: list[str] = []
88
+ seen: set[str] = set()
89
+ for item in candidates:
90
+ text = str(item).strip()
91
+ if not text:
92
+ continue
93
+ if text.startswith("file://"):
94
+ text = unquote(text[7:])
95
+ if text and text not in seen:
96
+ seen.add(text)
97
+ paths.append(text)
98
+ return paths
99
+
100
+
101
+ def _collect_lines(chunks: list[str], *, limit: int) -> list[str]:
102
+ """Extract deduplicated non-empty lines from FTS user_body chunks."""
103
+ items: list[str] = []
104
+ seen: set[str] = set()
105
+ for chunk in chunks:
106
+ for raw_line in chunk.splitlines():
107
+ cleaned = raw_line.strip()
108
+ if not cleaned or cleaned in seen:
109
+ continue
110
+ seen.add(cleaned)
111
+ items.append(cleaned[:_MAX_PROMPT_CHARS])
112
+ if len(items) > limit:
113
+ return items[-limit:]
114
+ return items
115
+
116
+
117
+ def _safe_int(raw: Any, default: int = 0) -> int:
118
+ """Convert SQLite column values safely into non-negative integers."""
119
+ if isinstance(raw, bool) or raw is None:
120
+ return default
121
+ if isinstance(raw, int):
122
+ return max(0, raw)
123
+ try:
124
+ return max(0, int(str(raw).strip()))
125
+ except ValueError:
126
+ return default
127
+
128
+
129
+ def _row_get(row: sqlite3.Row, key: str, default: Any = None) -> Any:
130
+ """Safely read an optional column from a sqlite3.Row."""
131
+ keys = row.keys()
132
+ if key in keys:
133
+ return row[key]
134
+ return default
135
+
136
+
137
+ def _log_adapter_event(
138
+ logger: Optional[RotatingJsonLogger],
139
+ *,
140
+ level: str,
141
+ conversation_id: str,
142
+ source_kind: str,
143
+ step_count: int = 0,
144
+ skipped_reason: Optional[str] = None,
145
+ error_code: Optional[str] = None,
146
+ duration_ms: float = 0.0,
147
+ ) -> None:
148
+ """Emit structured CP-ADP-01 diagnostics event without raw transcript text."""
149
+ if logger is None:
150
+ return
151
+ logger.log_event(
152
+ level,
153
+ "adapters",
154
+ CP_ADP_01,
155
+ error_code=error_code,
156
+ duration_ms=duration_ms,
157
+ details={
158
+ "surface": "cli",
159
+ "source_kind": source_kind,
160
+ "conversation_id": conversation_id,
161
+ "step_count": step_count,
162
+ "expanded_truncated_steps": 0,
163
+ "skipped_reason": skipped_reason,
164
+ },
165
+ )
166
+
167
+
168
+ def _extract_jsonl_fallback(
169
+ transcript_path: Union[str, Path],
170
+ conversation_id: str,
171
+ *,
172
+ logger: Optional[RotatingJsonLogger] = None,
173
+ ) -> Optional[NormalizedConversation]:
174
+ """Parse a CLI JSONL transcript file when SQLite summary is unavailable."""
175
+ start = time.perf_counter()
176
+ path = Path(transcript_path).expanduser()
177
+ if not path.is_file():
178
+ return None
179
+
180
+ prompts: list[str] = []
181
+ last_response = ""
182
+ step_count = 0
183
+ title = ""
184
+ last_modified = ""
185
+
186
+ try:
187
+ with open(path, "r", encoding="utf-8", errors="replace") as handle:
188
+ for raw_line in handle:
189
+ stripped = raw_line.strip()
190
+ if not stripped:
191
+ continue
192
+ try:
193
+ entry = json.loads(stripped)
194
+ except json.JSONDecodeError:
195
+ continue
196
+ if not isinstance(entry, dict):
197
+ continue
198
+ step_count += 1
199
+ parent_id = str(entry.get("parent_conversation_id") or "").strip()
200
+ nesting_depth = _safe_int(entry.get("nesting_depth"), default=0)
201
+ if nesting_depth > 0 or parent_id:
202
+ _log_adapter_event(
203
+ logger,
204
+ level="INFO",
205
+ conversation_id=conversation_id,
206
+ source_kind="jsonl",
207
+ step_count=step_count,
208
+ skipped_reason="subagent",
209
+ duration_ms=(time.perf_counter() - start) * 1000.0,
210
+ )
211
+ return None
212
+
213
+ ts = _normalize_timestamp(entry.get("timestamp") or entry.get("last_modified_time"))
214
+ if ts:
215
+ last_modified = ts
216
+ if not title and isinstance(entry.get("title"), str) and entry["title"].strip():
217
+ title = entry["title"].strip()
218
+
219
+ entry_type = str(entry.get("type") or "").upper()
220
+ role = str(entry.get("role") or "").lower()
221
+ if entry_type == "USER_INPUT" or role == "user":
222
+ text = str(
223
+ entry.get("text") or entry.get("content") or entry.get("message") or ""
224
+ ).strip()
225
+ if text:
226
+ prompts.append(text[:_MAX_PROMPT_CHARS])
227
+ elif entry_type == "PLANNER_RESPONSE" or role in ("assistant", "model"):
228
+ resp = str(
229
+ entry.get("response") or entry.get("text") or entry.get("content") or ""
230
+ ).strip()
231
+ if resp:
232
+ last_response = resp[:_MAX_RESPONSE_CHARS]
233
+ except OSError:
234
+ _log_adapter_event(
235
+ logger,
236
+ level="WARN",
237
+ conversation_id=conversation_id,
238
+ source_kind="jsonl",
239
+ skipped_reason="read_failed",
240
+ error_code=ADAPTER_READ_FAILED,
241
+ duration_ms=(time.perf_counter() - start) * 1000.0,
242
+ )
243
+ return None
244
+
245
+ if step_count == 0:
246
+ _log_adapter_event(
247
+ logger,
248
+ level="INFO",
249
+ conversation_id=conversation_id,
250
+ source_kind="jsonl",
251
+ skipped_reason="empty_transcript",
252
+ duration_ms=(time.perf_counter() - start) * 1000.0,
253
+ )
254
+ return None
255
+
256
+ if not last_modified:
257
+ try:
258
+ last_modified = _normalize_timestamp(path.stat().st_mtime)
259
+ except OSError:
260
+ last_modified = ""
261
+
262
+ resolved_title = title or (prompts[0][:120] if prompts else conversation_id)
263
+ conv = NormalizedConversation(
264
+ conversation_id=conversation_id,
265
+ surface="cli",
266
+ source_kind="jsonl",
267
+ title=resolved_title,
268
+ step_count=step_count,
269
+ last_modified_time=last_modified,
270
+ recent_prompts=prompts[-_MAX_RECENT_PROMPTS:],
271
+ last_agent_response=last_response,
272
+ )
273
+ _log_adapter_event(
274
+ logger,
275
+ level="INFO",
276
+ conversation_id=conversation_id,
277
+ source_kind="jsonl",
278
+ step_count=step_count,
279
+ skipped_reason=None,
280
+ duration_ms=(time.perf_counter() - start) * 1000.0,
281
+ )
282
+ return conv
283
+
284
+
285
+ # @para-doc [#csa-adapter-agy-cli-harvester]
286
+ def extract_cli_conversation(
287
+ conversation_id: str,
288
+ *,
289
+ db_path: Optional[Union[str, Path]] = None,
290
+ transcript_path: Optional[Union[str, Path]] = None,
291
+ logger: Optional[RotatingJsonLogger] = None,
292
+ ) -> Optional[NormalizedConversation]:
293
+ """Extract an Antigravity CLI conversation from read-only SQLite or JSONL fallback."""
294
+ start = time.perf_counter()
295
+ conv_id = conversation_id.strip()
296
+ if not conv_id:
297
+ return None
298
+
299
+ resolved_db: Optional[Path]
300
+ if db_path is not None:
301
+ resolved_db = Path(db_path).expanduser()
302
+ else:
303
+ resolved_db = _discover_cli_db_path(transcript_path)
304
+
305
+ sqlite_attempted = False
306
+ if resolved_db is not None and resolved_db.is_file():
307
+ sqlite_attempted = True
308
+ uri = f"file:{quote(str(resolved_db.resolve()), safe='/:')}?mode=ro"
309
+ conn: Optional[sqlite3.Connection] = None
310
+ try:
311
+ conn = sqlite3.connect(uri, uri=True, timeout=2.0)
312
+ conn.row_factory = sqlite3.Row
313
+ row = conn.execute(
314
+ "SELECT * FROM conversation_summaries WHERE conversation_id = ?",
315
+ (conv_id,),
316
+ ).fetchone()
317
+ if row is not None:
318
+ parent_id = str(_row_get(row, "parent_conversation_id", "") or "").strip()
319
+ nesting_depth = _safe_int(_row_get(row, "nesting_depth", 0), default=0)
320
+ if nesting_depth > 0 or parent_id:
321
+ _log_adapter_event(
322
+ logger,
323
+ level="INFO",
324
+ conversation_id=conv_id,
325
+ source_kind="sqlite",
326
+ step_count=_safe_int(_row_get(row, "step_count", 0)),
327
+ skipped_reason="subagent",
328
+ duration_ms=(time.perf_counter() - start) * 1000.0,
329
+ )
330
+ return None
331
+
332
+ user_chunks: list[str] = []
333
+ agent_chunks: list[str] = []
334
+ has_fts = (
335
+ conn.execute(
336
+ "SELECT 1 FROM sqlite_master WHERE name = 'conversations_fts'"
337
+ ).fetchone()
338
+ is not None
339
+ )
340
+ if has_fts:
341
+ fts_rows = conn.execute(
342
+ "SELECT user_body, agent_body FROM conversations_fts "
343
+ "WHERE conversation_id = ? ORDER BY chunk_index ASC",
344
+ (conv_id,),
345
+ ).fetchall()
346
+ for fts_row in fts_rows:
347
+ user_body = str(_row_get(fts_row, "user_body", "") or "").strip()
348
+ agent_body = str(_row_get(fts_row, "agent_body", "") or "").strip()
349
+ if user_body:
350
+ user_chunks.append(user_body)
351
+ if agent_body:
352
+ agent_chunks.append(agent_body)
353
+
354
+ title = str(_row_get(row, "title", "") or "").strip() or conv_id
355
+ preview = str(_row_get(row, "preview", "") or "").strip()
356
+ step_count = _safe_int(_row_get(row, "step_count", 0))
357
+ last_modified = _normalize_timestamp(_row_get(row, "last_modified_time", ""))
358
+ workspace_paths = _parse_workspace_uris(_row_get(row, "workspace_uris", ""))
359
+ recent_prompts = _collect_lines(user_chunks, limit=_MAX_RECENT_PROMPTS)
360
+ last_agent_response = (
361
+ agent_chunks[-1][:_MAX_RESPONSE_CHARS]
362
+ if agent_chunks
363
+ else preview[:_MAX_RESPONSE_CHARS]
364
+ )
365
+
366
+ conv = NormalizedConversation(
367
+ conversation_id=conv_id,
368
+ surface="cli",
369
+ source_kind="sqlite",
370
+ title=title,
371
+ step_count=step_count,
372
+ last_modified_time=last_modified,
373
+ workspace_paths=workspace_paths,
374
+ recent_prompts=recent_prompts,
375
+ last_agent_response=last_agent_response,
376
+ )
377
+ _log_adapter_event(
378
+ logger,
379
+ level="INFO",
380
+ conversation_id=conv_id,
381
+ source_kind="sqlite",
382
+ step_count=step_count,
383
+ skipped_reason=None,
384
+ duration_ms=(time.perf_counter() - start) * 1000.0,
385
+ )
386
+ return conv
387
+ except (sqlite3.Error, OSError):
388
+ _log_adapter_event(
389
+ logger,
390
+ level="WARN",
391
+ conversation_id=conv_id,
392
+ source_kind="sqlite",
393
+ skipped_reason="read_failed",
394
+ error_code=ADAPTER_READ_FAILED,
395
+ duration_ms=(time.perf_counter() - start) * 1000.0,
396
+ )
397
+ finally:
398
+ if conn is not None:
399
+ conn.close()
400
+
401
+ if transcript_path is not None:
402
+ fallback = _extract_jsonl_fallback(transcript_path, conv_id, logger=logger)
403
+ if fallback is not None:
404
+ return fallback
405
+
406
+ if sqlite_attempted or resolved_db is not None:
407
+ _log_adapter_event(
408
+ logger,
409
+ level="INFO",
410
+ conversation_id=conv_id,
411
+ source_kind="sqlite",
412
+ skipped_reason="not_found",
413
+ duration_ms=(time.perf_counter() - start) * 1000.0,
414
+ )
415
+ return None
416
+
417
+
418
+ class AntigravityCliAdapter:
419
+ """TranscriptAdapter implementation targeting Antigravity CLI SQLite stores."""
420
+
421
+ surface: str = "cli"
422
+
423
+ def extract(
424
+ self,
425
+ *,
426
+ conversation_id: str,
427
+ transcript_path: Optional[Union[str, Path]] = None,
428
+ db_path: Optional[Union[str, Path]] = None,
429
+ logger: Optional[RotatingJsonLogger] = None,
430
+ ) -> Optional[NormalizedConversation]:
431
+ """Extract a normalized CLI conversation via read-only SQLite or JSONL fallback."""
432
+ return extract_cli_conversation(
433
+ conversation_id,
434
+ db_path=db_path,
435
+ transcript_path=transcript_path,
436
+ logger=logger,
437
+ )