tortoise-graph 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.
Files changed (93) hide show
  1. tortoise/__init__.py +45 -0
  2. tortoise/__main__.py +1865 -0
  3. tortoise/analyze.py +473 -0
  4. tortoise/api.py +303 -0
  5. tortoise/archived/search_legacy.py +31 -0
  6. tortoise/audit.py +236 -0
  7. tortoise/audit_events.py +284 -0
  8. tortoise/auth.py +107 -0
  9. tortoise/backup.py +155 -0
  10. tortoise/config.py +99 -0
  11. tortoise/connector_loader.py +74 -0
  12. tortoise/connectors/__init__.py +5 -0
  13. tortoise/connectors/github.py +432 -0
  14. tortoise/connectors/github_docs.py +146 -0
  15. tortoise/connectors/linear.py +199 -0
  16. tortoise/connectors/slack.py +222 -0
  17. tortoise/consistency.py +132 -0
  18. tortoise/crypto.py +52 -0
  19. tortoise/deployment.py +62 -0
  20. tortoise/domain_loader.py +142 -0
  21. tortoise/dream.py +153 -0
  22. tortoise/embedded_reaper.py +744 -0
  23. tortoise/embeddings.py +227 -0
  24. tortoise/ep.py +534 -0
  25. tortoise/exceptions.py +16 -0
  26. tortoise/extractor.py +945 -0
  27. tortoise/hosted_api.py +1982 -0
  28. tortoise/hosted_middleware.py +22 -0
  29. tortoise/idempotency.py +39 -0
  30. tortoise/ids.py +23 -0
  31. tortoise/indexer/github_indexer.py +129 -0
  32. tortoise/ingest.py +614 -0
  33. tortoise/log.py +29 -0
  34. tortoise/m0.py +50 -0
  35. tortoise/mcp_auth.py +337 -0
  36. tortoise/mcp_client.py +108 -0
  37. tortoise/mcp_server.py +1356 -0
  38. tortoise/memory_orchestrator.py +492 -0
  39. tortoise/memory_scope.py +15 -0
  40. tortoise/migrate_db.py +244 -0
  41. tortoise/migrate_kinds.py +141 -0
  42. tortoise/mining.py +338 -0
  43. tortoise/models.py +109 -0
  44. tortoise/monitoring.py +133 -0
  45. tortoise/navigation.py +216 -0
  46. tortoise/pack_registry.py +767 -0
  47. tortoise/pipeline_cli.py +197 -0
  48. tortoise/projection/__init__.py +913 -0
  49. tortoise/projection/edges.py +311 -0
  50. tortoise/projection/entities.py +521 -0
  51. tortoise/projection/grounding.py +95 -0
  52. tortoise/projection/propagation.py +114 -0
  53. tortoise/projection.py +37 -0
  54. tortoise/quadrature.py +90 -0
  55. tortoise/query_suggestions.py +194 -0
  56. tortoise/quota.py +163 -0
  57. tortoise/ranking.py +280 -0
  58. tortoise/render.py +108 -0
  59. tortoise/scripts/manifest.py +67 -0
  60. tortoise/sdk.py +4713 -0
  61. tortoise/search_engine.py +887 -0
  62. tortoise/security.py +268 -0
  63. tortoise/selfhost.py +157 -0
  64. tortoise/selfhost_api.py +201 -0
  65. tortoise/session_continuity.py +82 -0
  66. tortoise/session_indexer.py +569 -0
  67. tortoise/shared_state/__init__.py +20 -0
  68. tortoise/shared_state/concurrency.py +113 -0
  69. tortoise/shared_state/event_log.py +192 -0
  70. tortoise/shared_state/events.py +150 -0
  71. tortoise/shared_state/monitoring.py +87 -0
  72. tortoise/shared_state/recovery.py +126 -0
  73. tortoise/shared_state/tests/__init__.py +15 -0
  74. tortoise/shared_state/tests/test_concurrency.py +123 -0
  75. tortoise/shared_state/tests/test_events.py +145 -0
  76. tortoise/shared_state/tests/test_monitoring.py +54 -0
  77. tortoise/shared_state/tests/test_recovery.py +181 -0
  78. tortoise/source_credibility.py +306 -0
  79. tortoise/svbp.py +446 -0
  80. tortoise/taxonomy.py +71 -0
  81. tortoise/test_cross_ontology.py +180 -0
  82. tortoise/test_tortoise_client.py +206 -0
  83. tortoise/tool_registry.py +805 -0
  84. tortoise/tortoise_client.py +262 -0
  85. tortoise/verify_ontology.py +154 -0
  86. tortoise/version_vector.py +97 -0
  87. tortoise/weights.py +61 -0
  88. tortoise_graph-0.2.0.dist-info/METADATA +152 -0
  89. tortoise_graph-0.2.0.dist-info/RECORD +93 -0
  90. tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
  91. tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
  92. tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
  93. tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,82 @@
1
+ """Session continuity — vibecoder wedge prototype.
2
+ Auto-capture findings during a session, auto-retrieve on next session start.
3
+ Zero config. The agent IS the interface."""
4
+ from tortoise.sdk import TortoiseSDK
5
+ from datetime import datetime
6
+
7
+ class SessionContinuity:
8
+ """Wraps a session with auto-capture and auto-retrieve."""
9
+
10
+ def __init__(self, db_path: str | None = None):
11
+ self.sdk = TortoiseSDK(db_path)
12
+ self.session_id = None
13
+ self.findings = []
14
+
15
+ def start(self, topic="General"):
16
+ """Called at session start. Returns context from prior sessions."""
17
+ self.session_id = datetime.now().strftime("session-%Y%m%d-%H%M%S")
18
+
19
+ # Find recent context (context-based query removed #49 Phase 2)
20
+ prior = self.sdk.query(kind="observation")
21
+
22
+ summary = []
23
+ # Get last 5 findings from any session
24
+ if prior:
25
+ summary = [p.get("content", "")[:120] for p in prior[-5:]]
26
+
27
+ print(f"Session: {self.session_id}")
28
+ print(f"Topic: {topic}")
29
+ if summary:
30
+ print("\nFrom your last session:")
31
+ for s in summary:
32
+ print(f" - {s}...")
33
+ else:
34
+ print("\nNo prior context found.")
35
+ print()
36
+ return self.session_id
37
+
38
+ def capture(self, content, kind="observation", **props):
39
+ """Capture a finding during the session."""
40
+ # P1 #49: use session_id property instead of deprecated context
41
+ point = self.sdk.create_point(kind, content,
42
+ session_id=self.session_id,
43
+ captured_at=datetime.now().isoformat(),
44
+ **props)
45
+ self.findings.append(point)
46
+ return point
47
+
48
+ def end(self):
49
+ """Called at session end. Persists findings and runs confidence."""
50
+ if self.findings:
51
+ print(f"\nCaptured {len(self.findings)} findings from this session.")
52
+ # Run confidence on new findings
53
+ try:
54
+ result = self.sdk.compute_confidence()
55
+ print(f"Confidence updated: {result.get('iterations', '?')} iterations")
56
+ except:
57
+ pass
58
+
59
+ # Report what was captured
60
+ for f in self.findings:
61
+ content = f.get("content", "")[:80]
62
+ print(f" [{f.get('pointKind', '?')}] {content}...")
63
+
64
+ self.sdk.close()
65
+
66
+
67
+ # Demo script
68
+ if __name__ == "__main__":
69
+ # Demo — requires TORTOISE_DB_URI or pass db_path explicitly
70
+ import os, sys
71
+ from tortoise.config import resolve_db_path
72
+ db_path = resolve_db_path() # canonical path; respects TORTOISE_DB_PATH
73
+ print(f"Using embedded DB at {db_path} (set TORTOISE_DB_PATH or TORTOISE_DB_URI docker:// to override)")
74
+ sc = SessionContinuity(db_path=db_path)
75
+ session_id = sc.start("Researching React auth libraries")
76
+
77
+ # Simulate findings during session
78
+ sc.capture("Lucia Auth has been deprecated as of 2025", kind="observation")
79
+ sc.capture("Better-Auth is the official successor to Lucia", kind="observation")
80
+ sc.capture("Clerk is overkill for solo projects — use Better-Auth", kind="decision")
81
+
82
+ sc.end()
@@ -0,0 +1,569 @@
1
+ """Session indexer — metadata extraction for agent session files.
2
+
3
+ Extracts narrative_arc, summary, keywords, topics, issues, PRs, and
4
+ critical_decisions from session markdown files via LLM or keyword fallback.
5
+
6
+ Usage:
7
+ python -m tortoise.session_indexer <file_path>
8
+ python -m tortoise.session_indexer --dir <directory> --batch
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import re
15
+ import sys
16
+ import hashlib
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ # ── YAML frontmatter parsing ──────────────────────────────────────
21
+
22
+ def _parse_frontmatter(content: str) -> dict:
23
+ """Extract YAML frontmatter from markdown content."""
24
+ if not content.startswith("---"):
25
+ return {}
26
+ parts = content.split("---", 2)
27
+ if len(parts) < 3:
28
+ return {}
29
+ try:
30
+ import yaml
31
+ return yaml.safe_load(parts[1]) or {}
32
+ except Exception:
33
+ return {}
34
+
35
+ # ── Keyword extraction (TF-IDF + graph entities, no LLM) ──────────
36
+
37
+ # Stopwords filtered before TF-IDF scoring
38
+ _STOPWORDS = frozenset({
39
+ 'the','a','an','is','was','are','were','be','been','has','have','had',
40
+ 'do','does','did','will','would','could','should','can','may','might',
41
+ 'i','you','he','she','it','we','they','me','him','her','us','them',
42
+ 'my','your','his','its','our','their','this','that','these','those',
43
+ 'and','or','but','not','no','yes','if','then','else','when','where',
44
+ 'what','why','how','in','on','at','to','of','for','with','from','by',
45
+ 'as','so','just','also','very','really','too','only','about','like',
46
+ 'all','some','any','each','every','more','most','here','there','now',
47
+ 'up','out','one','two','go','get','see','know','think','say','make',
48
+ 'use','take','come','look','need','let','find','want','work','well',
49
+ 'ok','okay','yeah','yes','right','good','great','done','got','going',
50
+ 'new','old','first','last','next','still','even','way','thing','much',
51
+ 'many','back','into','over','after','before','between','through',
52
+ 'user','assistant','agent','session','file','data','time','run',
53
+ 'code','error','fix','change','add','set','try','call','return',
54
+ })
55
+
56
+ # Cached IDF model — built once across the corpus
57
+ _idf_model: dict[str, float] | None = None
58
+ _corpus_size: int = 0
59
+
60
+
61
+ def _tokenize(text: str) -> list[str]:
62
+ """Lowercase, extract alphanumeric tokens, filter stopwords and short terms."""
63
+ import re as _re
64
+ tokens = _re.findall(r'[a-z0-9][a-z0-9_./-]*[a-z0-9]', text.lower())
65
+ return [t for t in tokens if len(t) > 2 and t not in _STOPWORDS]
66
+
67
+
68
+ def _build_idf(corpus_paths: list[str] | None = None, force: bool = False) -> dict[str, float]:
69
+ """Build IDF model from session files. Cached globally, rebuilt when force=True."""
70
+ global _idf_model, _corpus_size
71
+ if _idf_model is not None and not force:
72
+ return _idf_model
73
+
74
+ import math
75
+ from pathlib import Path
76
+
77
+ if corpus_paths is None:
78
+ docs_dir = Path.home() / '.tortoise' / 'docs' / 'conversations'
79
+ corpus_paths = [str(p) for p in docs_dir.glob('*.md')]
80
+
81
+ df = {} # document frequency: term → how many docs contain it
82
+ doc_count = 0
83
+
84
+ for path in corpus_paths:
85
+ try:
86
+ with open(path) as f:
87
+ text = f.read()
88
+ except Exception:
89
+ continue
90
+ doc_count += 1
91
+ unique_terms = set(_tokenize(text))
92
+ for term in unique_terms:
93
+ df[term] = df.get(term, 0) + 1
94
+
95
+ _corpus_size = max(doc_count, 1)
96
+ _idf_model = {term: math.log(_corpus_size / (count + 1)) + 1 for term, count in df.items()}
97
+ return _idf_model
98
+
99
+
100
+ def _tfidf_keywords(content: str, top_n: int = 8) -> list[str]:
101
+ """Extract top TF-IDF keywords from a single document."""
102
+ idf = _build_idf()
103
+ tokens = _tokenize(content)
104
+ if not tokens:
105
+ return []
106
+
107
+ from collections import Counter
108
+ tf = Counter(tokens)
109
+ max_tf = max(tf.values()) if tf else 1
110
+
111
+ scores = {}
112
+ for term, count in tf.items():
113
+ tf_norm = count / max_tf
114
+ scores[term] = tf_norm * idf.get(term, 1.0)
115
+
116
+ return [t for t, _ in sorted(scores.items(), key=lambda x: -x[1])[:top_n]]
117
+
118
+
119
+ # Cached FalkorDB connection for graph entity lookups
120
+ _graph_db = None
121
+
122
+ def _graph_entity_keywords(content: str) -> list[str]:
123
+ """Find Object and Subject names from the graph mentioned in content."""
124
+ global _graph_db
125
+ content_lower = content.lower()
126
+ matches = []
127
+ try:
128
+ import os as _os
129
+ uri = _os.environ.get('TORTOISE_DB_URI', '')
130
+ if not uri:
131
+ return []
132
+ if _graph_db is None:
133
+ from falkordb import FalkorDB
134
+ from urllib.parse import urlparse
135
+ parsed = urlparse(uri)
136
+ host = parsed.hostname or 'localhost'
137
+ port = parsed.port or 16379
138
+ _graph_db = FalkorDB(host=host, port=port)
139
+ g = _graph_db.select_graph('tortoise')
140
+ rows = g.query('MATCH (n) WHERE (n:Object OR n:Subject) AND n.name IS NOT NULL RETURN DISTINCT n.name').result_set
141
+ for row in rows:
142
+ name = str(row[0])
143
+ if len(name) > 3 and name.lower() in content_lower:
144
+ matches.append(name)
145
+ except Exception:
146
+ pass
147
+ return matches
148
+
149
+
150
+ def extract_keywords_from_frontmatter(content: str) -> dict:
151
+ """Extract metadata from session content — no LLM required.
152
+
153
+ Uses TF-IDF over the full corpus to find distinctive terms, plus
154
+ graph entity matching for high-precision Object/Subject references.
155
+
156
+ Returns dict with keys: summary, narrative_arc, keywords, topics, issues, prs.
157
+ """
158
+ fm = _parse_frontmatter(content)
159
+
160
+ # Summary from title or first substantive line
161
+ summary = fm.get("title", "")
162
+ if not summary:
163
+ body = content.split("---", 2)[-1] if "---" in content else content
164
+ for line in body.split("\n"):
165
+ stripped = line.strip()
166
+ if stripped and not stripped.startswith("#") and len(stripped) > 10:
167
+ summary = stripped[:200]
168
+ break
169
+
170
+ # Keywords: frontmatter tags + TF-IDF terms + graph entity matches
171
+ keywords = fm.get("tags", [])
172
+ if isinstance(keywords, str):
173
+ keywords = [k.strip() for k in keywords.split(",")]
174
+
175
+ tfidf_terms = _tfidf_keywords(content)
176
+ graph_terms = _graph_entity_keywords(content)
177
+
178
+ # Combine: tags first (explicit), then graph entities (high precision), then TF-IDF (fill)
179
+ keywords = list(dict.fromkeys(keywords + graph_terms + tfidf_terms))[:10]
180
+
181
+ # Topics from frontmatter domain or inferred from keyword clusters
182
+ topics = []
183
+ domain = fm.get("domain", "")
184
+ if domain:
185
+ topics.append(domain)
186
+ infra_terms = {"docker","container","volume","port","deploy","config","server","host","network"}
187
+ data_terms = {"graph","database","index","search","query","falkordb","tortoise","redis","sql"}
188
+ eng_terms = {"api","sdk","mcp","extension","test","e2e","typecheck","pipeline","workflow",
189
+ "commit","pr","github","issue","python","typescript"}
190
+ kw_set = set(keywords)
191
+ if kw_set & infra_terms:
192
+ topics.append("infrastructure")
193
+ if kw_set & data_terms:
194
+ topics.append("data")
195
+ if kw_set & eng_terms:
196
+ topics.append("engineering")
197
+ topics = list(dict.fromkeys(topics))[:3]
198
+
199
+ # Issues from frontmatter or content regex
200
+ issues = fm.get("issues", [])
201
+ if isinstance(issues, str):
202
+ issues = [issues]
203
+ # Also scan content for repo#NNN patterns
204
+ issue_refs = re.findall(r'([a-zA-Z0-9_-]+)#(\d+)', content)
205
+ for repo, num in issue_refs:
206
+ ref = f"{repo}#{num}"
207
+ if ref not in issues:
208
+ issues.append(ref)
209
+ issues = issues[:20]
210
+
211
+ # PRs from content
212
+ prs = fm.get("prs", [])
213
+ if isinstance(prs, str):
214
+ prs = [prs]
215
+
216
+ # Narrative arc from frontmatter phases or basic generation
217
+ narrative_arc = fm.get("narrative_arc", [])
218
+ if not narrative_arc:
219
+ narrative_arc = [{
220
+ "phase": "Session",
221
+ "topic": summary[:100] or "Untitled",
222
+ "decisions": [],
223
+ "message_range": [1, max(1, _count_messages(content))]
224
+ }]
225
+
226
+ # Critical decisions from frontmatter
227
+ critical_decisions = fm.get("critical_decisions", [])
228
+
229
+ return {
230
+ "summary": summary or "Untitled session",
231
+ "narrative_arc": narrative_arc,
232
+ "keywords": keywords,
233
+ "topics": topics[:3],
234
+ "issues": issues,
235
+ "prs": prs,
236
+ "critical_decisions": critical_decisions,
237
+ }
238
+
239
+ def _count_messages(content: str) -> int:
240
+ """Count ## User / ## Assistant blocks in markdown."""
241
+ return len(re.findall(r'^## (?:User|Assistant)$', content, re.MULTILINE))
242
+
243
+ # ── LLM extraction ────────────────────────────────────────────────
244
+
245
+ EXTRACTION_PROMPT = """Analyze this AI agent conversation. Return JSON only, no markdown:
246
+
247
+ {
248
+ "narrative_arc": [
249
+ {
250
+ "phase": "Act N — Short Title",
251
+ "topic": "one-line description of what was discussed",
252
+ "decisions": ["any decisions made in this phase"],
253
+ "message_range": [start_msg_number, end_msg_number]
254
+ }
255
+ ],
256
+ "summary": "One paragraph synthesizing the narrative arc phases",
257
+ "keywords": ["3-8", "specific", "technical", "terms"],
258
+ "topics": ["1-3", "high-level", "categories"],
259
+ "issues": ["repo#NNN"],
260
+ "prs": ["repo#NNN"],
261
+ "critical_decisions": [
262
+ {"decision": "what was decided", "confidence": "high|medium|low", "phase": "Act N"}
263
+ ]
264
+ }
265
+
266
+ Conversation:
267
+ ---
268
+ """
269
+
270
+
271
+ # Whitelist of known models — llm_model flows from MCP tools / CLI and must
272
+ # not allow arbitrary model injection (could trigger expensive tiers).
273
+ _ALLOWED_LLM_MODELS = {"gpt-5-mini", "gpt-4o-mini", "gpt-4o"}
274
+
275
+
276
+ def extract_metadata_with_llm(content: str, model: str = "gpt-5-mini") -> dict | None:
277
+ """Extract metadata using an LLM. Returns None on failure (caller should fall back)."""
278
+ if model not in _ALLOWED_LLM_MODELS:
279
+ return {"error": f"llm_model {model!r} not allowed (whitelist: {sorted(_ALLOWED_LLM_MODELS)})"}
280
+ try:
281
+ # Try OpenAI-compatible API
282
+ api_key = os.environ.get("OPENAI_API_KEY")
283
+ if not api_key:
284
+ return None
285
+
286
+ import requests
287
+ response = requests.post(
288
+ "https://api.openai.com/v1/chat/completions",
289
+ headers={
290
+ "Authorization": f"Bearer {api_key}",
291
+ "Content-Type": "application/json",
292
+ },
293
+ json={
294
+ "model": model,
295
+ "messages": [
296
+ {"role": "system", "content": "You extract structured metadata from agent conversations. Return only valid JSON, no markdown fences."},
297
+ {"role": "user", "content": EXTRACTION_PROMPT + content[:16000]}, # ~12K token limit
298
+ ],
299
+ "temperature": 0.3,
300
+ "max_tokens": 2000,
301
+ },
302
+ timeout=30,
303
+ )
304
+ response.raise_for_status()
305
+ result = response.json()
306
+ text = result["choices"][0]["message"]["content"]
307
+
308
+ # Strip markdown fences if present
309
+ text = text.strip()
310
+ if text.startswith("```"):
311
+ text = text.split("\n", 1)[-1]
312
+ if text.endswith("```"):
313
+ text = text[:-3]
314
+ text = text.strip()
315
+
316
+ result = json.loads(text)
317
+ # Validate types to prevent downstream crashes
318
+ if not isinstance(result.get("narrative_arc"), list):
319
+ result["narrative_arc"] = []
320
+ if not isinstance(result.get("keywords"), list):
321
+ result["keywords"] = []
322
+ if not isinstance(result.get("issues"), list):
323
+ result["issues"] = []
324
+ if not isinstance(result.get("prs"), list):
325
+ result["prs"] = []
326
+ return result
327
+ except Exception as e:
328
+ print(f"[session_indexer] LLM extraction failed: {e}", file=sys.stderr)
329
+ return None
330
+
331
+
332
+ # ── Tiered extraction (main entry point) ──────────────────────────
333
+
334
+ def extract_metadata(content: str, llm_model: str | None = "gpt-5-mini") -> dict:
335
+ """Extract metadata from session content.
336
+
337
+ Strategy:
338
+ 1. If frontmatter has keywords and narrative_arc → use them (fast path)
339
+ 2. If LLM available → LLM extraction
340
+ 3. Fallback → keyword extraction from frontmatter
341
+
342
+ Returns dict suitable for passing to create_event().
343
+ """
344
+ fm = _parse_frontmatter(content)
345
+
346
+ # Tier 1: Rich frontmatter — skip LLM
347
+ if fm.get("keywords") and fm.get("narrative_arc"):
348
+ issues = fm.get("issues", [])
349
+ if isinstance(issues, str):
350
+ issues = [issues]
351
+ prs = fm.get("prs", [])
352
+ if isinstance(prs, str):
353
+ prs = [prs]
354
+ return {
355
+ "summary": fm.get("title", ""),
356
+ "narrative_arc": fm["narrative_arc"],
357
+ "keywords": fm["keywords"] if isinstance(fm["keywords"], list) else [fm["keywords"]],
358
+ "topics": fm.get("topics", []),
359
+ "issues": issues,
360
+ "prs": prs,
361
+ "critical_decisions": fm.get("critical_decisions", []),
362
+ }
363
+
364
+ # Tier 2: LLM extraction
365
+ if llm_model:
366
+ result = extract_metadata_with_llm(content, llm_model)
367
+ if result:
368
+ # Validate
369
+ if "keywords" in result and len(result.get("keywords", [])) > 0:
370
+ return result
371
+
372
+ # Tier 3: Keyword fallback
373
+ return extract_keywords_from_frontmatter(content)
374
+
375
+
376
+ # ── Session embeddings (#244) ──────────────────────────────────────
377
+
378
+
379
+ def session_embedding_text(name: str, summary: str = "",
380
+ keywords: list[str] | None = None,
381
+ topics: list[str] | None = None) -> str:
382
+ """Compose the embedding text for an AgentSession Event.
383
+
384
+ name + summary + keywords + topics, de-duplicated (preserving order) and
385
+ whitespace-joined. Shared by the indexers (session_indexer CLI,
386
+ ingest_corpus) and graph-scripts/backfill_embeddings.py so the semantic
387
+ surface is identical everywhere.
388
+ """
389
+ parts: list[str] = []
390
+ for p in (name or "", summary or "", *(keywords or []), *(topics or [])):
391
+ s = str(p).strip() if p else ""
392
+ if s and s not in parts:
393
+ parts.append(s)
394
+ return " ".join(parts).strip()
395
+
396
+
397
+ def compute_session_embedding(name: str, summary: str = "",
398
+ keywords: list[str] | None = None,
399
+ topics: list[str] | None = None) -> list[float] | None:
400
+ """Compute the 384-dim embedding for an AgentSession Event.
401
+
402
+ Degrades gracefully to None when the embedding model is unavailable or the
403
+ composed text is empty (mirrors tortoise.embeddings.compute_embedding —
404
+ session indexing must never depend on embeddings). Callers store the result
405
+ as vecf32 on the Event node.
406
+ """
407
+ text = session_embedding_text(name, summary, keywords, topics)
408
+ if not text:
409
+ return None
410
+ try:
411
+ from tortoise.embeddings import compute_embedding
412
+ return compute_embedding(text)
413
+ except Exception:
414
+ return None
415
+
416
+
417
+ # ── File utilities ────────────────────────────────────────────────
418
+
419
+ def compute_file_hash(file_path: str) -> str | None:
420
+ """SHA256 hash of file contents. Returns None on error."""
421
+ try:
422
+ with open(file_path, "rb") as f:
423
+ return hashlib.sha256(f.read()).hexdigest()
424
+ except Exception:
425
+ return None
426
+
427
+
428
+ def extract_session_id(file_path: str) -> str | None:
429
+ """Extract session ID from frontmatter or filename."""
430
+ try:
431
+ with open(file_path) as f:
432
+ content = f.read()
433
+ except Exception:
434
+ return None
435
+
436
+ fm = _parse_frontmatter(content)
437
+ sid = fm.get("sessionId") or fm.get("session_id")
438
+ if sid:
439
+ return sid
440
+
441
+ # Fallback: derive from filename
442
+ stem = Path(file_path).stem
443
+ return f"file_{stem}"
444
+
445
+
446
+ # ── CLI ────────────────────────────────────────────────────────────
447
+
448
+ def main():
449
+ import argparse
450
+ parser = argparse.ArgumentParser(description="Extract metadata from session files")
451
+ parser.add_argument("path", help="Session file path or directory")
452
+ parser.add_argument("--dir", action="store_true", help="Path is a directory")
453
+ parser.add_argument("--batch", action="store_true", help="Batch process (with --dir)")
454
+ parser.add_argument("--no-llm", action="store_true", help="Skip LLM, use keyword-only")
455
+ parser.add_argument("--model", default="gpt-5-mini", help="LLM model name")
456
+ parser.add_argument("--db", default=None, help="Tortoise DB URI (docker://host:port/graph). When set, indexes into FalkorDB instead of printing to stdout.")
457
+ args = parser.parse_args()
458
+
459
+ model = None if args.no_llm else args.model
460
+
461
+ if args.dir:
462
+ dir_path = Path(args.path).resolve()
463
+ if not dir_path.is_dir():
464
+ print(f"Error: {args.path} is not a directory", file=sys.stderr)
465
+ sys.exit(1)
466
+
467
+ if args.db:
468
+ # Index via SDK
469
+ import os as _os
470
+ _os.environ['TORTOISE_DB_URI'] = args.db
471
+ from tortoise.sdk import TortoiseSDK
472
+ sdk = TortoiseSDK()
473
+ llm = None if args.no_llm else args.model
474
+ result = sdk.index_sessions(str(dir_path), extract_metadata=True, llm_model=llm)
475
+ print(json.dumps(result, indent=2))
476
+ else:
477
+ files = sorted(dir_path.glob("*.md"))
478
+ print(f"Processing {len(files)} files...")
479
+ model = None if args.no_llm else args.model
480
+ for i, f in enumerate(files):
481
+ try:
482
+ content = f.read_text()
483
+ metadata = extract_metadata(content, model)
484
+ print(f"[{i+1}/{len(files)}] {f.name}: {len(metadata.get('keywords',[]))} keywords, "
485
+ f"{len(metadata.get('narrative_arc',[]))} phases")
486
+ except Exception as e:
487
+ print(f"[{i+1}/{len(files)}] {f.name}: ERROR - {e}", file=sys.stderr)
488
+ else:
489
+ file_path = Path(args.path).resolve()
490
+ if args.db:
491
+ # Index single file via SDK
492
+ import os as _os
493
+ _os.environ['TORTOISE_DB_URI'] = args.db
494
+ from tortoise.sdk import TortoiseSDK
495
+ sdk = TortoiseSDK()
496
+ llm = None if args.no_llm else args.model
497
+ content = file_path.read_text()
498
+ metadata = extract_metadata(content, llm)
499
+ session_id = extract_session_id(str(file_path))
500
+ file_hash = compute_file_hash(str(file_path))
501
+ event_id = f"session_{session_id}" if session_id else f"file_{file_path.stem}"
502
+ proj = sdk._get_proj()
503
+ exists = proj.g.query(
504
+ "MATCH (e:Event {eventId: $eid}) RETURN properties(e)",
505
+ params={"eid": event_id}
506
+ ).result_set
507
+ if exists and exists[0][0].get("file_hash") == file_hash:
508
+ print(json.dumps({"status": "skipped", "reason": "unchanged"}))
509
+ else:
510
+ # #244: compute the session embedding (name + summary + keywords
511
+ # + topics) and store as vecf32 — degrades to None when the
512
+ # model is unavailable (session indexing never depends on it).
513
+ embedding = compute_session_embedding(
514
+ metadata.get("summary", file_path.stem),
515
+ metadata.get("summary", ""),
516
+ metadata.get("keywords", []),
517
+ metadata.get("topics", []),
518
+ )
519
+ props = {
520
+ "name": metadata.get("summary", file_path.stem),
521
+ "eventKind": "AgentSession",
522
+ "session_id": session_id or f"file_{file_path.stem}",
523
+ "agent": "pi",
524
+ "source_file": str(file_path),
525
+ "file_hash": file_hash,
526
+ "keywords": metadata.get("keywords", []),
527
+ "topics": metadata.get("topics", []),
528
+ "message_count": _count_messages(content),
529
+ "content_metadata": json.dumps({
530
+ "schema_version": 1,
531
+ "summary": metadata.get("summary", ""),
532
+ "narrative_arc": metadata.get("narrative_arc", []),
533
+ "issues": metadata.get("issues", []),
534
+ "prs": metadata.get("prs", []),
535
+ "critical_decisions": metadata.get("critical_decisions", []),
536
+ }),
537
+ "eventStatus": "completed",
538
+ "classificationLevel": "internal",
539
+ }
540
+ if exists:
541
+ proj.g.query(
542
+ "MATCH (e:Event {eventId: $eid}) SET e += $props, "
543
+ "e.embedding = CASE WHEN $embedding IS NOT NULL THEN vecf32($embedding) ELSE e.embedding END",
544
+ params={"eid": event_id, "props": props, "embedding": embedding}
545
+ )
546
+ print(json.dumps({"status": "updated", "eventId": event_id}))
547
+ else:
548
+ props["startedAt"] = __import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat()
549
+ proj.g.query(
550
+ "CREATE (e:Event {eventId: $eid}) SET e += $props, "
551
+ "e.embedding = CASE WHEN $embedding IS NOT NULL THEN vecf32($embedding) END",
552
+ params={"eid": event_id, "props": props, "embedding": embedding}
553
+ )
554
+ print(json.dumps({"status": "ingested", "eventId": event_id}))
555
+ # Wire INSTANTIATES edges to issue/PR Objects (parity with ingest_corpus)
556
+ try:
557
+ from tortoise.sdk import TortoiseSDK
558
+ _sdk = TortoiseSDK()
559
+ _sdk._connect_issue_objects(event_id, metadata)
560
+ except Exception:
561
+ pass # non-fatal edge wiring
562
+ else:
563
+ content = file_path.read_text()
564
+ metadata = extract_metadata(content, args.model if not args.no_llm else None)
565
+ print(json.dumps(metadata, indent=2))
566
+
567
+
568
+ if __name__ == "__main__":
569
+ main()
@@ -0,0 +1,20 @@
1
+ """Shared state layer — infrastructure & observability .
2
+
3
+ Modules:
4
+ monitoring — 4 golden signals (latency P99, throughput, error rate, saturation)
5
+ concurrency — fcntl.flock + atomic os.rename for single-machine coordination
6
+ events — type-based event versioning (no global schemaVersion)
7
+ recovery — crash recovery: scan incomplete cards on startup, event ID dedup
8
+ """
9
+
10
+ from .monitoring import GoldenSignals, collect_signals
11
+ from .concurrency import locked_append, atomic_claim
12
+ from .events import EventCodec, event_types, register_event_type
13
+ from .recovery import scan_incomplete_cards, dedup_events, find_last_checkpoint
14
+
15
+ __all__ = [
16
+ "GoldenSignals", "collect_signals",
17
+ "locked_append", "atomic_claim",
18
+ "EventCodec", "event_types", "register_event_type",
19
+ "scan_incomplete_cards", "dedup_events", "find_last_checkpoint",
20
+ ]