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
tortoise/extractor.py ADDED
@@ -0,0 +1,945 @@
1
+ """Extractor — transcript segment(s) → events, via the shared EventAPI.
2
+
3
+ M0 ships a deterministic, offline `MockExtractor` so the spine runs with no API
4
+ key: one utterance-level point each (Option A), plus asserted-only {NAND, IMPL}
5
+ operators inferred from discourse connectives. The real LLM extractor (M2) will
6
+ implement the same `Extractor` interface — segment in, events out — so nothing
7
+ downstream changes when it's swapped in.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ from typing import Protocol
14
+
15
+ from .api import EventAPI, provenance
16
+
17
+ # Asserted-relation cues (README: speaker-asserted operators only, for now).
18
+ # ponytail: single-word cues use \b word boundaries (#8); multi-word phrases use substring.
19
+ _SUPPORT_SINGLE_RE = re.compile(r'\b(because|since|therefore|thus|hence|so)\b', re.IGNORECASE)
20
+ _SUPPORT_PHRASES = ("given that",)
21
+ _REFUTE_SINGLE_RE = re.compile(r'\b(but|however|although)\b', re.IGNORECASE)
22
+ _REFUTE_PHRASES = ("not relevant", "doesn't follow", "on the contrary", "except that")
23
+ _PUNC = re.compile(r'[,.!?;:\'\"()\[\]{}]') # strip before phrase-matching (#8)
24
+
25
+ def _has_cue(text: str, single_re: re.Pattern, phrases: tuple[str, ...]) -> bool:
26
+ return bool(single_re.search(text)) or any(p in text for p in phrases)
27
+
28
+ _SPEAKER = re.compile(r"^\s*([A-Z][\w .'-]{0,40}):\s*(.*)$")
29
+ _SENT = re.compile(r"[^.?!]+[.?!]?")
30
+
31
+
32
+ class Extractor(Protocol):
33
+ def run(self, transcript: str, source_id: str, api: EventAPI,
34
+ *, multi_source: bool = False) -> None: ...
35
+
36
+
37
+ def _utterances(transcript: str):
38
+ """Yield (speaker, text, span) at sentence granularity with char offsets."""
39
+ base = 0
40
+ for line in transcript.splitlines(keepends=True):
41
+ stripped = line.rstrip("\n")
42
+ m = _SPEAKER.match(stripped)
43
+ if not m: # skip preamble / non-"Speaker: text" lines
44
+ base += len(line)
45
+ continue
46
+ speaker, body = m.group(1), m.group(2)
47
+ body_off = m.start(2)
48
+ for sm in _SENT.finditer(body):
49
+ text = sm.group(0).strip()
50
+ if len(text) >= 3:
51
+ start = base + body_off + sm.start()
52
+ yield speaker, text, [start, start + len(sm.group(0))]
53
+ base += len(line)
54
+
55
+
56
+ def _strip_frontmatter(text: str) -> str:
57
+ """Strip YAML frontmatter only if at document start and before first ## header."""
58
+ m = re.match(r'^---\n.*?\n---\n', text, re.DOTALL)
59
+ if m:
60
+ after = text[m.end():]
61
+ first_header = after.find('## ')
62
+ if first_header >= 0:
63
+ return after
64
+ return text
65
+
66
+
67
+ # -- Document mode: split markdown on ## headers, not conversation turns -------------
68
+ _DOC_HEADER = re.compile(r"^##\s+(.+)$", re.MULTILINE)
69
+
70
+
71
+ def _document_sections(transcript: str):
72
+ """Split markdown on ## section headers for document-mode ingestion.
73
+
74
+ Returns (is_document, sections) where sections is a list of
75
+ (title, text, span). Returns (False, []) if no ## headers found.
76
+ """
77
+ text = _strip_frontmatter(transcript)
78
+ if "\n## " not in text and not text.startswith("## "):
79
+ return False, []
80
+
81
+ # ponytail: strip fenced code blocks to avoid splitting on ## inside them.
82
+ # Replace code block content with placeholder to keep section offsets correct.
83
+ in_code = False
84
+ fence_char = ""
85
+ processed: list[str] = []
86
+ i = 0
87
+ while i < len(text):
88
+ if text[i:i+3] in ("```", "~~~"):
89
+ if not in_code:
90
+ fence_char = text[i:i+3]
91
+ in_code = True
92
+ processed.append(f"\n\n{text[i:i+3]}\n")
93
+ i += 3
94
+ elif text[i:i+3] == fence_char:
95
+ in_code = False
96
+ processed.append(f"{fence_char}\n\n")
97
+ i += 3
98
+ else:
99
+ processed.append(text[i])
100
+ i += 1
101
+ elif in_code:
102
+ # Keep code content as literal text (preserve newlines for offset alignment)
103
+ # but ensure ## on its own line doesn't match as a section header
104
+ if text[i:i+3] == "## " and (i == 0 or text[i-1] == '\n'):
105
+ processed.append("#_# ") # ponytail: mangle section-like headers in code
106
+ else:
107
+ processed.append(text[i])
108
+ i += 1
109
+ else:
110
+ processed.append(text[i])
111
+ i += 1
112
+ clean = "".join(processed)
113
+
114
+ sections = []
115
+ for m in _DOC_HEADER.finditer(clean):
116
+ title = m.group(1).strip()
117
+ start = m.start()
118
+ sections.append((title, start, m.end()))
119
+
120
+ results = []
121
+ first_start = sections[0][1]
122
+ if first_start > 0:
123
+ preamble = clean[:first_start].strip()
124
+ if preamble:
125
+ results.append(("preamble", preamble, [0, first_start]))
126
+
127
+ for i, (title, start, body_start) in enumerate(sections):
128
+ content_start = body_start
129
+ if content_start < len(clean) and clean[content_start] == '\n':
130
+ content_start += 1
131
+
132
+ content_end = sections[i + 1][1] if i + 1 < len(sections) else len(clean)
133
+ body = clean[content_start:content_end].strip()
134
+ if len(body) >= 20: # skip empty/short sections
135
+ span = [content_start, content_end]
136
+ results.append((title, body, span))
137
+
138
+ return True, results
139
+
140
+
141
+ def _is_claim(text: str) -> bool:
142
+ """Filter: keep only lines that express a CLAIM (assertion, finding, tension, causal relationship)."""
143
+ t = text.strip()
144
+ if len(t) < 40:
145
+ return False
146
+ if t.startswith('**') and t.count('**') >= 2 and len(t) < 80:
147
+ return False
148
+ if t.startswith('|') or t.startswith('```') or t.startswith('#'):
149
+ return False
150
+ if t.startswith('>'):
151
+ return False
152
+ low = t.lower()
153
+ # Explicit stance verbs
154
+ stance_words = (' is ', ' are ', ' does ', ' should ', ' must ', ' can ', ' cannot ',
155
+ ' claim', ' assert', ' argue', ' find', ' show', ' suggests',
156
+ ' contradicts', ' challenges', ' disagrees', ' fails', ' never',
157
+ ' always', ' instead', ' however', ' therefore', ' because')
158
+ if any(w in low for w in stance_words):
159
+ return True
160
+ # Arrow/causal notation: only keep if part of a complete statement (has context)
161
+ if ('→' in t or '->' in t or '──' in t) and len(t) > 80:
162
+ return True
163
+ # Comparative/ranking: "better than", "more than", "primary", "dominant"
164
+ if any(w in low for w in ('better than', 'more important', 'primary', 'dominant',
165
+ 'key turning point', 'structural', 'fundamental')):
166
+ return True
167
+ # Percentage/fact with implied stance: need context AND a stance word
168
+ if any(c.isdigit() for c in t) and '%' in t and len(t) > 60:
169
+ if any(w in low for w in ('fail', 'unchanged', 'rate', 'increase', 'decrease', 'drop', 'rise', 'fall')):
170
+ return True
171
+ return False
172
+
173
+
174
+ class MockExtractor:
175
+ """Heuristic, deterministic extractor for the M0 spine."""
176
+
177
+ version = "mock@0"
178
+
179
+ def run(self, transcript: str, source_id: str, api: EventAPI,
180
+ *, multi_source: bool = False) -> None:
181
+ if multi_source:
182
+ # Multi-source mode: claim extraction → embedding pre-filter → cue-word gate typing
183
+ pids = []
184
+ for speaker, text, span in _utterances(transcript):
185
+ if not _is_claim(text):
186
+ continue
187
+ prov = provenance(source_id, span, quote=text, speaker=speaker,
188
+ extracted_by=self.version)
189
+ # #49 Phase 2: context is deprecated — use extractedFrom for provenance
190
+ pid = api.add_point(content=text, provenance=prov,
191
+ extractedFrom=source_id)
192
+ pids.append((pid, text.lower(), prov))
193
+
194
+ # Use embedding pre-filter if available
195
+ try:
196
+ from tortoise.embeddings import find_cross_source_matches
197
+ # Build points dict from API's stored points
198
+ # We need to reconstruct from the log — simple approach: use what we collected
199
+ all_points = {}
200
+ for pid_i, ti, pvi in pids:
201
+ sp = pvi.get('speaker', 'unknown') if isinstance(pvi, dict) else 'unknown'
202
+ all_points[pid_i] = {"content": ti, "speaker": sp}
203
+
204
+ emb_matches = find_cross_source_matches(all_points, threshold=0.40)
205
+ matched_pairs = set()
206
+ for m in emb_matches:
207
+ matched_pairs.add((m['src'], m['dst']))
208
+
209
+ # Only create operators for embedding-matched pairs with cue words
210
+ for i in range(len(pids)):
211
+ pi, ti, pvi = pids[i]
212
+ for j in range(i + 1, len(pids)):
213
+ pj, tj, pvj = pids[j]
214
+ if (pi, pj) not in matched_pairs and (pj, pi) not in matched_pairs:
215
+ continue
216
+ # Check cue words for gate type
217
+ gate = None
218
+ ti_clean = _PUNC.sub('', f" {ti} ")
219
+ tj_clean = _PUNC.sub('', f" {tj} ")
220
+ if _has_cue(ti_clean, _SUPPORT_SINGLE_RE, _SUPPORT_PHRASES) or _has_cue(tj_clean, _SUPPORT_SINGLE_RE, _SUPPORT_PHRASES):
221
+ gate = "IMPL"
222
+ elif _has_cue(ti_clean, _REFUTE_SINGLE_RE, _REFUTE_PHRASES) or _has_cue(tj_clean, _REFUTE_SINGLE_RE, _REFUTE_PHRASES):
223
+ gate = "NAND"
224
+ if gate:
225
+ api.add_operator(gate, inputs=[pi, pj], provenance=pvi)
226
+ elif (pi, pj) in matched_pairs:
227
+ # Semantic agreement: similar claims from different sources = IMPL
228
+ # But require shared noun phrase to avoid weak thematic connections
229
+ words_i = set(ti.split())
230
+ words_j = set(tj.split())
231
+ shared = words_i & words_j
232
+ # Need at least 3 shared content words (not just stopwords)
233
+ stopwords = {'the','a','an','is','are','was','were','be','been','being',
234
+ 'have','has','had','do','does','did','will','would','could',
235
+ 'should','may','might','can','shall','to','of','in','for',
236
+ 'on','with','at','by','from','as','into','through','during',
237
+ 'and','but','or','nor','not','so','yet','both','either','neither',
238
+ 'if','then','else','when','where','why','how','this','that','these','those',
239
+ 'it','its','they','them','their','we','our','i','my','you','your',
240
+ 'more','less','very','also','just','only','now','still','already'}
241
+ shared_content = shared - stopwords
242
+ if len(shared_content) >= 3:
243
+ api.add_operator("IMPL", inputs=[pi, pj], provenance=pvi)
244
+ except Exception:
245
+ # Fallback: cue-word only all-pairs (noisy but works)
246
+ # (catches ImportError for missing dependencies AND runtime errors
247
+ # like sklearn ValueError on empty vocabulary)
248
+ for i in range(len(pids)):
249
+ for j in range(i + 1, len(pids)):
250
+ pi, ti, pvi = pids[i]
251
+ pj, tj, pvj = pids[j]
252
+ gate = None
253
+ ti_clean = _PUNC.sub('', f" {ti} ")
254
+ tj_clean = _PUNC.sub('', f" {tj} ")
255
+ if _has_cue(ti_clean, _SUPPORT_SINGLE_RE, _SUPPORT_PHRASES) or _has_cue(tj_clean, _SUPPORT_SINGLE_RE, _SUPPORT_PHRASES):
256
+ gate = "IMPL"
257
+ elif _has_cue(ti_clean, _REFUTE_SINGLE_RE, _REFUTE_PHRASES) or _has_cue(tj_clean, _REFUTE_SINGLE_RE, _REFUTE_PHRASES):
258
+ gate = "NAND"
259
+ if gate:
260
+ api.add_operator(gate, inputs=[pi, pj], provenance=pvi)
261
+ else:
262
+ # Sequential mode (original): only connect consecutive utterances
263
+ prev_pid = None
264
+ for speaker, text, span in _utterances(transcript):
265
+ prov = provenance(source_id, span, quote=text, speaker=speaker,
266
+ extracted_by=self.version)
267
+ # #49 Phase 2: context is deprecated — use extractedFrom for provenance
268
+ pid = api.add_point(content=text, provenance=prov,
269
+ extractedFrom=source_id)
270
+ low = _PUNC.sub('', f" {text.lower()} ")
271
+ gate = None
272
+ if _has_cue(low, _SUPPORT_SINGLE_RE, _SUPPORT_PHRASES):
273
+ gate = "IMPL"
274
+ elif _has_cue(low, _REFUTE_SINGLE_RE, _REFUTE_PHRASES):
275
+ gate = "NAND"
276
+ if gate and prev_pid is not None:
277
+ api.add_operator(gate, inputs=[prev_pid, pid],
278
+ provenance=prov)
279
+ prev_pid = pid
280
+
281
+
282
+ # ---------------------------------------------------------------------------
283
+ # M2: two-stage LLM extractor (cheap point model + reasoning relation model).
284
+ # ---------------------------------------------------------------------------
285
+
286
+ _POINTS_SYS = (
287
+ "TASK: extract_points\n"
288
+ "You are given numbered transcript utterances. For EACH one, return a cleaned, "
289
+ "standalone statement (strip leading discourse connectives like but/so/however, "
290
+ "expand contractions, keep the exact meaning; Option A: one point per utterance, "
291
+ "do NOT split into sub-propositions). Return JSON "
292
+ '{"points": {"<index>": "<cleaned statement>", ...}} with one entry per input '
293
+ "index. Do not add, drop, merge, or reorder."
294
+ )
295
+ _RELATIONS_SYS = (
296
+ "TASK: extract_relations\n"
297
+ "Identify ONLY relations the speaker EXPLICITLY asserted between the given "
298
+ "points — cue words like because/therefore/so (support) or but/however/not "
299
+ "relevant (refute). Do NOT infer unstated relations. Gates: IMPL (supports) or "
300
+ "NAND (refutes). Return JSON "
301
+ '{"relations":[{"op_type":"IMPL|NAND","src":<point index>,"dst":<point index>}]}.'
302
+ )
303
+
304
+ _POINTS_DOC_SYS = (
305
+ "TASK: extract_points_from_section\n"
306
+ "You are given a markdown document section (title + body). Extract structured "
307
+ "claims as Points. Each Point must be a standalone, self-contained statement "
308
+ "that can be understood without the surrounding document context.\n\n"
309
+ "For each claim, classify it into one of these pointKind values:\n"
310
+ "{pointKind_list}\n\n"
311
+ "Also extract:\n"
312
+ "- aboutEntities: list of entity names the claim is about "
313
+ "(people, teams, tools, products, competitors, etc.)\n"
314
+ "- confidence: your confidence that this claim is correctly extracted "
315
+ "and classified (0.0 to 1.0)\n\n"
316
+ 'Return JSON: {{"points": [{{"content": "...", "pointKind": "...", '
317
+ '"aboutEntities": ["..."], "confidence": 0.X}}]}}\n\n'
318
+ "Rules:\n"
319
+ "- One claim per array element. Do not merge unrelated claims.\n"
320
+ "- Skip boilerplate (navigation, table of contents, YAML frontmatter).\n"
321
+ 'If a section contains no extractable claims, return {{"points": []}}.\n'
322
+ "- Claims must be standalone — resolve all pronouns and implicit references."
323
+ )
324
+
325
+ # Default pointKind descriptions (used when no domain override)
326
+ _DEFAULT_POINT_KIND_DESCRIPTIONS: list[tuple[str, str]] = [
327
+ ("statement", "a factual claim or assertion"),
328
+ ("decision", "a binding choice was made"),
329
+ ("vision", "an aspirational future state"),
330
+ ("strategy", "an approach to achieve something"),
331
+ ("plan", "a concrete implementation approach"),
332
+ ("goal", "a desired outcome"),
333
+ ("target", "a measurable objective"),
334
+ ("observation", "an empirical finding or data point"),
335
+ ("hypothesis", "a testable proposition not yet verified"),
336
+ ]
337
+
338
+
339
+ def _build_pointkind_prompt(point_kinds: list[str] | None = None) -> str:
340
+ """Build the pointKind list for the LLM prompt.
341
+
342
+ If point_kinds is provided, use those values (bare names for domain kinds).
343
+ Otherwise use default descriptions.
344
+ """
345
+ if point_kinds:
346
+ lines = [f"- {k}" for k in point_kinds]
347
+ else:
348
+ lines = [f"- {kind}: {desc}" for kind, desc in _DEFAULT_POINT_KIND_DESCRIPTIONS]
349
+ return "\n".join(lines)
350
+
351
+
352
+ def _warn_unrecognized_kinds(extracted_kinds: set[str]) -> None:
353
+ """Warn if any extracted pointKind values are not in the known registry.
354
+
355
+ Prints warnings to stderr. Unknown kinds are accepted (open vocabulary) but
356
+ agents should know when the LLM invents a new kind.
357
+ """
358
+ try:
359
+ from tortoise.domain_loader import kind_is_known
360
+ unknown = {k for k in extracted_kinds if not kind_is_known(k, "pointKind")}
361
+ if unknown:
362
+ import sys
363
+ print(
364
+ f"⚠ unrecognized pointKind values: {sorted(unknown)}. "
365
+ f"These will be stored but may not match any registered ontology. "
366
+ f"Register them via domain manifest if intentional.",
367
+ file=sys.stderr,
368
+ )
369
+ except Exception:
370
+ pass # ponytail: validation is best-effort, don't block extraction
371
+
372
+ _RELATIONS_DOC_SYS = (
373
+ "TASK: extract_relations\n"
374
+ "You are given a list of Points extracted from a document. Identify logical "
375
+ "relationships between them:\n\n"
376
+ "- IMPL: Point A supports, implies, or provides evidence for Point B. "
377
+ "Directional: A → B means 'A supports B'.\n"
378
+ "- NAND: Point A contradicts or is incompatible with Point B. "
379
+ "Symmetric: A ↔ B means 'these cannot both be true'.\n\n"
380
+ "Only report relations that are LOGICALLY NECESSARY — where one claim's truth "
381
+ "implies, supports, or contradicts another. Do NOT report:\n"
382
+ "- Topical similarity (both about the same topic but logically independent)\n"
383
+ "- Co-occurrence (both appear in the same section)\n"
384
+ "- Hierarchical membership (A is a sub-point of B — that's composedOf, not IMPL)\n\n"
385
+ 'Return JSON: {"relations": [{"op_type": "IMPL", "src": <index>, "dst": <index>}, ...]}'
386
+ )
387
+
388
+
389
+ class MockModel:
390
+ """Deterministic offline stand-in implementing the Model interface. Keys on the
391
+ TASK tag in the system prompt so it can serve either stage without a network."""
392
+
393
+ def __init__(self, id: str = "mock"):
394
+ self.id = id
395
+
396
+ def complete(self, *, system: str, user: str) -> str:
397
+ payload = json.loads(user)
398
+ if "extract_entities" in system:
399
+ # Mock entity extraction: detect proper nouns / capitalized names
400
+ body = payload.get("section_body", "")
401
+ subjects, objects, entities = [], [], []
402
+ # Detect organization/team names (multi-word capitalized)
403
+ for match in re.finditer(r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)+)\b', body):
404
+ name = match.group(1)
405
+ if name.lower() not in ("the", "this", "that"):
406
+ if any(w in name.lower() for w in ("team", "org", "group", "dept")):
407
+ subjects.append({"name": name, "subjectKind": "team"})
408
+ else:
409
+ objects.append({"name": name, "objectKind": "product"})
410
+ # Single-word proper nouns
411
+ for word in re.findall(r'\b[A-Z][a-z]+\b', body):
412
+ if len(word) < 3 or word.lower() in ("the", "this", "that", "these", "those", "each", "every", "some", "any", "all", "both", "few", "many", "most", "other", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very"):
413
+ continue
414
+ entities.append(word)
415
+ return json.dumps({"subjects": subjects, "objects": objects,
416
+ "aboutEntities": entities[:5]})
417
+ if "extract_points_from_section" in system:
418
+ # Document mode: return points from section body
419
+ body = payload.get("section_body", "")
420
+ title = payload.get("section_title", "")
421
+ pts = []
422
+ # ponytail: extract sentences as mock points with keyword-based pointKind
423
+ for sent in _SENT.finditer(body):
424
+ text = sent.group(0).strip()
425
+ if len(text) < 20:
426
+ continue
427
+ kind = "statement"
428
+ low = text.lower()
429
+ if any(w in low for w in ("decided", "chosen", "chose", "select", "will adopt")):
430
+ kind = "decision"
431
+ elif any(w in low for w in ("vision", "future state", "aspir")):
432
+ kind = "vision"
433
+ elif any(w in low for w in ("plan", "step", "implement", "build")):
434
+ kind = "plan"
435
+ elif any(w in low for w in ("goal", "outcome", "achieve")):
436
+ kind = "goal"
437
+ elif any(w in low for w in ("found", "observe", "measure", "data shows")):
438
+ kind = "observation"
439
+ elif any(w in low for w in ("hypothes", "might", "could be", "possibly")):
440
+ kind = "hypothesis"
441
+ pts.append({
442
+ "content": text,
443
+ "pointKind": kind,
444
+ "aboutEntities": [],
445
+ "confidence": 0.8,
446
+ })
447
+ return json.dumps({"points": pts})
448
+ if "extract_points" in system:
449
+ utts = payload["utterances"]
450
+ items = utts.items() if isinstance(utts, dict) else enumerate(utts)
451
+ return json.dumps({"points": {str(k): v for k, v in items}})
452
+ if "extract_relations" in system:
453
+ pts = payload["points"]
454
+ rels = []
455
+ for i in range(len(pts)):
456
+ for j in range(i + 1, len(pts)):
457
+ low_i = _PUNC.sub('', f" {pts[i]['content'].lower()} ")
458
+ low_j = _PUNC.sub('', f" {pts[j]['content'].lower()} ")
459
+ if _has_cue(low_j, _SUPPORT_SINGLE_RE, _SUPPORT_PHRASES):
460
+ rels.append({"op_type": "IMPL", "src": i, "dst": j})
461
+ elif _has_cue(low_j, _REFUTE_SINGLE_RE, _REFUTE_PHRASES):
462
+ rels.append({"op_type": "NAND", "src": i, "dst": j})
463
+ if _has_cue(low_i, _SUPPORT_SINGLE_RE, _SUPPORT_PHRASES):
464
+ rels.append({"op_type": "IMPL", "src": j, "dst": i})
465
+ elif _has_cue(low_i, _REFUTE_SINGLE_RE, _REFUTE_PHRASES):
466
+ rels.append({"op_type": "NAND", "src": j, "dst": i})
467
+ return json.dumps({"relations": rels})
468
+ return "{}"
469
+
470
+
471
+ def _overlap(cleaned: str, source: str) -> float:
472
+ """Fraction of source words retained. Guards against a weak point model
473
+ mis-mapping its index→content keys: a real cleaning keeps most words; a
474
+ cleaning of a *different* utterance does not."""
475
+ src = set(re.findall(r"[a-z0-9]+", source.lower()))
476
+ if not src:
477
+ return 1.0
478
+ return len(set(re.findall(r"[a-z0-9]+", cleaned.lower())) & src) / len(src)
479
+
480
+
481
+ def _json(text: str) -> dict:
482
+ """Tolerant JSON parse — small/local models wrap output in ``` fences, add
483
+ preamble, or (thinking models) emit <think>…</think>. Fall back to the
484
+ outermost {...} span."""
485
+ text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL)
486
+ try:
487
+ return json.loads(text)
488
+ except json.JSONDecodeError:
489
+ pass
490
+ t = text.strip()
491
+ if t.startswith("```"):
492
+ t = t.split("```", 2)[1] if t.count("```") >= 2 else t.strip("`")
493
+ t = t[4:] if t.lower().startswith("json") else t
494
+ start, end = t.find("{"), t.rfind("}")
495
+ if 0 <= start < end:
496
+ return json.loads(t[start:end + 1])
497
+ raise ValueError(f"no JSON object in model output: {text[:120]!r}")
498
+
499
+
500
+ class _PointStage:
501
+ def __init__(self, model):
502
+ self.model = model
503
+
504
+ def run(self, utterances, llm_context) -> dict[int, str]:
505
+ """Return {utterance_index: cleaned_content}. The caller owns identity and
506
+ provenance; this is best-effort cleaning only. Tolerates map or list output."""
507
+ numbered = {str(i): u for i, u in enumerate(utterances)}
508
+ out = self.model.complete(
509
+ system=_POINTS_SYS,
510
+ user=json.dumps({"context": llm_context, "utterances": numbered}),
511
+ )
512
+ raw = _json(out).get("points", {})
513
+ cleaned: dict[int, str] = {}
514
+ if isinstance(raw, dict):
515
+ for k, v in raw.items():
516
+ try:
517
+ cleaned[int(k)] = str(v)
518
+ except (ValueError, TypeError):
519
+ pass
520
+ elif isinstance(raw, list): # tolerate [{src/i, content}] or [str]
521
+ for i, item in enumerate(raw):
522
+ if isinstance(item, dict) and "content" in item:
523
+ idx = item.get("src", item.get("i", i))
524
+ try:
525
+ cleaned[int(idx)] = str(item["content"])
526
+ except (ValueError, TypeError):
527
+ pass
528
+ elif isinstance(item, str):
529
+ cleaned[i] = item
530
+ return cleaned
531
+
532
+
533
+ class _DocumentPointStage:
534
+ """Per-section structured output parser for document mode.
535
+ Returns list[dict] with {content, pointKind, aboutEntities, confidence}."""
536
+
537
+ def __init__(self, model, *, point_kinds: list[str] | None = None):
538
+ self.model = model
539
+ self._system = _POINTS_DOC_SYS.format(
540
+ pointKind_list=_build_pointkind_prompt(point_kinds),
541
+ )
542
+
543
+ def run(self, title: str, body: str, llm_context: str) -> list[dict]:
544
+ out = self.model.complete(
545
+ system=self._system,
546
+ user=json.dumps({
547
+ "context": llm_context,
548
+ "section_title": title,
549
+ "section_body": body,
550
+ }),
551
+ )
552
+ raw = _json(out).get("points", [])
553
+ if isinstance(raw, list):
554
+ return [
555
+ {
556
+ "content": str(r.get("content", "")),
557
+ "pointKind": str(r.get("pointKind", "statement")),
558
+ "aboutEntities": list(r.get("aboutEntities", [])),
559
+ "confidence": float(r.get("confidence", 0.5)),
560
+ }
561
+ for r in raw
562
+ if isinstance(r, dict) and r.get("content")
563
+ ]
564
+ return []
565
+
566
+
567
+ class _RelationStage:
568
+ def __init__(self, model, *, system_prompt: str | None = None):
569
+ self.model = model
570
+ self._sys = system_prompt or _RELATIONS_SYS
571
+
572
+ def run(self, point_contents, llm_context, *, multi_source: bool = False):
573
+ extra = " These statements come from DIFFERENT sources. Identify where they agree or contradict." if multi_source else ""
574
+ out = self.model.complete(
575
+ system=self._sys,
576
+ user=json.dumps({"context": llm_context + extra,
577
+ "points": [{"i": i, "content": c}
578
+ for i, c in enumerate(point_contents)]}),
579
+ )
580
+ return _json(out).get("relations", [])
581
+
582
+
583
+ # -- S7 Semantic Extractor ---------------------------------------------------
584
+
585
+ _SEMANTIC_SYS = (
586
+ "TASK: extract_entities\n"
587
+ "Extract Subjects (organizations, teams, roles, people) and Objects "
588
+ "(tools, products, documents, competitors, skills, etc.) from the document "
589
+ "section.\n\n"
590
+ "Subjects represent agents that act, own, or are responsible. Types: "
591
+ "{subject_kinds}\n"
592
+ "Objects represent things that are created, used, or referenced. Types: "
593
+ "{object_kinds}\n\n"
594
+ "Return JSON:\n"
595
+ '{{"subjects": [{{"name": "...", "subjectKind": "..."}}], '
596
+ '"objects": [{{"name": "...", "objectKind": "..."}}], '
597
+ '"aboutEntities": ["entity_name", ...]}}\n\n'
598
+ "Rules:\n"
599
+ "- Only extract entities that appear in the text. Do not invent.\n"
600
+ "- Prefer specific over generic kinds (e.g. 'product' over 'other').\n"
601
+ "- aboutEntities lists all entity names this section is about.\n"
602
+ '- If no entities found, return {{"subjects": [], "objects": [], "aboutEntities": []}}.\n'
603
+ )
604
+
605
+
606
+ class _SemanticStage:
607
+ """LLM call for entity extraction from a document section."""
608
+
609
+ def __init__(self, model, *, subject_kinds: list[str] | None = None,
610
+ object_kinds: list[str] | None = None):
611
+ self.model = model
612
+ self.subject_kinds = subject_kinds or ["organization", "team", "role",
613
+ "legalPerson", "naturalPerson", "other"]
614
+ self.object_kinds = object_kinds or ["document", "product", "customer",
615
+ "competitor", "user", "skill",
616
+ "workflow", "tool", "agent", "indicator",
617
+ "database", "api", "code", "software",
618
+ "infrastructure", "agreement", "standard",
619
+ "epic", "project", "task", "other"]
620
+
621
+ def run(self, title: str, body: str, llm_context: str) -> dict:
622
+ system = _SEMANTIC_SYS.format(
623
+ subject_kinds=", ".join(self.subject_kinds),
624
+ object_kinds=", ".join(self.object_kinds),
625
+ )
626
+ out = self.model.complete(
627
+ system=system,
628
+ user=json.dumps({
629
+ "context": llm_context,
630
+ "section_title": title,
631
+ "section_body": body,
632
+ }),
633
+ )
634
+ raw = _json(out)
635
+ return {
636
+ "subjects": [
637
+ {"name": str(s.get("name", "")),
638
+ "subjectKind": str(s.get("subjectKind", "other"))}
639
+ for s in raw.get("subjects", [])
640
+ if isinstance(s, dict) and s.get("name")
641
+ ],
642
+ "objects": [
643
+ {"name": str(o.get("name", "")),
644
+ "objectKind": str(o.get("objectKind", "other"))}
645
+ for o in raw.get("objects", [])
646
+ if isinstance(o, dict) and o.get("name")
647
+ ],
648
+ "aboutEntities": list(raw.get("aboutEntities", [])),
649
+ }
650
+
651
+
652
+ class LLMExtractor:
653
+ """Cheap point model + large relation model, same Extractor interface as the
654
+ mock. Spans/quotes come from the deterministic segmenter, so provenance
655
+ grounding holds regardless of model strength; the point model only cleans
656
+ `content`."""
657
+
658
+ def __init__(self, point_model, relation_model, *, prompt_version: str = "v2"):
659
+ self.points = _PointStage(point_model)
660
+ self.relations = _RelationStage(relation_model)
661
+ self.version = f"{point_model.id}/{relation_model.id}@{prompt_version}"
662
+
663
+ def run(self, transcript: str, source_id: str, api: EventAPI,
664
+ *, max_utterances: int = 0, multi_source: bool = False,
665
+ domain: str | None = None) -> None:
666
+ # Document mode: markdown with ## headers → split on sections, not utterances
667
+ is_doc, doc_sections = _document_sections(transcript)
668
+ if is_doc:
669
+ self._run_document(doc_sections, source_id, api,
670
+ max_utterances=max_utterances,
671
+ domain=domain)
672
+ return
673
+
674
+ segs = list(_utterances(transcript))
675
+ if max_utterances: # exploration cap (whole-transcript relations don't scale yet)
676
+ segs = segs[:max_utterances]
677
+
678
+ # Deterministic 1:1 utterance→point. The segmenter owns identity + provenance;
679
+ # the model only supplies cleaned content, with the raw utterance as fallback,
680
+ # so a weak point model can neither drop points nor corrupt grounding.
681
+ cleaned = self.points.run([s[1] for s in segs], f"conversation:{source_id}")
682
+ ids, contents = [], []
683
+ for i, (speaker, text, span) in enumerate(segs):
684
+ c = cleaned.get(i)
685
+ content = c if (c and _overlap(c, text) >= 0.5) else text
686
+ contents.append(content)
687
+ prov = provenance(source_id, span, quote=text, speaker=speaker,
688
+ extracted_by=self.version)
689
+ # #49 Phase 2: context is deprecated — use extractedFrom for provenance
690
+ ids.append(api.add_point(content, prov, extractedFrom=source_id))
691
+
692
+ for r in self.relations.run(contents, f"conversation:{source_id}", multi_source=multi_source):
693
+ s, d = r.get("src"), r.get("dst")
694
+ if s is None or d is None or not (0 <= s < len(ids)) or not (0 <= d < len(ids)):
695
+ continue
696
+ # ground the operator in the utterance that asserted the relation (dst)
697
+ speaker, text, span = segs[d]
698
+ prov = provenance(source_id, span, quote=text, speaker=speaker,
699
+ extracted_by=self.version)
700
+ api.add_operator(r["op_type"], [ids[s], ids[d]], prov)
701
+
702
+ def _run_document(self, sections, source_id, api, *,
703
+ max_utterances: int = 0, max_points_per_batch: int = 40,
704
+ skip_on_failure: bool = False,
705
+ authored_by: str = "unknown",
706
+ domain: str | None = None):
707
+ """Document mode: extract Points per ## section, then IMPL/NAND across all."""
708
+ if max_utterances:
709
+ sections = sections[:max_utterances]
710
+
711
+ # Resolve domain pointKinds for the prompt
712
+ point_kinds = None
713
+ if domain:
714
+ try:
715
+ from tortoise.domain_loader import domain_kinds
716
+ point_kinds = domain_kinds(domain, "pointKind")
717
+ except Exception:
718
+ pass # ponytail: use defaults if loader fails
719
+
720
+ doc_stage = _DocumentPointStage(self.points.model, point_kinds=point_kinds)
721
+ all_point_ids: list[str] = []
722
+ all_contents: list[str] = []
723
+ seen_kinds: set[str] = set()
724
+ failed: list[str] = []
725
+
726
+ for title, body, span in sections:
727
+ try:
728
+ points_data = doc_stage.run(title, body, f"document:{source_id}")
729
+ except Exception:
730
+ if skip_on_failure:
731
+ failed.append(title)
732
+ continue
733
+ raise
734
+
735
+ for pd in points_data:
736
+ # ponytail: provenance carries the section span for traceability
737
+ prov = provenance(source_id, [span[0], span[1]], quote=body,
738
+ speaker="document", extracted_by=self.version)
739
+ pk = pd.get("pointKind", "statement")
740
+ seen_kinds.add(pk)
741
+ # #49 Phase 2: context is deprecated — use extractedFrom for provenance
742
+ pid = api.add_point(
743
+ pd["content"], prov,
744
+ pointKind=pk,
745
+ aboutEntities=pd["aboutEntities"],
746
+ confidence=pd["confidence"],
747
+ authoredBy=authored_by,
748
+ extractedFrom=source_id,
749
+ )
750
+ all_point_ids.append(pid)
751
+ all_contents.append(pd["content"])
752
+
753
+ # Validate extracted pointKinds against domain registry
754
+ _warn_unrecognized_kinds(seen_kinds)
755
+
756
+ if not all_point_ids:
757
+ return
758
+
759
+ # Batch relation extraction
760
+ rel_stage = _RelationStage(self.relations.model,
761
+ system_prompt=_RELATIONS_DOC_SYS)
762
+ seen_pairs: set[tuple[int, int]] = set()
763
+ for batch_start in range(0, len(all_point_ids), max_points_per_batch):
764
+ batch_ids = all_point_ids[batch_start:batch_start + max_points_per_batch]
765
+ batch_contents = all_contents[batch_start:batch_start + max_points_per_batch]
766
+ for r in rel_stage.run(batch_contents, f"document:{source_id}"):
767
+ s, d = r.get("src"), r.get("dst")
768
+ if s is None or d is None:
769
+ continue
770
+ if not (0 <= s < len(batch_ids)) or not (0 <= d < len(batch_ids)):
771
+ continue
772
+ if s == d:
773
+ continue
774
+ # NAND: canonical pair order for dedup
775
+ if r.get("op_type") == "NAND":
776
+ pair = tuple(sorted([batch_start + s, batch_start + d]))
777
+ else:
778
+ pair = (batch_start + s, batch_start + d)
779
+ if pair in seen_pairs:
780
+ continue
781
+ seen_pairs.add(pair)
782
+
783
+ try:
784
+ api.add_operator(
785
+ r["op_type"],
786
+ [all_point_ids[pair[0]], all_point_ids[pair[1]]],
787
+ provenance(source_id, None, quote="",
788
+ speaker="document",
789
+ extracted_by=self.version),
790
+ )
791
+ except Exception:
792
+ # ponytail: skip malformed operator, don't abort whole run
793
+ pass
794
+
795
+ # Store results for post-extraction reporting
796
+ self._last_result = {
797
+ "points": len(all_point_ids),
798
+ "operators": len(seen_pairs),
799
+ "sections": len(sections),
800
+ "point_ids": all_point_ids,
801
+ "failed_sections": failed,
802
+ }
803
+
804
+ # -- public API for standalone use ---------------------------------------
805
+ def extract_from_document(self, text: str, source_id: str, api: EventAPI, *,
806
+ authored_by: str = "unknown",
807
+ max_sections: int = 0,
808
+ max_points_per_batch: int = 40,
809
+ skip_on_failure: bool = False,
810
+ domain: str | None = None) -> dict:
811
+ """Extract Points + IMPL/NAND from a markdown document.
812
+
813
+ Returns: {"points": N, "operators": M, "sections": S,
814
+ "point_ids": [...], "failed_sections": [...]}
815
+ """
816
+ is_doc, doc_sections = _document_sections(text)
817
+ if not is_doc:
818
+ return {"points": 0, "operators": 0, "sections": 0,
819
+ "point_ids": [], "failed_sections": []}
820
+ self._run_document(doc_sections, source_id, api,
821
+ max_utterances=max_sections,
822
+ max_points_per_batch=max_points_per_batch,
823
+ skip_on_failure=skip_on_failure,
824
+ authored_by=authored_by,
825
+ domain=domain)
826
+ return getattr(self, "_last_result", {
827
+ "points": 0, "operators": 0, "sections": 0,
828
+ "point_ids": [], "failed_sections": [],
829
+ })
830
+
831
+ def extract_entities(self, text: str, source_id: str, api: EventAPI, *,
832
+ domain: str | None = None,
833
+ skip_on_failure: bool = False) -> dict:
834
+ """S7: Extract Subjects + Objects from a markdown document.
835
+
836
+ Emits SubjectAdded/ObjectAdded events via the API. Deduplicates by name
837
+ within a run (idempotent across runs via IngestKey in begin_ingest).
838
+
839
+ Returns: {"subjects": N, "objects": M, "entities": [names...]}
840
+ """
841
+ is_doc, sections = _document_sections(text)
842
+ if not is_doc:
843
+ return {"subjects": 0, "objects": 0, "entities": []}
844
+
845
+ # Build kind vocabularies from domain loader
846
+ subject_kinds = None
847
+ object_kinds = None
848
+ try:
849
+ from tortoise.domain_loader import known_kinds, domain_kinds
850
+ if domain:
851
+ subject_kinds = domain_kinds(domain, "subjectKind")
852
+ object_kinds = domain_kinds(domain, "objectKind")
853
+ else:
854
+ subject_kinds = list(known_kinds("subjectKind"))
855
+ object_kinds = list(known_kinds("objectKind"))
856
+ except Exception:
857
+ pass # ponytail: use defaults if domain_loader not available
858
+
859
+ stage = _SemanticStage(
860
+ self.points.model,
861
+ subject_kinds=subject_kinds,
862
+ object_kinds=object_kinds,
863
+ )
864
+ context = f"document:{source_id}"
865
+
866
+ seen_subjects: dict[str, str] = {} # name → id
867
+ seen_objects: dict[str, str] = {} # name → id
868
+ all_entity_names: set[str] = set()
869
+ n_subjects, n_objects = 0, 0
870
+
871
+ for title, body, span in sections:
872
+ try:
873
+ entities = stage.run(title, body, context)
874
+ except Exception:
875
+ if skip_on_failure:
876
+ continue
877
+ raise
878
+
879
+ for s in entities.get("subjects", []):
880
+ name = s["name"].strip()
881
+ if not name or name in seen_subjects:
882
+ continue
883
+ sid = api.add_subject(name, s["subjectKind"])
884
+ seen_subjects[name] = sid
885
+ all_entity_names.add(name)
886
+ n_subjects += 1
887
+
888
+ for o in entities.get("objects", []):
889
+ name = o["name"].strip()
890
+ if not name or name in seen_objects:
891
+ continue
892
+ oid = api.add_object(name, o["objectKind"])
893
+ seen_objects[name] = oid
894
+ all_entity_names.add(name)
895
+ n_objects += 1
896
+
897
+ for ename in entities.get("aboutEntities", []):
898
+ ename = str(ename).strip()
899
+ if ename:
900
+ all_entity_names.add(ename)
901
+
902
+ return {
903
+ "subjects": n_subjects,
904
+ "objects": n_objects,
905
+ "entities": sorted(all_entity_names),
906
+ }
907
+
908
+
909
+ # -- Module-level convenience API ------------------------------------------------
910
+
911
+ def extract_from_document(
912
+ text: str,
913
+ source_id: str,
914
+ api: EventAPI,
915
+ *,
916
+ point_model,
917
+ relation_model,
918
+ authored_by: str = "unknown",
919
+ max_sections: int = 0,
920
+ max_points_per_batch: int = 40,
921
+ skip_on_failure: bool = False,
922
+ domain: str | None = None,
923
+ ) -> dict:
924
+ """Extract Points + IMPL/NAND from a markdown document.
925
+
926
+ Returns: {"points": N, "operators": M, "sections": S,
927
+ "point_ids": [...], "failed_sections": [...]}
928
+ """
929
+ extractor = LLMExtractor(point_model, relation_model)
930
+ is_doc, doc_sections = _document_sections(text)
931
+ if not is_doc:
932
+ return {"points": 0, "operators": 0, "sections": 0,
933
+ "point_ids": [], "failed_sections": []}
934
+ extractor._run_document(
935
+ doc_sections, source_id, api,
936
+ max_utterances=max_sections,
937
+ max_points_per_batch=max_points_per_batch,
938
+ skip_on_failure=skip_on_failure,
939
+ authored_by=authored_by,
940
+ domain=domain,
941
+ )
942
+ return getattr(extractor, "_last_result", {
943
+ "points": 0, "operators": 0, "sections": 0,
944
+ "point_ids": [], "failed_sections": [],
945
+ })