dandelion-memory 1.0.0rc15__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 (232) hide show
  1. benchmarks/__init__.py +3 -0
  2. benchmarks/adapters/__init__.py +29 -0
  3. benchmarks/adapters/ablations.py +406 -0
  4. benchmarks/adapters/base.py +72 -0
  5. benchmarks/adapters/controlled/__init__.py +13 -0
  6. benchmarks/adapters/controlled/core_archival.py +115 -0
  7. benchmarks/adapters/controlled/extract_resolve.py +130 -0
  8. benchmarks/adapters/controlled/hybrid_rag.py +120 -0
  9. benchmarks/adapters/controlled/no_late_binding.py +113 -0
  10. benchmarks/adapters/dandelion.py +94 -0
  11. benchmarks/adapters/native/__init__.py +31 -0
  12. benchmarks/adapters/native/base.py +45 -0
  13. benchmarks/adapters/native/dandelion_native.py +164 -0
  14. benchmarks/adapters/native/dandelion_native_b0.py +165 -0
  15. benchmarks/adapters/native/dandelion_native_b1.py +170 -0
  16. benchmarks/adapters/native/dandelion_native_b2.py +169 -0
  17. benchmarks/adapters/native/dandelion_native_b3.py +171 -0
  18. benchmarks/adapters/native/dandelion_native_c4.py +261 -0
  19. benchmarks/adapters/native/dandelion_native_c4_1.py +281 -0
  20. benchmarks/adapters/native/dandelion_native_c4_2.py +435 -0
  21. benchmarks/adapters/native/event_evidence_b2.py +616 -0
  22. benchmarks/adapters/native/evidence_b2.py +609 -0
  23. benchmarks/adapters/native/letta_native.py +253 -0
  24. benchmarks/adapters/native/mem0_native.py +219 -0
  25. benchmarks/adapters/native/store_vector_b0.py +792 -0
  26. benchmarks/adapters/native/store_vector_b2.py +808 -0
  27. benchmarks/agent_adapter_stdio_acceptance.py +86 -0
  28. benchmarks/bootstrap_cross_stack.py +218 -0
  29. benchmarks/canonical_profile_instrumentation.py +167 -0
  30. benchmarks/canonical_public_baseline.py +288 -0
  31. benchmarks/cli.py +525 -0
  32. benchmarks/collector_public30_offline.py +1653 -0
  33. benchmarks/datasets/__init__.py +45 -0
  34. benchmarks/datasets/conversational_generator.py +238 -0
  35. benchmarks/datasets/generator.py +283 -0
  36. benchmarks/datasets/holdout_topology_generator.py +290 -0
  37. benchmarks/datasets/holdout_topology_generator_v2.py +294 -0
  38. benchmarks/datasets/multi_world.py +1643 -0
  39. benchmarks/datasets/scale_generator.py +289 -0
  40. benchmarks/datasets/schema.py +57 -0
  41. benchmarks/deep_collision_stress.py +199 -0
  42. benchmarks/evaluators/__init__.py +12 -0
  43. benchmarks/evaluators/manifest.py +142 -0
  44. benchmarks/evaluators/metrics.py +277 -0
  45. benchmarks/evaluators/runner.py +258 -0
  46. benchmarks/f1_step0/build_dev_measurement_manifest_v1.py +127 -0
  47. benchmarks/f1_step0/build_dev_measurement_manifest_v2.py +127 -0
  48. benchmarks/f1_step0/build_dev_measurement_manifest_v3.py +146 -0
  49. benchmarks/f1_step0/build_ledger.py +143 -0
  50. benchmarks/f1_step0/build_ledger_v2.py +296 -0
  51. benchmarks/f1_step0/compare_dev52_readiness_v1.py +106 -0
  52. benchmarks/f1_step0/locator_public_smoke.py +172 -0
  53. benchmarks/f1_step0/prepare_dev52_owner_v1.py +133 -0
  54. benchmarks/f1_step0/prepare_dev52_owner_v2.py +133 -0
  55. benchmarks/f1_step0/public_identity_probe.py +191 -0
  56. benchmarks/f1_step0/public_response_mapper.py +101 -0
  57. benchmarks/f1_step0/real_source_public_preflight.py +244 -0
  58. benchmarks/f1_step0/run_exact_fusion_dev_experiment_v1.py +83 -0
  59. benchmarks/f1_step0/scorer.py +110 -0
  60. benchmarks/f1_step0/source_aware_dev_measurement_v1.py +627 -0
  61. benchmarks/f1_step0/source_aware_dev_measurement_v2.py +659 -0
  62. benchmarks/f1_step0/source_aware_dev_measurement_v3.py +776 -0
  63. benchmarks/f1_step0/test_public_response_mapper.py +110 -0
  64. benchmarks/f1_step0/test_real_source_public_preflight.py +25 -0
  65. benchmarks/f1_step0/test_scorer.py +158 -0
  66. benchmarks/f1_step0/test_source_aware_dev_measurement.py +189 -0
  67. benchmarks/f1_step0/test_source_aware_dev_measurement_v2.py +263 -0
  68. benchmarks/f1_step0/test_source_aware_dev_measurement_v3.py +334 -0
  69. benchmarks/f1_step0/typed_readback_public_smoke.py +181 -0
  70. benchmarks/forensic_c4_1_dev.py +258 -0
  71. benchmarks/forensic_c4_dev.py +255 -0
  72. benchmarks/forensic_deep25_c4_1.py +478 -0
  73. benchmarks/legacy_migration_acceptance.py +29 -0
  74. benchmarks/longmemeval_actor.py +497 -0
  75. benchmarks/longmemeval_agent_judge.py +593 -0
  76. benchmarks/longmemeval_budget.py +139 -0
  77. benchmarks/longmemeval_full.py +410 -0
  78. benchmarks/longmemeval_judge.py +327 -0
  79. benchmarks/longmemeval_pilot.py +316 -0
  80. benchmarks/longmemeval_s.py +318 -0
  81. benchmarks/memory_bench.py +248 -0
  82. benchmarks/memory_formation/__init__.py +1 -0
  83. benchmarks/memory_formation/audit.py +801 -0
  84. benchmarks/memory_formation/real_audit.py +688 -0
  85. benchmarks/memory_session_acceptance.py +279 -0
  86. benchmarks/native_codex_host.py +513 -0
  87. benchmarks/owner_dense_acceptance.py +126 -0
  88. benchmarks/pilot_seeker_vault.py +266 -0
  89. benchmarks/prepare_public30_ripgrep_range_owner.py +115 -0
  90. benchmarks/profile_canonical.py +373 -0
  91. benchmarks/profile_canonical_lanes.py +405 -0
  92. benchmarks/profile_search_chunks.py +351 -0
  93. benchmarks/public_ranges_faq_proof.py +121 -0
  94. benchmarks/public_repos/build_history_scope_v3.py +330 -0
  95. benchmarks/public_repos/build_oracle.py +108 -0
  96. benchmarks/public_repos/build_oracle_v2.py +169 -0
  97. benchmarks/public_repos/build_oracle_v3.py +176 -0
  98. benchmarks/public_repos/map_public_v2.py +296 -0
  99. benchmarks/public_repos/project_prompts_v2.py +31 -0
  100. benchmarks/public_repos/project_prompts_v3.py +29 -0
  101. benchmarks/public_repos/ready_admin_v2.py +214 -0
  102. benchmarks/public_repos/score_public_v2.py +258 -0
  103. benchmarks/public_repos/test_map_public_v2.py +171 -0
  104. benchmarks/public_repos/test_public_repo_v2.py +44 -0
  105. benchmarks/public_repos/test_public_repo_v3.py +46 -0
  106. benchmarks/public_repos/test_ready_admin_v2.py +117 -0
  107. benchmarks/public_repos/test_score_public_v2.py +163 -0
  108. benchmarks/public_repos/test_wire_v2.py +292 -0
  109. benchmarks/public_repos/wire_v2.py +603 -0
  110. benchmarks/real_blocker_fix_acceptance.py +155 -0
  111. benchmarks/real_scan_rescan_acceptance.py +41 -0
  112. benchmarks/recall_v2_20k_smoke.py +112 -0
  113. benchmarks/recall_v2_e1_retrieve.py +70 -0
  114. benchmarks/recall_v2_e1_score.py +271 -0
  115. benchmarks/recall_v2_e2_prepare.py +69 -0
  116. benchmarks/recall_v2_e2_public_score.py +91 -0
  117. benchmarks/recall_v2_e2_score.py +108 -0
  118. benchmarks/recall_v2_navigation_mcp_replay.py +308 -0
  119. benchmarks/recall_v2_reader_capture.py +118 -0
  120. benchmarks/recall_v2_reader_replay.py +136 -0
  121. benchmarks/run_blind_h10_holdout.py +284 -0
  122. benchmarks/run_blind_h9_holdout.py +275 -0
  123. benchmarks/run_c4_2_nightly_scale.py +446 -0
  124. benchmarks/run_context_scale_simulation.py +189 -0
  125. benchmarks/run_conversational_bench.py +170 -0
  126. benchmarks/run_h11_evaluation.py +316 -0
  127. benchmarks/run_h11_v2_evaluation.py +431 -0
  128. benchmarks/run_native_fixed12.py +469 -0
  129. benchmarks/run_native_preflight.py +280 -0
  130. benchmarks/run_scale_stress.py +225 -0
  131. benchmarks/solanazation_brownfield_01/build_oracle.py +970 -0
  132. benchmarks/solanazation_brownfield_01/check_level_a.py +78 -0
  133. benchmarks/solanazation_brownfield_01/debug_scope.py +13 -0
  134. benchmarks/solanazation_brownfield_01/evaluate_bootstrap_02.py +570 -0
  135. benchmarks/solanazation_brownfield_01/evaluate_first_pass.py +306 -0
  136. benchmarks/solanazation_brownfield_01/generate_dryrun_report.py +222 -0
  137. benchmarks/solanazation_brownfield_01/generate_manifests.py +146 -0
  138. benchmarks/solanazation_brownfield_01/inspect_misses.py +29 -0
  139. benchmarks/solanazation_brownfield_01/run_miss_forensic.py +206 -0
  140. benchmarks/solanazation_brownfield_01/test_facts.py +15 -0
  141. benchmarks/statistics/__init__.py +15 -0
  142. benchmarks/statistics/significance.py +326 -0
  143. benchmarks/test_native_mcp_preflight.py +229 -0
  144. benchmarks/test_prepare_public30_range_owner.py +35 -0
  145. benchmarks/test_public30_source_reference.py +698 -0
  146. benchmarks/test_recall_v2_e1_reader_input.py +89 -0
  147. benchmarks/test_recall_v2_navigation_mcp_replay.py +155 -0
  148. benchmarks/test_recall_v2_reader_replay.py +41 -0
  149. dandelion/__init__.py +3 -0
  150. dandelion/__main__.py +11 -0
  151. dandelion/agent_adapter.py +2369 -0
  152. dandelion/bootstrap/__init__.py +872 -0
  153. dandelion/bootstrap/alias_policy.py +50 -0
  154. dandelion/bootstrap/authority.py +225 -0
  155. dandelion/bootstrap/canonical_history.py +412 -0
  156. dandelion/bootstrap/classifier.py +403 -0
  157. dandelion/bootstrap/component_graph.py +280 -0
  158. dandelion/bootstrap/discovery.py +279 -0
  159. dandelion/bootstrap/domain_induction.py +180 -0
  160. dandelion/bootstrap/domain_topology.py +673 -0
  161. dandelion/bootstrap/evidence_envelope.py +132 -0
  162. dandelion/bootstrap/extractors/base.py +171 -0
  163. dandelion/bootstrap/extractors/exact.py +1234 -0
  164. dandelion/bootstrap/extractors/generic.py +100 -0
  165. dandelion/bootstrap/extractors/git_temporal.py +111 -0
  166. dandelion/bootstrap/extractors/registry.py +345 -0
  167. dandelion/bootstrap/extractors/relations.py +89 -0
  168. dandelion/bootstrap/extractors/semantic.py +424 -0
  169. dandelion/bootstrap/extractors/status.py +218 -0
  170. dandelion/bootstrap/git_sweeper.py +135 -0
  171. dandelion/bootstrap/manifest.py +246 -0
  172. dandelion/bootstrap/quarantine.py +264 -0
  173. dandelion/bootstrap/report.py +259 -0
  174. dandelion/bootstrap/root_resolver.py +221 -0
  175. dandelion/bootstrap/tech_profiler.py +125 -0
  176. dandelion/bootstrap/topology.py +75 -0
  177. dandelion/bootstrap/topology_index.py +110 -0
  178. dandelion/bootstrap/transaction.py +315 -0
  179. dandelion/canonical_bootstrap.py +257 -0
  180. dandelion/canonical_memory.py +4130 -0
  181. dandelion/captured_input.py +295 -0
  182. dandelion/cli.py +767 -0
  183. dandelion/config.py +40 -0
  184. dandelion/derived_index.py +745 -0
  185. dandelion/domains.py +706 -0
  186. dandelion/embedder.py +229 -0
  187. dandelion/event_evidence.py +571 -0
  188. dandelion/evidence.py +812 -0
  189. dandelion/evidence_response.py +453 -0
  190. dandelion/evidence_workspace.py +2360 -0
  191. dandelion/exact_context.py +129 -0
  192. dandelion/hydrator.py +124 -0
  193. dandelion/inspector.py +442 -0
  194. dandelion/inspector_assets/dandelion-mark.svg +33 -0
  195. dandelion/inspector_assets/dandelion_graph.js +361 -0
  196. dandelion/inspector_assets/inspector.css +223 -0
  197. dandelion/inspector_assets/inspector.html +135 -0
  198. dandelion/inspector_assets/inspector.js +1059 -0
  199. dandelion/legacy_import.py +431 -0
  200. dandelion/live_source_grants.py +133 -0
  201. dandelion/local_owner.py +114 -0
  202. dandelion/memory_client.py +252 -0
  203. dandelion/memory_contract.py +107 -0
  204. dandelion/memory_owner.py +560 -0
  205. dandelion/reader_providers.py +118 -0
  206. dandelion/recall_v2.py +767 -0
  207. dandelion/reconciler.py +219 -0
  208. dandelion/request_budget.py +125 -0
  209. dandelion/retained_basis.py +223 -0
  210. dandelion/retrieval.py +485 -0
  211. dandelion/router.py +405 -0
  212. dandelion/search_terms.py +53 -0
  213. dandelion/security.py +124 -0
  214. dandelion/server.py +810 -0
  215. dandelion/source_content_fts.py +219 -0
  216. dandelion/source_delivery.py +89 -0
  217. dandelion/source_history.py +241 -0
  218. dandelion/source_identity.py +88 -0
  219. dandelion/source_navigator.py +5 -0
  220. dandelion/source_reader.py +444 -0
  221. dandelion/source_references.py +379 -0
  222. dandelion/source_sections.py +265 -0
  223. dandelion/store_kv.py +684 -0
  224. dandelion/store_vector.py +1289 -0
  225. dandelion/studio.py +325 -0
  226. dandelion/wal.py +227 -0
  227. dandelion_memory-1.0.0rc15.dist-info/METADATA +48 -0
  228. dandelion_memory-1.0.0rc15.dist-info/RECORD +232 -0
  229. dandelion_memory-1.0.0rc15.dist-info/WHEEL +5 -0
  230. dandelion_memory-1.0.0rc15.dist-info/entry_points.txt +5 -0
  231. dandelion_memory-1.0.0rc15.dist-info/licenses/LICENSE +21 -0
  232. dandelion_memory-1.0.0rc15.dist-info/top_level.txt +2 -0
@@ -0,0 +1,100 @@
1
+ """Mandatory Generic Fallback Extractor (BOOTSTRAP-02 Section 9).
2
+
3
+ Gracefully processes any unknown textual format or source file lacking a specialized
4
+ extractor. Guarantees that unknown information is structurally indexed and semantically
5
+ searchable rather than invisible.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from pathlib import Path
12
+ from typing import Optional
13
+
14
+ from dandelion.bootstrap.discovery import DiscoveredFile
15
+ from dandelion.bootstrap.extractors.base import SemanticMemoryRecord
16
+
17
+ # Regex patterns for structural cues across programming languages and formats
18
+ HEADING_PATTERN = re.compile(r'^(?:#{1,6}\s+|\[[\w\s.-]+\]|(?:class|struct|interface|enum|func|def|fun|fn|pub fn)\s+([a-zA-Z0-9_]+))', re.MULTILINE)
19
+ IMPORT_PATTERN = re.compile(r'^(?:import|from|require|include|use|extends|package)\s+["\']?([a-zA-Z0-9_./-]+)["\']?', re.MULTILINE)
20
+ ASSIGNMENT_PATTERN = re.compile(r'^\s*(?:const|let|var|val)?\s*([A-Za-z0-9_]+)\s*[:=]\s*["\']?([^"\';\n\r]+)["\']?', re.MULTILINE)
21
+
22
+
23
+ class GenericFallbackExtractor:
24
+ """Universal structural parser and semantic chunker for arbitrary text and code."""
25
+
26
+ def supports(self, file: DiscoveredFile) -> float:
27
+ """Fallback supports any text file."""
28
+ return 0.50 if file.is_text else 0.0
29
+
30
+ def extract_semantic(
31
+ self,
32
+ file: DiscoveredFile,
33
+ project_name: str,
34
+ target_domain: Optional[str] = None,
35
+ chunk_size: int = 1200,
36
+ chunk_overlap: int = 200,
37
+ ) -> list[SemanticMemoryRecord]:
38
+ records: list[SemanticMemoryRecord] = []
39
+ if not file.is_text or not file.abs_path.exists():
40
+ return records
41
+
42
+ try:
43
+ text = file.abs_path.read_text(encoding="utf-8", errors="ignore")
44
+ except Exception:
45
+ return records
46
+
47
+ if not text.strip():
48
+ return records
49
+
50
+ norm_path = file.rel_path.replace("\\", "/")
51
+ parts = norm_path.split("/")
52
+ subsystem = parts[0] if len(parts) > 1 else "root"
53
+ domain = target_domain or f"{project_name}.{subsystem}"
54
+
55
+ # 1. Structural Scan (Headings, Imports, Key Declarations)
56
+ imports = IMPORT_PATTERN.findall(text)
57
+ headings = HEADING_PATTERN.findall(text)
58
+
59
+ # 2. Window Chunking with Line Boundaries
60
+ lines = text.splitlines(keepends=True)
61
+ total_lines = len(lines)
62
+
63
+ current_chunk_lines: list[str] = []
64
+ current_char_count = 0
65
+ chunk_start_line = 1
66
+
67
+ for line_idx, line in enumerate(lines, start=1):
68
+ current_chunk_lines.append(line)
69
+ current_char_count += len(line)
70
+
71
+ # Flush when exceeding window size or at logical heading boundary
72
+ is_heading = bool(HEADING_PATTERN.match(line.strip()))
73
+ if (current_char_count >= chunk_size) or (is_heading and current_char_count >= chunk_size // 2) or (line_idx == total_lines):
74
+ chunk_text = "".join(current_chunk_lines).strip()
75
+ if chunk_text:
76
+ chunk_end_line = line_idx
77
+ source_id = f"{norm_path}:{chunk_start_line}-{chunk_end_line}"
78
+
79
+ # Construct high-relevance semantic template
80
+ header_meta = f"File: {norm_path} ({file.role.value})"
81
+ if imports and chunk_start_line <= 30:
82
+ header_meta += f" | References: {', '.join(imports[:4])}"
83
+
84
+ template = f"{project_name} {header_meta}:\n{chunk_text}"
85
+
86
+ records.append(SemanticMemoryRecord(
87
+ source_id=source_id,
88
+ source_path=file.rel_path,
89
+ domain=domain,
90
+ template=template,
91
+ line_range=(chunk_start_line, chunk_end_line),
92
+ ))
93
+
94
+ # Advance with overlap
95
+ overlap_lines = max(1, chunk_overlap // 50)
96
+ current_chunk_lines = current_chunk_lines[-overlap_lines:] if len(current_chunk_lines) > overlap_lines else []
97
+ current_char_count = sum(len(l) for l in current_chunk_lines)
98
+ chunk_start_line = max(1, line_idx - len(current_chunk_lines) + 1)
99
+
100
+ return records
@@ -0,0 +1,111 @@
1
+ """Staged Git history and temporal revision extractor (BOOTSTRAP-01).
2
+
3
+ Follows staged strategy:
4
+ 1. Fast pass: Current state + release tags + selective history of target config/ADR files
5
+ via `git log -- <relevant paths>`.
6
+ 2. Deep pass (--deep-history): Complete historical commit reconstruction on demand.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import subprocess
12
+ from pathlib import Path
13
+ from dataclasses import dataclass, field
14
+ from typing import Optional
15
+
16
+
17
+ @dataclass
18
+ class GitCommitRecord:
19
+ """Historical commit modifying a relevant configuration or ADR file."""
20
+ commit_sha: str
21
+ author: str
22
+ timestamp: float
23
+ subject: str
24
+ file_path: str
25
+
26
+
27
+ @dataclass
28
+ class GitTemporalReport:
29
+ """Collected temporal history from Git repository."""
30
+ is_git_repo: bool
31
+ current_head: Optional[str] = None
32
+ tags: list[str] = field(default_factory=list)
33
+ file_revisions: dict[str, list[GitCommitRecord]] = field(default_factory=dict)
34
+
35
+
36
+ def run_git_cmd(repo_root: Path, args: list[str]) -> Optional[str]:
37
+ """Execute a git command in repository root safely."""
38
+ try:
39
+ res = subprocess.run(
40
+ ["git"] + args,
41
+ cwd=str(repo_root),
42
+ capture_output=True,
43
+ text=True,
44
+ check=True,
45
+ timeout=15,
46
+ )
47
+ return res.stdout.strip()
48
+ except Exception:
49
+ return None
50
+
51
+
52
+ def extract_git_temporal(
53
+ repo_root: Path,
54
+ relevant_files: list[str],
55
+ deep_history: bool = False,
56
+ ) -> GitTemporalReport:
57
+ """Extract selective Git history for relevant configuration and ADR paths."""
58
+ git_dir = repo_root / ".git"
59
+ if not git_dir.exists():
60
+ return GitTemporalReport(is_git_repo=False)
61
+
62
+ head_sha = run_git_cmd(repo_root, ["rev-parse", "HEAD"])
63
+ raw_tags = run_git_cmd(repo_root, ["tag", "-l", "--sort=-creatordate"])
64
+ tags = [t.strip() for t in raw_tags.splitlines() if t.strip()] if raw_tags else []
65
+
66
+ report = GitTemporalReport(
67
+ is_git_repo=True,
68
+ current_head=head_sha,
69
+ tags=tags,
70
+ )
71
+
72
+ # Selective history pass: run git log strictly for target relevant files!
73
+ # Avoids arbitrary last-N commit slicing across unrelated code files.
74
+ for rel_path in relevant_files:
75
+ # Use --follow to track renames across file history
76
+ cmd = [
77
+ "log",
78
+ "--follow",
79
+ "--format=%H|%an|%ct|%s",
80
+ "--",
81
+ rel_path,
82
+ ]
83
+ if not deep_history:
84
+ # In fast pass, bound the per-file history to top 20 modifications
85
+ cmd = ["log", "-n", "20", "--follow", "--format=%H|%an|%ct|%s", "--", rel_path]
86
+
87
+ log_out = run_git_cmd(repo_root, cmd)
88
+ if not log_out:
89
+ continue
90
+
91
+ records: list[GitCommitRecord] = []
92
+ for line in log_out.splitlines():
93
+ parts = line.strip().split("|", maxsplit=3)
94
+ if len(parts) == 4:
95
+ sha, author, ts_str, subj = parts
96
+ try:
97
+ ts = float(ts_str)
98
+ except ValueError:
99
+ ts = 0.0
100
+ records.append(GitCommitRecord(
101
+ commit_sha=sha,
102
+ author=author,
103
+ timestamp=ts,
104
+ subject=subj,
105
+ file_path=rel_path,
106
+ ))
107
+
108
+ if records:
109
+ report.file_revisions[rel_path] = records
110
+
111
+ return report
@@ -0,0 +1,345 @@
1
+ """Universal Extractor Registry (BOOTSTRAP-02 Section 8).
2
+
3
+ Orchestrates specialized extractors and mandatory generic fallback:
4
+ 1. Exact Fact Extraction (configs, manifests, descriptors)
5
+ 2. Semantic Markdown & Decision Extraction (docs, ADRs)
6
+ 3. Epistemic Status Extraction (cross-cutting capabilities)
7
+ 4. Generic Fallback Extraction (arbitrary code, unknown text formats)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import hashlib
14
+ from typing import Optional, TYPE_CHECKING
15
+
16
+ from dandelion.bootstrap.authority import (
17
+ AuthorityRecord,
18
+ ContextAwareAuthorityResolver,
19
+ EpistemicTrustClass,
20
+ )
21
+ from dandelion.bootstrap.discovery import DiscoveredFile, ProjectDiscoveryReport
22
+ from dandelion.bootstrap.evidence_envelope import EvidenceEnvelope, EvidenceLocatorKind, EvidencePlane
23
+ from dandelion.bootstrap.extractors.base import (
24
+ ExactFactRecord,
25
+ SemanticMemoryRecord,
26
+ StatusEvidenceRecord,
27
+ )
28
+ from dandelion.bootstrap.extractors.exact import extract_exact_facts
29
+ from dandelion.bootstrap.extractors.generic import GenericFallbackExtractor
30
+ from dandelion.bootstrap.extractors.relations import extract_cross_file_relations
31
+ from dandelion.bootstrap.extractors.semantic import extract_semantic_memories
32
+ from dandelion.bootstrap.extractors.status import StatusExtractor
33
+
34
+ if TYPE_CHECKING:
35
+ from dandelion.bootstrap.component_graph import ComponentGraph
36
+ from dandelion.bootstrap.topology_index import TopologyIndex
37
+
38
+
39
+ def _source_component_for_path(
40
+ component_graph: "ComponentGraph",
41
+ source_path: str,
42
+ ) -> tuple[Optional[str], str]:
43
+ """Resolve an artifact owner from graph paths, never from a basename guess."""
44
+ normalized_path = source_path.replace("\\", "/").strip("/")
45
+ candidates = [
46
+ node
47
+ for node in component_graph.nodes.values()
48
+ if node.rel_path
49
+ and (
50
+ normalized_path == node.rel_path.strip("/")
51
+ or normalized_path.startswith(node.rel_path.strip("/") + "/")
52
+ )
53
+ ]
54
+ if candidates:
55
+ owner = max(candidates, key=lambda node: len(node.rel_path))
56
+ return (
57
+ owner.id,
58
+ "SOURCE_COMPONENT_UNRESOLVED"
59
+ if owner.resolution != "RESOLVED"
60
+ else "NONE",
61
+ )
62
+ if "/" not in normalized_path and component_graph.root_id in component_graph.nodes:
63
+ return component_graph.root_id, "NONE"
64
+ return None, "SOURCE_COMPONENT_UNRESOLVED"
65
+
66
+
67
+ def _explicit_subject_components(
68
+ evidence_text: str,
69
+ component_graph: "ComponentGraph",
70
+ ) -> list[str]:
71
+ """Find only normalized repository-relative component paths in prose."""
72
+ normalized_text = evidence_text.replace("\\", "/").lower()
73
+ matched: list[str] = []
74
+ for node in component_graph.nodes.values():
75
+ rel_path = node.rel_path.strip("/").lower()
76
+ # A bare component name is an ambiguous basename token in prose. Only
77
+ # a multi-segment repository-relative path can bind a documentary claim.
78
+ if "/" not in rel_path:
79
+ continue
80
+ pattern = rf"(?<![a-z0-9_.-]){re.escape(rel_path)}(?![a-z0-9_.-])"
81
+ if re.search(pattern, normalized_text):
82
+ matched.append(node.id)
83
+ return sorted(set(matched))
84
+
85
+
86
+ def _bind_status_record(
87
+ record: StatusEvidenceRecord,
88
+ file: DiscoveredFile,
89
+ component_graph: Optional["ComponentGraph"],
90
+ ) -> None:
91
+ """Attach conservative source/subject bindings to one status evidence unit."""
92
+ record.evidence_role = file.role.value
93
+ record.evidence_authority = getattr(file.authority, "value", "NONE")
94
+ if component_graph is None:
95
+ record.binding_ambiguity = "NO_COMPONENT_GRAPH"
96
+ return
97
+
98
+ source_component, source_ambiguity = _source_component_for_path(
99
+ component_graph,
100
+ record.source_path,
101
+ )
102
+ record.source_component = source_component
103
+ if source_ambiguity != "NONE":
104
+ record.binding_ambiguity = source_ambiguity
105
+ return
106
+
107
+ # Artifact-role evidence proves the state of the owning component, without
108
+ # extending that assertion to graph neighbours or named capabilities.
109
+ if record.is_corroborated:
110
+ record.subject_component = source_component
111
+ record.binding_ambiguity = "NONE"
112
+ return
113
+
114
+ explicit_subjects = _explicit_subject_components(record.evidence_text, component_graph)
115
+ if len(explicit_subjects) == 1:
116
+ record.subject_component = explicit_subjects[0]
117
+ record.binding_ambiguity = "NONE"
118
+ elif len(explicit_subjects) > 1:
119
+ record.binding_ambiguity = "AMBIGUOUS_SUBJECT"
120
+ else:
121
+ record.binding_ambiguity = "UNRESOLVED_SUBJECT"
122
+
123
+
124
+ def _status_locator_kind(record: StatusEvidenceRecord, line_number: Optional[int]) -> EvidenceLocatorKind:
125
+ """Only coarse artifact-presence rows may use a digest-only locator."""
126
+ if line_number is not None:
127
+ return EvidenceLocatorKind.LINE_SPAN
128
+ if (
129
+ ".claim_" not in record.entity
130
+ and record.is_corroborated
131
+ and record.claim_predicate in {
132
+ "implementation_present", "test_present", "build_configured", "deployment_configured",
133
+ }
134
+ ):
135
+ return EvidenceLocatorKind.FILE_DIGEST
136
+ return EvidenceLocatorKind.UNLOCATED
137
+
138
+
139
+ class ExtractorRegistry:
140
+ """Unified coordinator for all extraction pipelines."""
141
+
142
+ def __init__(self) -> None:
143
+ self.status_extractor = StatusExtractor()
144
+ self.generic_extractor = GenericFallbackExtractor()
145
+
146
+ def run_exact_extraction(
147
+ self,
148
+ report: ProjectDiscoveryReport,
149
+ project_name: str,
150
+ ) -> list[AuthorityRecord]:
151
+ """Extract deterministic exact facts from all relevant files."""
152
+ records = extract_exact_facts(report.all_discovered, project_name=project_name)
153
+ files = {item.rel_path: item for item in report.all_discovered}
154
+ for record in records:
155
+ source = files.get(record.source_file)
156
+ child_sources = sorted(
157
+ (item for path, item in files.items() if path.startswith(record.source_file.rstrip("/") + "/")),
158
+ key=lambda item: item.rel_path,
159
+ )
160
+ artifact_hash = source.content_hash if source else hashlib.sha256(
161
+ "".join(item.content_hash for item in child_sources).encode("ascii")
162
+ ).hexdigest() if child_sources else ""
163
+ if source:
164
+ record.source_authority = ContextAwareAuthorityResolver.resolve_authority(
165
+ fact_type=record.key,
166
+ file_role=source.role.value,
167
+ rel_path=record.source_file,
168
+ default_auth=record.source_authority,
169
+ )
170
+ record.epistemic_class = (
171
+ EpistemicTrustClass.AUTHORITATIVE
172
+ if record.source_authority.rank >= 4.5
173
+ else EpistemicTrustClass.DERIVED
174
+ )
175
+ record.provenance = EvidenceEnvelope.create(
176
+ plane=EvidencePlane.EXACT,
177
+ source_id=(
178
+ "exact:"
179
+ + hashlib.sha256(
180
+ f"{record.key}\x1f{record.source_file}\x1f{record.line_number}\x1f{artifact_hash}".encode("utf-8")
181
+ ).hexdigest()[:20]
182
+ ),
183
+ source_path=record.source_file,
184
+ artifact_hash=artifact_hash,
185
+ source_revision=report.git_head,
186
+ authority=record.source_authority.value,
187
+ confidence=record.extraction_confidence,
188
+ security_class=record.security_class,
189
+ extractor_id="exact-registry",
190
+ line_start=record.line_number,
191
+ line_end=record.line_number,
192
+ locator_kind=(
193
+ EvidenceLocatorKind.FILE_DIGEST
194
+ if source and record.line_number is None
195
+ and str(record.value).replace("\\", "/") == record.source_file.replace("\\", "/")
196
+ else None
197
+ ),
198
+ )
199
+ return records
200
+
201
+ def run_status_extraction(
202
+ self,
203
+ report: ProjectDiscoveryReport,
204
+ project_name: str,
205
+ topology_index: Optional[TopologyIndex] = None,
206
+ component_graph: Optional["ComponentGraph"] = None,
207
+ ) -> tuple[list[StatusEvidenceRecord], list[SemanticMemoryRecord]]:
208
+ """Extract epistemic status evidence across docs and source files."""
209
+ all_status: list[StatusEvidenceRecord] = []
210
+ files = {item.rel_path: item for item in report.all_discovered}
211
+ for f in report.all_discovered:
212
+ if self.status_extractor.supports(f) > 0:
213
+ extracted = self.status_extractor.extract_status_evidence(f, project_name)
214
+ for record in extracted:
215
+ _bind_status_record(record, f, component_graph)
216
+ line_start, line_end = record.line_range or (None, None)
217
+ line_number = line_start
218
+ record.provenance = EvidenceEnvelope.create(
219
+ plane=EvidencePlane.STATUS,
220
+ source_id=f"status-evidence:{record.entity}",
221
+ source_path=record.source_path,
222
+ artifact_hash=f.content_hash,
223
+ source_revision=report.git_head,
224
+ authority=f.authority.value,
225
+ confidence=record.confidence,
226
+ extractor_id="status",
227
+ line_start=line_start,
228
+ line_end=line_end,
229
+ locator_kind=_status_locator_kind(record, line_number),
230
+ )
231
+ all_status.extend(extracted)
232
+
233
+ # Convert to semantic memories for retrieval
234
+ status_memories = self.status_extractor.to_semantic_memories(
235
+ all_status,
236
+ project_name,
237
+ topology_index=topology_index,
238
+ )
239
+ return all_status, status_memories
240
+
241
+ def run_semantic_extraction(
242
+ self,
243
+ report: ProjectDiscoveryReport,
244
+ project_name: str,
245
+ topology_index: Optional[TopologyIndex] = None,
246
+ ) -> list[SemanticMemoryRecord]:
247
+ """Extract episodic semantic memories from documentation, sources, and generic text."""
248
+ memories: list[SemanticMemoryRecord] = []
249
+ processed_paths: set[str] = set()
250
+ files = {item.rel_path: item for item in report.all_discovered}
251
+
252
+ # 1. Specialized Markdown / Documentation Extractor
253
+ doc_files = report.docs + report.adrs
254
+ doc_memories = extract_semantic_memories(doc_files, project_name=project_name)
255
+ for m in doc_memories:
256
+ source = files.get(m.source_path)
257
+ record = SemanticMemoryRecord(
258
+ source_id=m.source_id,
259
+ source_path=m.source_path,
260
+ domain=topology_index.binding_for(m.source_path).domain if topology_index else m.domain,
261
+ template=m.template,
262
+ supersedes=m.supersedes,
263
+ security_class=getattr(m, "security_class", "PUBLIC"),
264
+ memory_kind=getattr(m, "memory_kind", "semantic"),
265
+ line_range=getattr(m, "line_range", None),
266
+ referenced_facts=list(m.referenced_facts),
267
+ )
268
+ record.provenance = EvidenceEnvelope.create(
269
+ plane=EvidencePlane.SEMANTIC,
270
+ source_id=record.source_id,
271
+ source_path=record.source_path,
272
+ artifact_hash=source.content_hash if source else "",
273
+ source_revision=report.git_head,
274
+ authority=source.authority.value if source else "NONE",
275
+ confidence=0.95,
276
+ security_class=record.security_class,
277
+ extractor_id="semantic-document",
278
+ line_start=record.line_range[0] if record.line_range else None,
279
+ line_end=record.line_range[1] if record.line_range else None,
280
+ )
281
+ memories.append(record)
282
+ processed_paths.add(m.source_path)
283
+
284
+ # 2. Generic Fallback on Source Code, Unknown Text, and structured
285
+ # configuration. Typed extractors preserve scalar facts; literal
286
+ # chunks preserve comments, arrays, and other source text.
287
+ # (Exclude assets, binaries, and already processed docs)
288
+ fallback_targets = [
289
+ f for f in report.all_discovered
290
+ if f.is_text
291
+ and f.rel_path not in processed_paths
292
+ and f.role.value in ("source_code", "test", "unknown_text", "structured_config",
293
+ "project_descriptor", "build_config")
294
+ ]
295
+
296
+ for f in fallback_targets:
297
+ if topology_index:
298
+ domain = topology_index.binding_for(f.rel_path).domain
299
+ else:
300
+ parts = f.rel_path.replace("\\", "/").split("/")
301
+ comp = parts[0] if len(parts) > 1 else "root"
302
+ domain = f"{project_name}.{comp}"
303
+
304
+ gen_records = self.generic_extractor.extract_semantic(
305
+ file=f,
306
+ project_name=project_name,
307
+ target_domain=domain,
308
+ )
309
+ for record in gen_records:
310
+ record.provenance = EvidenceEnvelope.create(
311
+ plane=EvidencePlane.SEMANTIC,
312
+ source_id=record.source_id,
313
+ source_path=record.source_path,
314
+ artifact_hash=f.content_hash,
315
+ source_revision=report.git_head,
316
+ authority=f.authority.value,
317
+ confidence=self.generic_extractor.supports(f),
318
+ security_class=record.security_class,
319
+ extractor_id="generic-fallback",
320
+ line_start=record.line_range[0] if record.line_range else None,
321
+ line_end=record.line_range[1] if record.line_range else None,
322
+ )
323
+ memories.extend(gen_records)
324
+
325
+ # 3. Cross-file relations are a separate evidence unit. Keeping them
326
+ # independent prevents a large source chunk from hiding the explicit
327
+ # component boundary that a query is trying to retrieve.
328
+ for record in extract_cross_file_relations(report, project_name):
329
+ source = files.get(record.source_path)
330
+ if topology_index:
331
+ record.domain = topology_index.binding_for(record.source_path).domain
332
+ record.provenance = EvidenceEnvelope.create(
333
+ plane=EvidencePlane.SEMANTIC,
334
+ source_id=record.source_id,
335
+ source_path=record.source_path,
336
+ artifact_hash=source.content_hash if source else "",
337
+ source_revision=report.git_head,
338
+ authority=source.authority.value if source else "NONE",
339
+ confidence=1.0,
340
+ security_class=record.security_class,
341
+ extractor_id="cross-file-relation",
342
+ )
343
+ memories.append(record)
344
+
345
+ return memories
@@ -0,0 +1,89 @@
1
+ """Grounded cross-file relation extraction for brownfield repositories.
2
+
3
+ Only explicit path references that resolve to another discovered artifact are
4
+ emitted. The extractor deliberately does not infer runtime behaviour from
5
+ directory names or tune relations to an evaluation corpus.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import posixpath
12
+ import re
13
+
14
+ from dandelion.bootstrap.discovery import DiscoveredFile, ProjectDiscoveryReport
15
+ from dandelion.bootstrap.extractors.base import SemanticMemoryRecord
16
+
17
+
18
+ _PATH_REFERENCE_RE = re.compile(
19
+ r"(?:res://|(?<![\w.-])(?:\.{1,2}/)?)[A-Za-z0-9_@./-]+"
20
+ r"\.(?:py|gd|ts|tsx|js|jsx|kt|kts|java|go|rs|cs|cpp|c|h|hpp|rb|php|"
21
+ r"swift|scala|vue|svelte|json|ya?ml|toml|md|sql|proto)\b",
22
+ re.IGNORECASE,
23
+ )
24
+
25
+
26
+ def _resolve_reference(source_path: str, raw_reference: str, known: set[str]) -> str | None:
27
+ reference = raw_reference.replace("\\", "/")
28
+ if reference.startswith("res://"):
29
+ candidate = reference[6:]
30
+ elif reference.startswith("./") or reference.startswith("../"):
31
+ candidate = posixpath.normpath(posixpath.join(posixpath.dirname(source_path), reference))
32
+ else:
33
+ candidate = posixpath.normpath(reference.lstrip("/"))
34
+ if candidate not in known:
35
+ candidate = posixpath.normpath(posixpath.join(posixpath.dirname(source_path), reference))
36
+ return candidate if candidate in known and candidate != source_path else None
37
+
38
+
39
+ def _relation_phrase(source: DiscoveredFile, target: DiscoveredFile) -> str:
40
+ if source.role.value == "test":
41
+ return "test artifact explicitly references"
42
+ if source.role.value == "documentation":
43
+ return "documentation explicitly references"
44
+ if source.role.value == "source_code" and target.role.value == "source_code":
45
+ return "source artifact explicitly depends on"
46
+ return "artifact explicitly references"
47
+
48
+
49
+ def extract_cross_file_relations(
50
+ report: ProjectDiscoveryReport,
51
+ project_name: str,
52
+ ) -> list[SemanticMemoryRecord]:
53
+ """Create one evidence-backed memory per unique resolved file relation."""
54
+ files = {item.rel_path.replace("\\", "/"): item for item in report.all_discovered}
55
+ known = set(files)
56
+ records: list[SemanticMemoryRecord] = []
57
+ seen: set[tuple[str, str]] = set()
58
+
59
+ for source_path, source in sorted(files.items()):
60
+ if not source.is_text or not source.abs_path.exists():
61
+ continue
62
+ try:
63
+ content = source.abs_path.read_text(encoding="utf-8", errors="ignore")
64
+ except OSError:
65
+ continue
66
+ for match in _PATH_REFERENCE_RE.finditer(content):
67
+ target_path = _resolve_reference(source_path, match.group(0), known)
68
+ if target_path is None or (source_path, target_path) in seen:
69
+ continue
70
+ seen.add((source_path, target_path))
71
+ target = files[target_path]
72
+ source_component = source_path.split("/", 1)[0] if "/" in source_path else "root"
73
+ target_component = target_path.split("/", 1)[0] if "/" in target_path else "root"
74
+ phrase = _relation_phrase(source, target)
75
+ digest = hashlib.sha256(f"{source_path}\x1f{target_path}".encode("utf-8")).hexdigest()[:16]
76
+ records.append(SemanticMemoryRecord(
77
+ source_id=f"relation:{digest}",
78
+ source_path=source.rel_path,
79
+ domain=f"{project_name}.relations",
80
+ template=(
81
+ f"Cross-file relation in {project_name}: {source_path} ({source.role.value}, "
82
+ f"component {source_component}) {phrase} {target_path} ({target.role.value}, "
83
+ f"component {target_component}). Evidence is the explicit path reference "
84
+ f"{match.group(0)!r} in {source_path}."
85
+ ),
86
+ memory_kind="relation",
87
+ line_range=(content.count("\n", 0, match.start()) + 1, content.count("\n", 0, match.end()) + 1),
88
+ ))
89
+ return records