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,176 @@
1
+ #!/usr/bin/env python3
2
+ """Materialize v3 from the reviewed v2 base plus preregistered replacements."""
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import re
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from build_oracle_v2 import CLONES, git, verify_proof
12
+
13
+ HERE = Path(__file__).parent
14
+
15
+
16
+ def verify_v3_proof(repo, proof):
17
+ if proof["type"] == "commit_diff":
18
+ commit = git(repo, "rev-parse", f"{proof['commit']}^{{commit}}")
19
+ if commit != proof["commit"]:
20
+ raise ValueError(f"commit diff revision mismatch: {proof['commit']}")
21
+ diff = git(repo, "show", "--format=", "--unified=0", proof["commit"], "--", proof["path"])
22
+ old_line = new_line = 0
23
+ for line in diff.splitlines():
24
+ hunk = re.match(r"@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@", line)
25
+ if hunk:
26
+ old_line = int(hunk.group(1))
27
+ new_line = int(hunk.group(2))
28
+ elif line.startswith("-") and not line.startswith("---"):
29
+ if proof.get("side", "deleted") == "deleted" and proof["quote"] in line[1:]:
30
+ return {"commit": commit, "path": proof["path"], "field": proof["field"], "line": old_line}
31
+ old_line += 1
32
+ elif line.startswith("+") and not line.startswith("+++"):
33
+ if proof.get("side", "deleted") == "added" and proof["quote"] in line[1:]:
34
+ return {"commit": commit, "path": proof["path"], "field": proof["field"], "line": new_line}
35
+ new_line += 1
36
+ elif line.startswith(" "):
37
+ old_line += 1
38
+ new_line += 1
39
+ raise ValueError(f"deleted source line not present in diff: {proof['quote']}")
40
+ if proof["type"] == "go_mod_directive_absent":
41
+ commit = git(repo, "rev-parse", f"{proof['commit']}^{{commit}}")
42
+ if commit != proof["commit"]:
43
+ raise ValueError("go.mod absence commit mismatch")
44
+ source = git(repo, "show", f"{proof['commit']}:{proof['path']}")
45
+ if re.search(r"(?m)^\s*toolchain\s+\S+", source):
46
+ raise ValueError("toolchain directive exists; bounded absence is false")
47
+ m = re.search(r"(?m)^go\s+(\S+)", source)
48
+ if not m:
49
+ raise ValueError("go.mod missing go directive; cannot identify file scope")
50
+ line = source[:m.start()].count("\n") + 1
51
+ return {"commit": commit, "path": proof["path"], "field": "whole-file toolchain directive absence", "line": line}
52
+ evidence = verify_proof(repo, proof)
53
+ if proof["type"] == "toml_absent" and proof["field"] == "workspace.members":
54
+ source = git(repo, "show", f"{proof['commit']}:{proof['path']}")
55
+ match = re.search(r"(?m)^\s*members\s*=\s*\[", source)
56
+ if not match:
57
+ raise ValueError("workspace.members source locator missing")
58
+ evidence["line"] = source[:match.start()].count("\n") + 1
59
+ return evidence
60
+
61
+
62
+ def main():
63
+ ap = argparse.ArgumentParser()
64
+ ap.add_argument("--oracle-output", type=Path, default=HERE / "oracle_dev_v3.json")
65
+ ap.add_argument("--questions-output", type=Path, default=HERE / "questions_dev_v3.json")
66
+ args = ap.parse_args()
67
+ spec = json.loads((HERE / "manifest_v3.json").read_text(encoding="utf-8"))
68
+ for base_name, expected in spec["base_sha256"].items():
69
+ actual = hashlib.sha256((HERE / base_name).read_bytes()).hexdigest()
70
+ if actual != expected:
71
+ raise ValueError(f"base artifact SHA-256 mismatch: {base_name}")
72
+ base_manifest = json.loads((HERE / spec["base_manifest"]).read_text(encoding="utf-8"))
73
+ questions = json.loads((HERE / spec["base_questions"]).read_text(encoding="utf-8"))
74
+ facts_by_id = {row["id"]: row for row in base_manifest["facts"]}
75
+ q_by_id = {row["prompt_id"]: row for row in questions["questions"]}
76
+ repo_heads = {row["id"]: row["commit"] for row in base_manifest["repositories"]}
77
+ for repo_spec in base_manifest["repositories"]:
78
+ repo = CLONES / repo_spec["id"]
79
+ if git(repo, "rev-parse", "HEAD") != repo_spec["commit"]:
80
+ raise ValueError(f"pinned HEAD mismatch: {repo_spec['id']}")
81
+ if git(repo, "rev-parse", f"{repo_spec['commit']}^{{tree}}") != repo_spec["tree"]:
82
+ raise ValueError(f"pinned tree mismatch: {repo_spec['id']}")
83
+ for override in spec["overrides"]:
84
+ if override["fact_id"] not in facts_by_id or override["prompt_id"] not in q_by_id:
85
+ raise ValueError("override points to unknown v2 case")
86
+ fact = facts_by_id[override["fact_id"]]
87
+ question = q_by_id[override["prompt_id"]]
88
+ if fact["repo"] != override["repo"] or question["repo"] != override["repo"]:
89
+ raise ValueError("override repository mismatch")
90
+ if fact["stratum"] != override["stratum"]:
91
+ raise ValueError("replacement cannot silently change the declared stratum")
92
+ question.update({"en": override["en"], "ru": override["ru"]})
93
+ fact.update({"answer": override["answer"], "proof": override["proof"], "semantic_predicate": override["semantic_predicate"]})
94
+
95
+ gates = spec["preregistered_quality_gates"]
96
+ required_strata = set(gates["required_strata"])
97
+ declared_overrides = {row["prompt_id"] for row in spec["overrides"]}
98
+ expected_overrides = set(gates["required_replacements"]) | set(gates["optional_scoped_improvements"])
99
+ if declared_overrides != expected_overrides:
100
+ raise ValueError("v3 replacement set differs from preregistered IDs")
101
+ if len(facts_by_id) != gates["case_count"] or len(q_by_id) != gates["case_count"]:
102
+ raise ValueError("fixed case-count gate failed")
103
+ if len(set(facts_by_id)) != len(facts_by_id) or len(set(q_by_id)) != len(q_by_id):
104
+ raise ValueError("duplicate case/fact identity")
105
+ if set(facts_by_id) != {q.replace("PR-", "V2-") for q in q_by_id}:
106
+ raise ValueError("one-to-one bilingual prompt/oracle mapping failed")
107
+ if any(not row.get("en", "").strip() or not row.get("ru", "").strip() for row in q_by_id.values()):
108
+ raise ValueError("RU/EN paired-text gate failed")
109
+ repo_counts = {}
110
+ absence_containers = set()
111
+ for fact in facts_by_id.values():
112
+ repo_counts[fact["repo"]] = repo_counts.get(fact["repo"], 0) + 1
113
+ if fact["stratum"] not in required_strata:
114
+ raise ValueError(f"unknown stratum: {fact['stratum']}")
115
+ if fact["stratum"] == "decision_rationale" and not fact.get("semantic_predicate") and fact["id"] not in {o["fact_id"] for o in spec["overrides"]}:
116
+ # Reviewed v2 rationale rows receive their preregistered predicate below.
117
+ fact["semantic_predicate"] = gates["semantic_predicates"]["decision_rationale"]
118
+ if not fact.get("semantic_predicate"):
119
+ fact["semantic_predicate"] = gates["semantic_predicates"][fact["stratum"]]
120
+ qid = fact["id"].replace("V2-", "PR-")
121
+ if not re.fullmatch(r"PR-(RG|VT|ZP)-\d{2}", qid):
122
+ raise ValueError(f"answer-shaped case label rejected: {qid}")
123
+ proof_types = {p["type"] for p in fact["proof"]}
124
+ if fact["stratum"] == "current_structured" and not proof_types.intersection({"json", "toml", "go_mod"}):
125
+ raise ValueError(f"current structured predicate lacks a parser proof: {fact['id']}")
126
+ if fact["stratum"] == "historical_change":
127
+ has_history = any(p.get("commit") != repo_heads[fact["repo"]] or (p["type"] == "quote" and re.search(r"20\d\d-\d\d-\d\d", p.get("quote", ""))) for p in fact["proof"])
128
+ if not has_history:
129
+ raise ValueError(f"historical stratum has no historical revision/release proof: {fact['id']}")
130
+ if fact["stratum"] == "decision_rationale" and not proof_types.intersection({"quote", "commit_text"}):
131
+ raise ValueError(f"decision rationale needs source prose/commit evidence: {fact['id']}")
132
+ if fact["stratum"] == "conflict_supersession":
133
+ has_transition = "commit_diff" in proof_types
134
+ values = {(p.get("commit"), p.get("value")) for p in fact["proof"] if p["type"] in {"json", "toml", "go_mod"}}
135
+ has_transition = has_transition or len({value for _, value in values}) >= 2
136
+ has_removal = "commit_text" in proof_types and any(word in " ".join(p.get("quote", "").lower() for p in fact["proof"] if p["type"] == "commit_text") for word in ("remove", "replace"))
137
+ if not (has_transition or has_removal):
138
+ raise ValueError(f"conflict stratum lacks before/after or diff evidence: {fact['id']}")
139
+ if fact["stratum"] == "bounded_absence":
140
+ absence_proof = next((p for p in fact["proof"] if p["type"].endswith("_absent")), None)
141
+ if not absence_proof:
142
+ raise ValueError(f"absence lacks finite-container predicate: {fact['id']}")
143
+ scope = (fact["repo"], absence_proof.get("path"), absence_proof.get("field"))
144
+ if scope in absence_containers:
145
+ raise ValueError(f"redundant absence pair rejected: {scope}")
146
+ absence_containers.add(scope)
147
+ if set(repo_counts.values()) != {10}:
148
+ raise ValueError(f"per-repository count gate failed: {repo_counts}")
149
+ strata_counts = {s: sum(row["stratum"] == s for row in facts_by_id.values()) for s in required_strata}
150
+ if any(count != 6 for count in strata_counts.values()):
151
+ raise ValueError(f"stratum balance gate failed: {strata_counts}")
152
+ if len(absence_containers) != sum(f["stratum"] == "bounded_absence" for f in facts_by_id.values()):
153
+ raise ValueError("no-redundant-absence-pairs gate failed")
154
+
155
+ # Projected evaluator inputs intentionally carry no IDs, values, evidence, or locators.
156
+ projected = [{"repo": row["repo"], "stratum": row["stratum"], "language": lang, "prompt": row[lang]} for row in questions["questions"] for lang in ("en", "ru")]
157
+ if any(set(row) & {"prompt_id", "fact_id", "answer", "evidence", "proof", "commit", "path", "line"} for row in projected):
158
+ raise ValueError("projection leakage gate failed")
159
+ if len(projected) != 60:
160
+ raise ValueError("paired RU/EN projection count mismatch")
161
+
162
+ oracle_rows = []
163
+ for fact in facts_by_id.values():
164
+ evidence = [verify_v3_proof(CLONES / fact["repo"], proof) for proof in fact["proof"]]
165
+ oracle_rows.append({"fact_id": fact["id"], "repo": fact["repo"], "stratum": fact["stratum"], "answer": fact["answer"], "kind": "prose_claim" if fact["stratum"] == "decision_rationale" else "fact", "semantic_predicate": fact["semantic_predicate"], "evidence": evidence})
166
+ args.oracle_output.write_text(json.dumps({"schema": spec["schema"], "facts": oracle_rows}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
167
+ args.questions_output.write_text(json.dumps({"schema":"public-repo-questions-dev-v3","case_count":30,"questions":questions["questions"]}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
168
+ print(f"v3 gates pass: {len(oracle_rows)} cases; 30 paired prompts; strata={strata_counts}; 60 projected language rows")
169
+
170
+
171
+ if __name__ == "__main__":
172
+ try:
173
+ main()
174
+ except (KeyError, IndexError, TypeError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
175
+ print(f"v3 build failed closed: {exc}", file=sys.stderr)
176
+ raise SystemExit(2)
@@ -0,0 +1,296 @@
1
+ """Actor-side normalization for the B0 public wire v2 protocol.
2
+
3
+ This module consumes only public six-tool adapter responses. It deliberately
4
+ has no oracle, product database, filesystem-discovery, or retry capability.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from collections.abc import Callable, Mapping, Sequence
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ try:
16
+ from . import wire_v2
17
+ except ImportError: # pragma: no cover - permits direct, reviewed invocation
18
+ import wire_v2 # type: ignore
19
+
20
+
21
+ JsonResponse = str | bytes | Mapping[str, Any]
22
+ Resolver = Callable[[str, Mapping[str, Any]], JsonResponse]
23
+ NONEMPTY_STATUSES = frozenset({"MATCHES", "SUPPORTED", "OK"})
24
+ PUBLIC_AUTHORIZATION = {
25
+ "host_authorized": True,
26
+ "public_eligible": True,
27
+ "security_class": "PUBLIC",
28
+ "security_policy": "public",
29
+ }
30
+
31
+
32
+ class MappingFailure(Exception):
33
+ def __init__(self, stage: str, code: str):
34
+ self.stage, self.code = stage, code
35
+
36
+
37
+ class Disclosure(Exception):
38
+ def __init__(self, code: str):
39
+ self.code = code
40
+
41
+
42
+ def _invoke(resolver: Resolver, tool: str, reference: Mapping[str, Any], stage: str) -> JsonResponse:
43
+ try:
44
+ return resolver(tool, reference)
45
+ except TimeoutError:
46
+ raise MappingFailure(stage, "TIMEOUT") from None
47
+ except Exception:
48
+ raise MappingFailure(stage, "TOOL_ERROR") from None
49
+
50
+
51
+ def _decode(raw: JsonResponse, stage: str) -> Mapping[str, Any]:
52
+ if raw is None: # type: ignore[comparison-overlap]
53
+ raise MappingFailure(stage, "NO_JSON")
54
+ if isinstance(raw, Mapping):
55
+ return raw
56
+ if not isinstance(raw, (str, bytes)):
57
+ raise MappingFailure(stage, "MALFORMED_JSON")
58
+ try:
59
+ value = json.loads(raw)
60
+ except (UnicodeDecodeError, json.JSONDecodeError, TypeError):
61
+ raise MappingFailure(stage, "MALFORMED_JSON") from None
62
+ if not isinstance(value, Mapping):
63
+ raise MappingFailure(stage, "MALFORMED_JSON")
64
+ return value
65
+
66
+
67
+ def _owner_failure(value: Mapping[str, Any], stage: str) -> None:
68
+ status = value.get("status")
69
+ if status == "OWNER_UNAVAILABLE":
70
+ raise MappingFailure(stage, "OWNER_UNAVAILABLE")
71
+ if status == "OWNER_INVALID_RESPONSE":
72
+ raise MappingFailure(stage, "OWNER_INVALID_RESPONSE")
73
+
74
+
75
+ def _restricted_metadata(value: Mapping[str, Any]) -> bool:
76
+ access = value.get("access_status")
77
+ return access == "DENIED" or value.get("security_class") not in (None, "PUBLIC") or value.get(
78
+ "security_policy"
79
+ ) not in (None, "public")
80
+
81
+
82
+ def _reference(result: Mapping[str, Any]) -> dict[str, Any]:
83
+ kind = result.get("result_type")
84
+ canonical = result.get("canonical_reference")
85
+ canonical = canonical if isinstance(canonical, Mapping) else {}
86
+ if kind == "fact" or "key" in result:
87
+ key, revision = result.get("key"), result.get("revision")
88
+ if key is None:
89
+ key = canonical.get("key")
90
+ if revision is None:
91
+ revision = canonical.get("revision")
92
+ if not isinstance(key, str) or not key or isinstance(revision, bool) or not isinstance(revision, int) or revision < 1:
93
+ raise MappingFailure("SEARCH", "SCHEMA_DRIFT")
94
+ return {"kind": "fact", "fact_key": key, "fact_revision": revision}
95
+ memory_id = result.get("memory_id")
96
+ if not isinstance(memory_id, str) or not memory_id:
97
+ raise MappingFailure("SEARCH", "SCHEMA_DRIFT")
98
+ return {"kind": "memory", "memory_id": memory_id}
99
+
100
+
101
+ def _source(identity: Mapping[str, Any], context: Mapping[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
102
+ binding = identity.get("revision_binding")
103
+ if not isinstance(binding, Mapping) or set(binding) != {"kind", "value"}:
104
+ raise MappingFailure("READBACK", "RESOLUTION_FAILURE")
105
+ binding_value = binding.get("value")
106
+ width = 40 if binding.get("kind") == "git_commit" else 64 if binding.get("kind") == "artifact_sha256" else 0
107
+ if not isinstance(binding_value, str) or not re.fullmatch(rf"[0-9a-f]{{{width}}}", binding_value):
108
+ raise MappingFailure("READBACK", "RESOLUTION_FAILURE")
109
+ if context.get("source_revision_binding") != binding:
110
+ raise MappingFailure("READBACK", "RESOLUTION_FAILURE")
111
+ path, digest, kind = context.get("source_path"), context.get("artifact_hash"), context.get("locator_kind")
112
+ path_parts = path.replace("\\", "/").split("/") if isinstance(path, str) else []
113
+ if (not isinstance(path, str) or not path or path.startswith(("/", "\\"))
114
+ or re.match(r"^[A-Za-z]:", path) or ".." in path_parts
115
+ or not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest)):
116
+ raise MappingFailure("READBACK", "RESOLUTION_FAILURE")
117
+ if kind == "LINE_SPAN":
118
+ start, end = context.get("line_start"), context.get("line_end")
119
+ if any(isinstance(x, bool) or not isinstance(x, int) for x in (start, end)):
120
+ raise MappingFailure("READBACK", "RESOLUTION_FAILURE")
121
+ if start < 1 or end < start:
122
+ raise MappingFailure("READBACK", "RESOLUTION_FAILURE")
123
+ locator = {"kind": kind, "start": start, "end": end}
124
+ elif kind == "FILE_DIGEST":
125
+ locator = {"kind": kind}
126
+ else:
127
+ raise MappingFailure("READBACK", "RESOLUTION_FAILURE")
128
+ return dict(binding), {"path": path, "locator": locator, "artifact_sha256": digest}
129
+
130
+
131
+ def _authorization(identity: Mapping[str, Any]) -> dict[str, Any]:
132
+ auth = identity.get("authorization")
133
+ public = {
134
+ "host_authorized": auth.get("host_authorized") if isinstance(auth, Mapping) else None,
135
+ "public_eligible": auth.get("public_eligible") if isinstance(auth, Mapping) else None,
136
+ "security_class": identity.get("security_class"),
137
+ "security_policy": identity.get("security_policy"),
138
+ }
139
+ if public != PUBLIC_AUTHORIZATION:
140
+ raise Disclosure("NON_PUBLIC_EGRESS")
141
+ return public
142
+
143
+
144
+ def _proof(raw: JsonResponse, identity: Mapping[str, Any], binding: dict[str, Any], source: dict[str, Any]) -> list[dict[str, Any]]:
145
+ evidence = _decode(raw, "EVIDENCE")
146
+ _owner_failure(evidence, "EVIDENCE")
147
+ if _restricted_metadata(evidence):
148
+ raise Disclosure("RESTRICTED_METADATA")
149
+ status = evidence.get("status")
150
+ if status in {"EVIDENCE_DENIED", "REDACTED", "UNKNOWN", "DENIED"}:
151
+ return []
152
+ if status != "SUPPORTED":
153
+ raise MappingFailure("EVIDENCE", "UNKNOWN_STATUS")
154
+ if evidence.get("source_identity") != identity:
155
+ raise MappingFailure("EVIDENCE", "RESOLUTION_FAILURE")
156
+ lineage = evidence.get("lineage")
157
+ if binding["kind"] == "git_commit" and (
158
+ not isinstance(lineage, Mapping) or lineage.get("source_git_head") != binding["value"]
159
+ ):
160
+ raise MappingFailure("EVIDENCE", "RESOLUTION_FAILURE")
161
+ freshness = evidence.get("freshness")
162
+ if (evidence.get("source_path") != source["path"] or not isinstance(freshness, Mapping)
163
+ or freshness.get("status") != "VERIFIED_MATCH"):
164
+ raise MappingFailure("EVIDENCE", "RESOLUTION_FAILURE")
165
+ payload = evidence.get("evidence")
166
+ if not isinstance(payload, Mapping) or payload.get("locator_kind") != source["locator"]["kind"]:
167
+ raise MappingFailure("EVIDENCE", "RESOLUTION_FAILURE")
168
+ # Keep proof and typed-read objects independent in memory as well as after
169
+ # JSON serialization; mutating one must not silently rewrite the other.
170
+ proof = {"proof_index": 1, "status": "SUPPORTED", "revision_binding": dict(binding),
171
+ "source": {"path": source["path"], "locator": dict(source["locator"]),
172
+ "artifact_sha256": source["artifact_sha256"]},
173
+ "freshness": "VERIFIED_MATCH"}
174
+ if source["locator"]["kind"] == "LINE_SPAN":
175
+ if (payload.get("line_start"), payload.get("line_end")) != (
176
+ source["locator"]["start"], source["locator"]["end"]
177
+ ) or not isinstance(payload.get("fragment"), str) or not payload["fragment"]:
178
+ raise MappingFailure("EVIDENCE", "RESOLUTION_FAILURE")
179
+ proof.update({"supports_claim": "NOT_MEASURED", "fragment": payload["fragment"]})
180
+ else:
181
+ if payload.get("supports_claim") is not False or payload.get("content_returned") is not False:
182
+ raise MappingFailure("EVIDENCE", "RESOLUTION_FAILURE")
183
+ proof["supports_claim"] = False
184
+ return [proof]
185
+
186
+
187
+ def _candidate(rank: int, result: Mapping[str, Any], resolver: Resolver) -> dict[str, Any]:
188
+ reference = _reference(result)
189
+ candidate: dict[str, Any] = {"rank": rank, "search_reference": reference, "resolution": "NOT_MEASURED", "proofs": []}
190
+ tool = "get_fact" if reference["kind"] == "fact" else "read_memory"
191
+ read = _decode(_invoke(resolver, tool, reference, "READBACK"), "READBACK")
192
+ _owner_failure(read, "READBACK")
193
+ status = read.get("status")
194
+ if status in {"DENIED", "UNKNOWN"}:
195
+ candidate["resolution"] = status
196
+ return candidate
197
+ if status != "SUPPORTED":
198
+ raise MappingFailure("READBACK", "UNKNOWN_STATUS")
199
+ identity, context = read.get("source_identity"), read.get("source_context")
200
+ if not isinstance(identity, Mapping):
201
+ raise MappingFailure("READBACK", "RESOLUTION_FAILURE")
202
+ authorization = _authorization(identity)
203
+ if not isinstance(context, Mapping):
204
+ candidate["resolution"] = "UNLOCATED"
205
+ return candidate
206
+ binding, source = _source(identity, context)
207
+ canonical = identity.get("canonical_reference")
208
+ if not isinstance(canonical, Mapping):
209
+ raise MappingFailure("READBACK", "RESOLUTION_FAILURE")
210
+ if reference["kind"] == "fact":
211
+ expected = {"kind": "fact", "key": reference["fact_key"], "revision": reference["fact_revision"]}
212
+ value = read.get("value")
213
+ else:
214
+ expected = {"kind": "memory", "id": reference["memory_id"]}
215
+ value = read.get("text")
216
+ if (dict(canonical) != expected or not isinstance(value, str)
217
+ or read.get("record_type") != reference["kind"]):
218
+ raise MappingFailure("READBACK", "RESOLUTION_FAILURE")
219
+ wire_reference = ({"kind": "fact", "key": reference["fact_key"], "revision": reference["fact_revision"]}
220
+ if reference["kind"] == "fact" else {"kind": "memory", "memory_id": reference["memory_id"]})
221
+ typed = {
222
+ "tool": tool, "record_type": read["record_type"], "value": value,
223
+ "value_type": identity.get("value_type") if isinstance(identity.get("value_type"), str) else "NOT_MEASURED",
224
+ "authority": read.get("authority") if isinstance(read.get("authority"), str) else "NOT_MEASURED",
225
+ "authorization": authorization,
226
+ "canonical_reference": wire_reference, "revision_binding": binding, "source": source,
227
+ }
228
+ proof_raw = _invoke(resolver, "evidence", reference, "EVIDENCE")
229
+ candidate.update({"resolution": "SUPPORTED", "typed_read": typed,
230
+ "proofs": _proof(proof_raw, identity, binding, source)})
231
+ return candidate
232
+
233
+
234
+ def map_case(*, ordinal: int, prompt: str, search_response: JsonResponse, resolver: Resolver) -> dict[str, Any]:
235
+ """Map one and only one public search attempt into its frozen global row."""
236
+ expected = wire_v2.GLOBAL_ORDER[ordinal - 1] if 1 <= ordinal <= 30 else None
237
+ if expected is None:
238
+ raise ValueError("ordinal must be in 1..30")
239
+ _, case_id, repository, stratum = expected
240
+ common = {"ordinal": ordinal, "case_id": case_id, "repository": repository, "stratum": stratum,
241
+ "prompt_sha256": wire_v2.sha256_bytes(prompt.encode("utf-8")), "attempt_count": 1}
242
+ try:
243
+ search = _decode(search_response, "SEARCH")
244
+ _owner_failure(search, "SEARCH")
245
+ status = search.get("status")
246
+ if "results" not in search:
247
+ raise MappingFailure("SEARCH", "MISSING_RESULTS")
248
+ results = search["results"]
249
+ if not isinstance(results, list):
250
+ raise MappingFailure("SEARCH", "RESULTS_NOT_ARRAY")
251
+ if status not in NONEMPTY_STATUSES | set(wire_v2.EMPTY_ADAPTER_STATUSES):
252
+ raise MappingFailure("SEARCH", "UNKNOWN_STATUS")
253
+ if not results:
254
+ if status not in wire_v2.EMPTY_ADAPTER_STATUSES:
255
+ raise MappingFailure("SEARCH", "UNKNOWN_STATUS")
256
+ return {**common, "status": "OBSERVED_EMPTY", "search": {"adapter_status": status,
257
+ "candidate_count": 0, "returned_count": 0}, "candidates": [], "restricted_disclosure": False}
258
+ if status not in NONEMPTY_STATUSES:
259
+ raise MappingFailure("SEARCH", "UNKNOWN_STATUS")
260
+ selected = results[:3]
261
+ if any(not isinstance(item, Mapping) for item in results):
262
+ raise MappingFailure("SEARCH", "SCHEMA_DRIFT")
263
+ if any(_restricted_metadata(item) for item in results if isinstance(item, Mapping)):
264
+ raise Disclosure("RESTRICTED_METADATA")
265
+ candidates = [_candidate(rank, item, resolver) for rank, item in enumerate(selected, 1)]
266
+ return {**common, "status": "OBSERVED_NONEMPTY", "search": {"adapter_status": status,
267
+ "candidate_count": len(results), "returned_count": len(candidates)},
268
+ "candidates": candidates, "restricted_disclosure": False}
269
+ except Disclosure as exc:
270
+ return {**common, "status": "RESTRICTED_DISCLOSURE", "disclosure": {"code": exc.code}}
271
+ except MappingFailure as exc:
272
+ return {**common, "status": "INFRA_ERROR", "failure": {"stage": exc.stage, "code": exc.code}}
273
+
274
+
275
+ def build_ledger(*, prompts: Sequence[str], search_responses: Sequence[JsonResponse], resolver: Resolver,
276
+ envelope: Mapping[str, Any]) -> dict[str, Any]:
277
+ """Build and validate a 30-row ledger in exact global order."""
278
+ if len(prompts) != 30 or len(search_responses) != 30:
279
+ raise ValueError("exactly 30 English projected prompts and responses are required")
280
+ if any(not isinstance(prompt, str) or not prompt for prompt in prompts):
281
+ raise ValueError("projected prompts must be non-empty strings")
282
+ ledger = dict(envelope)
283
+ ledger["rows"] = [map_case(ordinal=i, prompt=prompts[i - 1], search_response=search_responses[i - 1],
284
+ resolver=resolver) for i in range(1, 31)]
285
+ wire_v2.validate_private_ledger(ledger)
286
+ return ledger
287
+
288
+
289
+ def serialize_exact(ledger: Mapping[str, Any], destination: Path) -> tuple[bytes, str]:
290
+ """Exclusively write the validated bytes handed to the scorer."""
291
+ wire_v2.validate_private_ledger(ledger)
292
+ data = wire_v2.canonical_json_bytes(ledger) + b"\n"
293
+ digest = wire_v2.write_new_json(destination, ledger, artifact_kind="private_ledger")
294
+ if destination.read_bytes() != data:
295
+ raise RuntimeError("serialized handoff bytes changed after validation")
296
+ return data, digest
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env python3
2
+ """Emit the agent-visible DEV v2 prompts without oracle identifiers or answers."""
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+ QUESTIONS = Path(__file__).with_name("questions_dev_v2.json")
8
+
9
+
10
+ def project(data, language):
11
+ if language not in ("en", "ru"):
12
+ raise ValueError("language must be en or ru")
13
+ return [
14
+ {"prompt_id": row["prompt_id"], "repo": row["repo"], "stratum": row["stratum"], "language": language, "prompt": row[language]}
15
+ for row in data["questions"]
16
+ ]
17
+
18
+
19
+ def main():
20
+ parser = argparse.ArgumentParser()
21
+ parser.add_argument("--language", choices=("en", "ru"), required=True)
22
+ parser.add_argument("--repo", choices=("ripgrep", "vite", "zap"))
23
+ args = parser.parse_args()
24
+ rows = project(json.loads(QUESTIONS.read_text(encoding="utf-8")), args.language)
25
+ if args.repo:
26
+ rows = [row for row in rows if row["repo"] == args.repo]
27
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
28
+
29
+
30
+ if __name__ == "__main__":
31
+ main()
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env python3
2
+ """Emit prompt text only; deterministic row order is the hidden scoring join."""
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+ HERE = Path(__file__).parent
8
+
9
+
10
+ def project(rows, language):
11
+ if language not in ("en", "ru"):
12
+ raise ValueError("language must be en or ru")
13
+ return [{"repo": row["repo"], "stratum": row["stratum"], "language": language, "prompt": row[language]} for row in rows]
14
+
15
+
16
+ def main():
17
+ ap = argparse.ArgumentParser()
18
+ ap.add_argument("--language", choices=("en", "ru"), required=True)
19
+ ap.add_argument("--repo", choices=("ripgrep", "vite", "zap"))
20
+ args = ap.parse_args()
21
+ data = json.loads((HERE / "questions_dev_v3.json").read_text(encoding="utf-8"))
22
+ rows = project(data["questions"], args.language)
23
+ if args.repo:
24
+ rows = [row for row in rows if row["repo"] == args.repo]
25
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
26
+
27
+
28
+ if __name__ == "__main__":
29
+ main()