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.
- benchmarks/__init__.py +3 -0
- benchmarks/adapters/__init__.py +29 -0
- benchmarks/adapters/ablations.py +406 -0
- benchmarks/adapters/base.py +72 -0
- benchmarks/adapters/controlled/__init__.py +13 -0
- benchmarks/adapters/controlled/core_archival.py +115 -0
- benchmarks/adapters/controlled/extract_resolve.py +130 -0
- benchmarks/adapters/controlled/hybrid_rag.py +120 -0
- benchmarks/adapters/controlled/no_late_binding.py +113 -0
- benchmarks/adapters/dandelion.py +94 -0
- benchmarks/adapters/native/__init__.py +31 -0
- benchmarks/adapters/native/base.py +45 -0
- benchmarks/adapters/native/dandelion_native.py +164 -0
- benchmarks/adapters/native/dandelion_native_b0.py +165 -0
- benchmarks/adapters/native/dandelion_native_b1.py +170 -0
- benchmarks/adapters/native/dandelion_native_b2.py +169 -0
- benchmarks/adapters/native/dandelion_native_b3.py +171 -0
- benchmarks/adapters/native/dandelion_native_c4.py +261 -0
- benchmarks/adapters/native/dandelion_native_c4_1.py +281 -0
- benchmarks/adapters/native/dandelion_native_c4_2.py +435 -0
- benchmarks/adapters/native/event_evidence_b2.py +616 -0
- benchmarks/adapters/native/evidence_b2.py +609 -0
- benchmarks/adapters/native/letta_native.py +253 -0
- benchmarks/adapters/native/mem0_native.py +219 -0
- benchmarks/adapters/native/store_vector_b0.py +792 -0
- benchmarks/adapters/native/store_vector_b2.py +808 -0
- benchmarks/agent_adapter_stdio_acceptance.py +86 -0
- benchmarks/bootstrap_cross_stack.py +218 -0
- benchmarks/canonical_profile_instrumentation.py +167 -0
- benchmarks/canonical_public_baseline.py +288 -0
- benchmarks/cli.py +525 -0
- benchmarks/collector_public30_offline.py +1653 -0
- benchmarks/datasets/__init__.py +45 -0
- benchmarks/datasets/conversational_generator.py +238 -0
- benchmarks/datasets/generator.py +283 -0
- benchmarks/datasets/holdout_topology_generator.py +290 -0
- benchmarks/datasets/holdout_topology_generator_v2.py +294 -0
- benchmarks/datasets/multi_world.py +1643 -0
- benchmarks/datasets/scale_generator.py +289 -0
- benchmarks/datasets/schema.py +57 -0
- benchmarks/deep_collision_stress.py +199 -0
- benchmarks/evaluators/__init__.py +12 -0
- benchmarks/evaluators/manifest.py +142 -0
- benchmarks/evaluators/metrics.py +277 -0
- benchmarks/evaluators/runner.py +258 -0
- benchmarks/f1_step0/build_dev_measurement_manifest_v1.py +127 -0
- benchmarks/f1_step0/build_dev_measurement_manifest_v2.py +127 -0
- benchmarks/f1_step0/build_dev_measurement_manifest_v3.py +146 -0
- benchmarks/f1_step0/build_ledger.py +143 -0
- benchmarks/f1_step0/build_ledger_v2.py +296 -0
- benchmarks/f1_step0/compare_dev52_readiness_v1.py +106 -0
- benchmarks/f1_step0/locator_public_smoke.py +172 -0
- benchmarks/f1_step0/prepare_dev52_owner_v1.py +133 -0
- benchmarks/f1_step0/prepare_dev52_owner_v2.py +133 -0
- benchmarks/f1_step0/public_identity_probe.py +191 -0
- benchmarks/f1_step0/public_response_mapper.py +101 -0
- benchmarks/f1_step0/real_source_public_preflight.py +244 -0
- benchmarks/f1_step0/run_exact_fusion_dev_experiment_v1.py +83 -0
- benchmarks/f1_step0/scorer.py +110 -0
- benchmarks/f1_step0/source_aware_dev_measurement_v1.py +627 -0
- benchmarks/f1_step0/source_aware_dev_measurement_v2.py +659 -0
- benchmarks/f1_step0/source_aware_dev_measurement_v3.py +776 -0
- benchmarks/f1_step0/test_public_response_mapper.py +110 -0
- benchmarks/f1_step0/test_real_source_public_preflight.py +25 -0
- benchmarks/f1_step0/test_scorer.py +158 -0
- benchmarks/f1_step0/test_source_aware_dev_measurement.py +189 -0
- benchmarks/f1_step0/test_source_aware_dev_measurement_v2.py +263 -0
- benchmarks/f1_step0/test_source_aware_dev_measurement_v3.py +334 -0
- benchmarks/f1_step0/typed_readback_public_smoke.py +181 -0
- benchmarks/forensic_c4_1_dev.py +258 -0
- benchmarks/forensic_c4_dev.py +255 -0
- benchmarks/forensic_deep25_c4_1.py +478 -0
- benchmarks/legacy_migration_acceptance.py +29 -0
- benchmarks/longmemeval_actor.py +497 -0
- benchmarks/longmemeval_agent_judge.py +593 -0
- benchmarks/longmemeval_budget.py +139 -0
- benchmarks/longmemeval_full.py +410 -0
- benchmarks/longmemeval_judge.py +327 -0
- benchmarks/longmemeval_pilot.py +316 -0
- benchmarks/longmemeval_s.py +318 -0
- benchmarks/memory_bench.py +248 -0
- benchmarks/memory_formation/__init__.py +1 -0
- benchmarks/memory_formation/audit.py +801 -0
- benchmarks/memory_formation/real_audit.py +688 -0
- benchmarks/memory_session_acceptance.py +279 -0
- benchmarks/native_codex_host.py +513 -0
- benchmarks/owner_dense_acceptance.py +126 -0
- benchmarks/pilot_seeker_vault.py +266 -0
- benchmarks/prepare_public30_ripgrep_range_owner.py +115 -0
- benchmarks/profile_canonical.py +373 -0
- benchmarks/profile_canonical_lanes.py +405 -0
- benchmarks/profile_search_chunks.py +351 -0
- benchmarks/public_ranges_faq_proof.py +121 -0
- benchmarks/public_repos/build_history_scope_v3.py +330 -0
- benchmarks/public_repos/build_oracle.py +108 -0
- benchmarks/public_repos/build_oracle_v2.py +169 -0
- benchmarks/public_repos/build_oracle_v3.py +176 -0
- benchmarks/public_repos/map_public_v2.py +296 -0
- benchmarks/public_repos/project_prompts_v2.py +31 -0
- benchmarks/public_repos/project_prompts_v3.py +29 -0
- benchmarks/public_repos/ready_admin_v2.py +214 -0
- benchmarks/public_repos/score_public_v2.py +258 -0
- benchmarks/public_repos/test_map_public_v2.py +171 -0
- benchmarks/public_repos/test_public_repo_v2.py +44 -0
- benchmarks/public_repos/test_public_repo_v3.py +46 -0
- benchmarks/public_repos/test_ready_admin_v2.py +117 -0
- benchmarks/public_repos/test_score_public_v2.py +163 -0
- benchmarks/public_repos/test_wire_v2.py +292 -0
- benchmarks/public_repos/wire_v2.py +603 -0
- benchmarks/real_blocker_fix_acceptance.py +155 -0
- benchmarks/real_scan_rescan_acceptance.py +41 -0
- benchmarks/recall_v2_20k_smoke.py +112 -0
- benchmarks/recall_v2_e1_retrieve.py +70 -0
- benchmarks/recall_v2_e1_score.py +271 -0
- benchmarks/recall_v2_e2_prepare.py +69 -0
- benchmarks/recall_v2_e2_public_score.py +91 -0
- benchmarks/recall_v2_e2_score.py +108 -0
- benchmarks/recall_v2_navigation_mcp_replay.py +308 -0
- benchmarks/recall_v2_reader_capture.py +118 -0
- benchmarks/recall_v2_reader_replay.py +136 -0
- benchmarks/run_blind_h10_holdout.py +284 -0
- benchmarks/run_blind_h9_holdout.py +275 -0
- benchmarks/run_c4_2_nightly_scale.py +446 -0
- benchmarks/run_context_scale_simulation.py +189 -0
- benchmarks/run_conversational_bench.py +170 -0
- benchmarks/run_h11_evaluation.py +316 -0
- benchmarks/run_h11_v2_evaluation.py +431 -0
- benchmarks/run_native_fixed12.py +469 -0
- benchmarks/run_native_preflight.py +280 -0
- benchmarks/run_scale_stress.py +225 -0
- benchmarks/solanazation_brownfield_01/build_oracle.py +970 -0
- benchmarks/solanazation_brownfield_01/check_level_a.py +78 -0
- benchmarks/solanazation_brownfield_01/debug_scope.py +13 -0
- benchmarks/solanazation_brownfield_01/evaluate_bootstrap_02.py +570 -0
- benchmarks/solanazation_brownfield_01/evaluate_first_pass.py +306 -0
- benchmarks/solanazation_brownfield_01/generate_dryrun_report.py +222 -0
- benchmarks/solanazation_brownfield_01/generate_manifests.py +146 -0
- benchmarks/solanazation_brownfield_01/inspect_misses.py +29 -0
- benchmarks/solanazation_brownfield_01/run_miss_forensic.py +206 -0
- benchmarks/solanazation_brownfield_01/test_facts.py +15 -0
- benchmarks/statistics/__init__.py +15 -0
- benchmarks/statistics/significance.py +326 -0
- benchmarks/test_native_mcp_preflight.py +229 -0
- benchmarks/test_prepare_public30_range_owner.py +35 -0
- benchmarks/test_public30_source_reference.py +698 -0
- benchmarks/test_recall_v2_e1_reader_input.py +89 -0
- benchmarks/test_recall_v2_navigation_mcp_replay.py +155 -0
- benchmarks/test_recall_v2_reader_replay.py +41 -0
- dandelion/__init__.py +3 -0
- dandelion/__main__.py +11 -0
- dandelion/agent_adapter.py +2369 -0
- dandelion/bootstrap/__init__.py +872 -0
- dandelion/bootstrap/alias_policy.py +50 -0
- dandelion/bootstrap/authority.py +225 -0
- dandelion/bootstrap/canonical_history.py +412 -0
- dandelion/bootstrap/classifier.py +403 -0
- dandelion/bootstrap/component_graph.py +280 -0
- dandelion/bootstrap/discovery.py +279 -0
- dandelion/bootstrap/domain_induction.py +180 -0
- dandelion/bootstrap/domain_topology.py +673 -0
- dandelion/bootstrap/evidence_envelope.py +132 -0
- dandelion/bootstrap/extractors/base.py +171 -0
- dandelion/bootstrap/extractors/exact.py +1234 -0
- dandelion/bootstrap/extractors/generic.py +100 -0
- dandelion/bootstrap/extractors/git_temporal.py +111 -0
- dandelion/bootstrap/extractors/registry.py +345 -0
- dandelion/bootstrap/extractors/relations.py +89 -0
- dandelion/bootstrap/extractors/semantic.py +424 -0
- dandelion/bootstrap/extractors/status.py +218 -0
- dandelion/bootstrap/git_sweeper.py +135 -0
- dandelion/bootstrap/manifest.py +246 -0
- dandelion/bootstrap/quarantine.py +264 -0
- dandelion/bootstrap/report.py +259 -0
- dandelion/bootstrap/root_resolver.py +221 -0
- dandelion/bootstrap/tech_profiler.py +125 -0
- dandelion/bootstrap/topology.py +75 -0
- dandelion/bootstrap/topology_index.py +110 -0
- dandelion/bootstrap/transaction.py +315 -0
- dandelion/canonical_bootstrap.py +257 -0
- dandelion/canonical_memory.py +4130 -0
- dandelion/captured_input.py +295 -0
- dandelion/cli.py +767 -0
- dandelion/config.py +40 -0
- dandelion/derived_index.py +745 -0
- dandelion/domains.py +706 -0
- dandelion/embedder.py +229 -0
- dandelion/event_evidence.py +571 -0
- dandelion/evidence.py +812 -0
- dandelion/evidence_response.py +453 -0
- dandelion/evidence_workspace.py +2360 -0
- dandelion/exact_context.py +129 -0
- dandelion/hydrator.py +124 -0
- dandelion/inspector.py +442 -0
- dandelion/inspector_assets/dandelion-mark.svg +33 -0
- dandelion/inspector_assets/dandelion_graph.js +361 -0
- dandelion/inspector_assets/inspector.css +223 -0
- dandelion/inspector_assets/inspector.html +135 -0
- dandelion/inspector_assets/inspector.js +1059 -0
- dandelion/legacy_import.py +431 -0
- dandelion/live_source_grants.py +133 -0
- dandelion/local_owner.py +114 -0
- dandelion/memory_client.py +252 -0
- dandelion/memory_contract.py +107 -0
- dandelion/memory_owner.py +560 -0
- dandelion/reader_providers.py +118 -0
- dandelion/recall_v2.py +767 -0
- dandelion/reconciler.py +219 -0
- dandelion/request_budget.py +125 -0
- dandelion/retained_basis.py +223 -0
- dandelion/retrieval.py +485 -0
- dandelion/router.py +405 -0
- dandelion/search_terms.py +53 -0
- dandelion/security.py +124 -0
- dandelion/server.py +810 -0
- dandelion/source_content_fts.py +219 -0
- dandelion/source_delivery.py +89 -0
- dandelion/source_history.py +241 -0
- dandelion/source_identity.py +88 -0
- dandelion/source_navigator.py +5 -0
- dandelion/source_reader.py +444 -0
- dandelion/source_references.py +379 -0
- dandelion/source_sections.py +265 -0
- dandelion/store_kv.py +684 -0
- dandelion/store_vector.py +1289 -0
- dandelion/studio.py +325 -0
- dandelion/wal.py +227 -0
- dandelion_memory-1.0.0rc15.dist-info/METADATA +48 -0
- dandelion_memory-1.0.0rc15.dist-info/RECORD +232 -0
- dandelion_memory-1.0.0rc15.dist-info/WHEEL +5 -0
- dandelion_memory-1.0.0rc15.dist-info/entry_points.txt +5 -0
- dandelion_memory-1.0.0rc15.dist-info/licenses/LICENSE +21 -0
- dandelion_memory-1.0.0rc15.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Export a hash-pinned, content-only allowlist of v3 history evidence."""
|
|
3
|
+
import argparse
|
|
4
|
+
from collections import Counter
|
|
5
|
+
import copy
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
HERE = Path(__file__).parent
|
|
17
|
+
CLONES = HERE.parents[1] / "scratch" / "public_repo_candidates_20260927"
|
|
18
|
+
INPUT_HASHES = {
|
|
19
|
+
"manifest_v3.json": "e25017aef21b0991635ec59b478adbd23c0cdaa2bec0fb14a1ef8c67f1f80f1a",
|
|
20
|
+
"oracle_dev_v3.json": "a0f50b4eab88f359e75bd7d9b358807f89bdf1f6a9f24f90f2eeb34ccb13daf8",
|
|
21
|
+
"manifest_v2.json": "e7ac02d93ab0f278df5a25f213b010c5953019c43ac15c6420a715f6973bd1f6",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def git(repo: Path, *args: str) -> str:
|
|
26
|
+
return subprocess.check_output(["git", "-C", str(repo), *args], text=True, stderr=subprocess.PIPE).rstrip("\r\n")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def sha(data: bytes) -> str:
|
|
30
|
+
return hashlib.sha256(data).hexdigest()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def norm(text: str) -> str:
|
|
34
|
+
return " ".join(text.split())
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def source_blob(repo, commit, path):
|
|
38
|
+
resolved = git(repo, "rev-parse", f"{commit}^{{commit}}")
|
|
39
|
+
oid = git(repo, "rev-parse", f"{resolved}:{path}")
|
|
40
|
+
data = subprocess.check_output(["git", "-C", str(repo), "show", f"{resolved}:{path}"], stderr=subprocess.PIPE)
|
|
41
|
+
return resolved, oid, data.decode("utf-8", errors="strict")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def quote_span(lines, quote, line_hint):
|
|
45
|
+
needle = norm(quote)
|
|
46
|
+
max_width = min(max(4, len(quote.splitlines()) + 5), 24)
|
|
47
|
+
for start in range(max(0, line_hint - 3), min(len(lines), line_hint + 2)):
|
|
48
|
+
for end in range(start + 1, min(len(lines), start + max_width) + 1):
|
|
49
|
+
if needle in norm(" ".join(lines[start:end])):
|
|
50
|
+
return max(0, start - 1), min(len(lines), end + 1)
|
|
51
|
+
raise ValueError("source quotation is not present at its cited line")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def toml_array_span(text, field):
|
|
55
|
+
lines = text.splitlines()
|
|
56
|
+
parent, key = field.rsplit(".", 1)
|
|
57
|
+
section = f"[{parent}]"
|
|
58
|
+
start = next((i for i, line in enumerate(lines) if line.strip() == section), None)
|
|
59
|
+
if start is None:
|
|
60
|
+
raise ValueError(f"TOML section missing: {section}")
|
|
61
|
+
field_i = next((i for i in range(start + 1, len(lines)) if re.match(rf"\s*{re.escape(key)}\s*=", lines[i])), None)
|
|
62
|
+
if field_i is None:
|
|
63
|
+
raise ValueError(f"TOML field missing: {field}")
|
|
64
|
+
if "[" not in lines[field_i]:
|
|
65
|
+
return max(0, field_i - 1), min(len(lines), field_i + 2)
|
|
66
|
+
end = field_i
|
|
67
|
+
depth = 0
|
|
68
|
+
for end in range(field_i, len(lines)):
|
|
69
|
+
depth += lines[end].count("[") - lines[end].count("]")
|
|
70
|
+
if depth <= 0:
|
|
71
|
+
break
|
|
72
|
+
return max(0, start - 1), min(len(lines), end + 2)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def toml_table_span(text, field):
|
|
76
|
+
lines = text.splitlines()
|
|
77
|
+
section = f"[{field}]"
|
|
78
|
+
start = next((i for i, line in enumerate(lines) if line.strip() == section), None)
|
|
79
|
+
if start is None:
|
|
80
|
+
raise ValueError(f"TOML section missing: {section}")
|
|
81
|
+
end = next((i for i in range(start + 1, len(lines)) if re.match(r"\s*\[", lines[i])), len(lines))
|
|
82
|
+
return max(0, start - 1), end
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def json_object_span(text, field):
|
|
86
|
+
match = re.search(rf'"{re.escape(field)}"\s*:\s*\{{', text)
|
|
87
|
+
if not match:
|
|
88
|
+
raise ValueError(f"JSON object missing: {field}")
|
|
89
|
+
opening = text.find("{", match.start())
|
|
90
|
+
depth, quoted, escaped = 0, False, False
|
|
91
|
+
closing = None
|
|
92
|
+
for pos in range(opening, len(text)):
|
|
93
|
+
ch = text[pos]
|
|
94
|
+
if quoted:
|
|
95
|
+
if escaped:
|
|
96
|
+
escaped = False
|
|
97
|
+
elif ch == "\\":
|
|
98
|
+
escaped = True
|
|
99
|
+
elif ch == '"':
|
|
100
|
+
quoted = False
|
|
101
|
+
elif ch == '"':
|
|
102
|
+
quoted = True
|
|
103
|
+
elif ch == "{":
|
|
104
|
+
depth += 1
|
|
105
|
+
elif ch == "}":
|
|
106
|
+
depth -= 1
|
|
107
|
+
if depth == 0:
|
|
108
|
+
closing = pos
|
|
109
|
+
break
|
|
110
|
+
if closing is None:
|
|
111
|
+
raise ValueError(f"unterminated JSON object: {field}")
|
|
112
|
+
start_line = text[:match.start()].count("\n")
|
|
113
|
+
end_line = text[:closing].count("\n") + 1
|
|
114
|
+
lines = text.splitlines()
|
|
115
|
+
return max(0, start_line - 1), min(len(lines), end_line + 1)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def go_require_span(text):
|
|
119
|
+
lines = text.splitlines()
|
|
120
|
+
selected = set()
|
|
121
|
+
in_block = False
|
|
122
|
+
for i, line in enumerate(lines):
|
|
123
|
+
if re.match(r"\s*require\s*\(\s*$", line):
|
|
124
|
+
in_block = True
|
|
125
|
+
selected.add(i)
|
|
126
|
+
continue
|
|
127
|
+
if in_block:
|
|
128
|
+
selected.add(i)
|
|
129
|
+
if re.match(r"\s*\)\s*$", line):
|
|
130
|
+
in_block = False
|
|
131
|
+
elif re.match(r"\s*require\s+\S+\s+v", line):
|
|
132
|
+
selected.add(i)
|
|
133
|
+
if not selected:
|
|
134
|
+
raise ValueError("go.mod has no require scope")
|
|
135
|
+
return max(0, min(selected) - 1), min(len(lines), max(selected) + 2)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def build_artifact(repo, proof, evidence):
|
|
139
|
+
ptype = proof["type"]
|
|
140
|
+
commit = proof["commit"]
|
|
141
|
+
scope = proof.get("field", "")
|
|
142
|
+
if ptype == "commit_text":
|
|
143
|
+
resolved = git(repo, "rev-parse", f"{commit}^{{commit}}")
|
|
144
|
+
text = git(repo, "show", "-s", "--format=%s", resolved) + "\n"
|
|
145
|
+
return resolved, "COMMIT_SUBJECT", scope or "commit subject", text, sha(text.encode("utf-8"))
|
|
146
|
+
if ptype == "commit_diff":
|
|
147
|
+
resolved = git(repo, "rev-parse", f"{commit}^{{commit}}")
|
|
148
|
+
text = git(repo, "show", "--format=", "--unified=0", resolved, "--", proof["path"]) + "\n"
|
|
149
|
+
if proof["quote"] not in text:
|
|
150
|
+
raise ValueError("allowlisted diff quote missing")
|
|
151
|
+
return resolved, proof["path"], "single-path commit diff", text, sha(text.encode("utf-8"))
|
|
152
|
+
resolved, blob_oid, raw = source_blob(repo, commit, proof["path"])
|
|
153
|
+
lines = raw.splitlines()
|
|
154
|
+
if ptype == "quote":
|
|
155
|
+
start, end = quote_span(lines, proof["quote"], max(0, evidence["line"] - 1))
|
|
156
|
+
scope = "cited passage with one-line context"
|
|
157
|
+
elif ptype == "toml_absent":
|
|
158
|
+
if proof["field"] == "workspace.members":
|
|
159
|
+
start, end = toml_array_span(raw, proof["field"])
|
|
160
|
+
elif proof["field"] == "features":
|
|
161
|
+
start, end = toml_table_span(raw, proof["field"])
|
|
162
|
+
else:
|
|
163
|
+
raise ValueError("unapproved TOML absence scope")
|
|
164
|
+
scope = f"finite {proof['field']} scope"
|
|
165
|
+
elif ptype == "json_absent":
|
|
166
|
+
start, end = json_object_span(raw, proof["field"])
|
|
167
|
+
scope = f"finite {proof['field']} object"
|
|
168
|
+
elif ptype == "go_mod_absent":
|
|
169
|
+
start, end = go_require_span(raw)
|
|
170
|
+
scope = "finite module requirement blocks"
|
|
171
|
+
elif ptype == "go_mod_directive_absent":
|
|
172
|
+
start, end = 0, len(lines)
|
|
173
|
+
scope = "whole go.mod directive scope"
|
|
174
|
+
elif ptype in ("toml", "json", "go_mod"):
|
|
175
|
+
center = max(0, evidence["line"] - 1)
|
|
176
|
+
start, end = max(0, center - 1), min(len(lines), center + 2)
|
|
177
|
+
scope = "field line with local context"
|
|
178
|
+
else:
|
|
179
|
+
raise ValueError(f"not an allowlisted history proof type: {ptype}")
|
|
180
|
+
snippet = "\n".join(lines[start:end]) + "\n"
|
|
181
|
+
return resolved, proof["path"], scope, snippet, sha(raw.encode("utf-8")), blob_oid
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def security_scan(data: bytes):
|
|
185
|
+
text = data.decode("utf-8", errors="strict")
|
|
186
|
+
patterns = [
|
|
187
|
+
r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----",
|
|
188
|
+
r"\bAKIA[0-9A-Z]{16}\b",
|
|
189
|
+
r"\bgh[pousr]_[A-Za-z0-9]{30,}\b",
|
|
190
|
+
r"\bxox[baprs]-[A-Za-z0-9-]{20,}\b",
|
|
191
|
+
r"\bsk-[A-Za-z0-9_-]{40,}\b",
|
|
192
|
+
]
|
|
193
|
+
if any(re.search(pattern, text) for pattern in patterns):
|
|
194
|
+
raise ValueError("security scan rejected a credential-like source fragment")
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def main():
|
|
198
|
+
ap = argparse.ArgumentParser()
|
|
199
|
+
ap.add_argument("--bundle-dir", type=Path, default=HERE / "history_scope_v3_files_stagecopy")
|
|
200
|
+
ap.add_argument("--manifest", type=Path, default=HERE / "history_scope_v3.json")
|
|
201
|
+
ap.add_argument("--hash-list", type=Path, default=HERE / "history_scope_v3.sha256")
|
|
202
|
+
args = ap.parse_args()
|
|
203
|
+
for target in (args.bundle_dir, args.manifest, args.hash_list):
|
|
204
|
+
if target.exists():
|
|
205
|
+
raise FileExistsError(f"refusing to overwrite existing target: {target}")
|
|
206
|
+
|
|
207
|
+
for input_name, expected_hash in INPUT_HASHES.items():
|
|
208
|
+
actual = sha((HERE / input_name).read_bytes())
|
|
209
|
+
if actual != expected_hash:
|
|
210
|
+
raise ValueError(f"frozen source artifact hash mismatch: {input_name}")
|
|
211
|
+
|
|
212
|
+
oracle = json.loads((HERE / "oracle_dev_v3.json").read_text(encoding="utf-8"))
|
|
213
|
+
base = json.loads((HERE / "manifest_v2.json").read_text(encoding="utf-8"))
|
|
214
|
+
v3 = json.loads((HERE / "manifest_v3.json").read_text(encoding="utf-8"))
|
|
215
|
+
oracle_facts = {row["fact_id"]: row for row in oracle["facts"]}
|
|
216
|
+
proof_by_id = {row["id"]: copy.deepcopy(row["proof"]) for row in base["facts"]}
|
|
217
|
+
overrides = {row["fact_id"]: row for row in v3["overrides"]}
|
|
218
|
+
for fact_id, override in overrides.items():
|
|
219
|
+
proof_by_id[fact_id] = override["proof"]
|
|
220
|
+
pins = {repo["id"]: repo for repo in base["repositories"]}
|
|
221
|
+
if len(oracle_facts) != 30 or len(base["facts"]) != 30 or set(oracle_facts) != set(proof_by_id):
|
|
222
|
+
raise ValueError("v3 source set is not the frozen 30-case corpus")
|
|
223
|
+
counts = Counter(row["stratum"] for row in oracle["facts"])
|
|
224
|
+
if any(counts[name] != 6 for name in ("historical_change", "conflict_supersession", "decision_rationale")):
|
|
225
|
+
raise ValueError("v3 history-scope strata validation failed")
|
|
226
|
+
|
|
227
|
+
plans = []
|
|
228
|
+
for fact_id, row in oracle_facts.items():
|
|
229
|
+
if row["stratum"] not in {"historical_change", "conflict_supersession", "decision_rationale"}:
|
|
230
|
+
continue
|
|
231
|
+
proofs = proof_by_id[fact_id]
|
|
232
|
+
if len(proofs) != len(row["evidence"]):
|
|
233
|
+
raise ValueError(f"oracle/source proof count differs for private case {fact_id}")
|
|
234
|
+
repo = CLONES / row["repo"]
|
|
235
|
+
for proof, evidence in zip(proofs, row["evidence"]):
|
|
236
|
+
resolved = git(repo, "rev-parse", f"{proof['commit']}^{{commit}}")
|
|
237
|
+
if evidence.get("commit") != resolved:
|
|
238
|
+
raise ValueError(f"private source locator revision mismatch for {fact_id}")
|
|
239
|
+
expected_path = "COMMIT_MESSAGE" if proof["type"] == "commit_text" else proof.get("path")
|
|
240
|
+
if evidence.get("path") != expected_path:
|
|
241
|
+
raise ValueError(f"private source locator path mismatch for {fact_id}")
|
|
242
|
+
if proof["type"] in {"commit_text", "commit_diff"} or resolved != pins[row["repo"]]["commit"] or row["stratum"] in {"historical_change", "conflict_supersession"}:
|
|
243
|
+
plans.append((row["repo"], proof, evidence))
|
|
244
|
+
|
|
245
|
+
stage_parent = args.bundle_dir.parent
|
|
246
|
+
stage_parent.mkdir(parents=True, exist_ok=True)
|
|
247
|
+
stage = Path(tempfile.mkdtemp(prefix=".history_scope_v3_stage_", dir=stage_parent))
|
|
248
|
+
try:
|
|
249
|
+
entries = []
|
|
250
|
+
used_names = set()
|
|
251
|
+
seen_refs = set()
|
|
252
|
+
for repo_id, proof, evidence in plans:
|
|
253
|
+
repo = CLONES / repo_id
|
|
254
|
+
result = build_artifact(repo, proof, evidence)
|
|
255
|
+
if len(result) == 5:
|
|
256
|
+
resolved, source_path, scope, content, source_hash = result
|
|
257
|
+
blob_oid = None
|
|
258
|
+
else:
|
|
259
|
+
resolved, source_path, scope, content, source_hash, blob_oid = result
|
|
260
|
+
payload = content.encode("utf-8")
|
|
261
|
+
security_scan(payload)
|
|
262
|
+
digest = sha(payload)
|
|
263
|
+
source_ref = (repo_id, resolved, source_path, scope, digest)
|
|
264
|
+
if source_ref in seen_refs:
|
|
265
|
+
continue
|
|
266
|
+
seen_refs.add(source_ref)
|
|
267
|
+
index = len(entries) + 1
|
|
268
|
+
name = f"source_{index:03d}_{digest[:12]}.txt"
|
|
269
|
+
if name in used_names:
|
|
270
|
+
raise ValueError("fixture filename collision")
|
|
271
|
+
used_names.add(name)
|
|
272
|
+
(stage / name).write_bytes(payload)
|
|
273
|
+
item = {
|
|
274
|
+
"repository": repo_id,
|
|
275
|
+
"source_revision": resolved,
|
|
276
|
+
"source_path": source_path,
|
|
277
|
+
"scope": scope,
|
|
278
|
+
"content_file": name,
|
|
279
|
+
"content_sha256": digest,
|
|
280
|
+
"source_sha256": source_hash,
|
|
281
|
+
"bytes": len(payload),
|
|
282
|
+
}
|
|
283
|
+
if blob_oid:
|
|
284
|
+
item["git_blob_oid"] = blob_oid
|
|
285
|
+
entries.append(item)
|
|
286
|
+
|
|
287
|
+
public = {
|
|
288
|
+
"schema": "runner-scoped-history-v3",
|
|
289
|
+
"artifact_policy": "allowlisted textual excerpts and one-path Git diffs only; no repository metadata or raw .git files",
|
|
290
|
+
"repositories": [{"repository": r["id"], "pinned_commit": r["commit"], "pinned_tree": r["tree"]} for r in base["repositories"]],
|
|
291
|
+
"sources": entries,
|
|
292
|
+
}
|
|
293
|
+
public_bytes = (json.dumps(public, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
|
294
|
+
security_scan(public_bytes)
|
|
295
|
+
forbidden_keys = re.compile(r"(?:fact.?id|question.?id|answer|expected|oracle)", re.I)
|
|
296
|
+
if any(forbidden_keys.search(key) for key in public.keys()) or any(forbidden_keys.search(key) for entry in entries for key in entry.keys()):
|
|
297
|
+
raise ValueError("runner manifest contains a forbidden mapping/answer field")
|
|
298
|
+
public_refs = [(s["repository"], s["source_revision"], s["source_path"], s["scope"], s["content_sha256"]) for s in entries]
|
|
299
|
+
if len(public_refs) != len(set(public_refs)):
|
|
300
|
+
raise ValueError("duplicate source reference in public manifest")
|
|
301
|
+
scope_digest = sha(json.dumps(entries, sort_keys=True, separators=(",", ":")).encode("utf-8"))
|
|
302
|
+
public["scope_sha256"] = scope_digest
|
|
303
|
+
public_bytes = (json.dumps(public, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
|
304
|
+
security_scan(public_bytes)
|
|
305
|
+
stage_manifest = stage / "history_scope_v3.json"
|
|
306
|
+
stage_manifest.write_bytes(public_bytes)
|
|
307
|
+
checksum_rows = [f"{sha(public_bytes)} history_scope_v3.json"]
|
|
308
|
+
checksum_rows.extend(f"{item['content_sha256']} {item['content_file']}" for item in entries)
|
|
309
|
+
checksum_rows.append(f"{sha(Path(__file__).read_bytes())} build_history_scope_v3.py")
|
|
310
|
+
readme_path = HERE / "HISTORY_SCOPE_V3.md"
|
|
311
|
+
if readme_path.exists():
|
|
312
|
+
checksum_rows.append(f"{sha(readme_path.read_bytes())} HISTORY_SCOPE_V3.md")
|
|
313
|
+
(stage / "history_scope_v3.sha256").write_text("\n".join(checksum_rows) + "\n", encoding="utf-8")
|
|
314
|
+
# Move content-only bundle first; public manifest and hash list are separate runner inputs.
|
|
315
|
+
os.rename(stage, args.bundle_dir)
|
|
316
|
+
args.manifest.write_bytes(public_bytes)
|
|
317
|
+
shutil.copyfile(args.bundle_dir / "history_scope_v3.sha256", args.hash_list)
|
|
318
|
+
print(f"exported {len(entries)} allowlisted history sources; {len(used_names)} content files; scope sha256={scope_digest}")
|
|
319
|
+
except Exception:
|
|
320
|
+
if stage.exists():
|
|
321
|
+
shutil.rmtree(stage)
|
|
322
|
+
raise
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
if __name__ == "__main__":
|
|
326
|
+
try:
|
|
327
|
+
main()
|
|
328
|
+
except (KeyError, IndexError, TypeError, ValueError, FileExistsError, subprocess.CalledProcessError, json.JSONDecodeError, OSError) as exc:
|
|
329
|
+
print(f"history scope v3 export failed closed: {exc}", file=sys.stderr)
|
|
330
|
+
raise SystemExit(2)
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Independent public-repository fact extractor; uses Git and Python stdlib parsers only."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import argparse
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
import tomllib
|
|
14
|
+
except ModuleNotFoundError: # Python < 3.11 is intentionally unsupported.
|
|
15
|
+
raise SystemExit("Python 3.11+ is required for the standard TOML parser")
|
|
16
|
+
|
|
17
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
18
|
+
CLONES = ROOT / "scratch" / "public_repo_candidates_20260927"
|
|
19
|
+
MANIFEST = Path(__file__).with_name("manifest.json")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def git(repo: Path, *args: str) -> str:
|
|
23
|
+
return subprocess.check_output(["git", "-C", str(repo), *args], text=True, stderr=subprocess.PIPE).strip()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def nested(obj, field):
|
|
27
|
+
# TOML array-table selector (only the documented first entry is needed here).
|
|
28
|
+
field = re.sub(r"\[(\d+)\]", r".\1", field)
|
|
29
|
+
for part in field.split("."):
|
|
30
|
+
obj = obj[int(part)] if part.isdigit() else obj[part]
|
|
31
|
+
return obj
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def go_mod_value(text: str, field: str):
|
|
35
|
+
if field in ("module", "go"):
|
|
36
|
+
match = re.search(rf"(?m)^{field}\s+(\S+)\s*$", text)
|
|
37
|
+
return match.group(1) if match else None
|
|
38
|
+
module = field.removeprefix("require.")
|
|
39
|
+
for line in text.splitlines():
|
|
40
|
+
match = re.match(r"\s*([^\s()]+)\s+(v[^\s]+)(?:\s+//.*)?$", line)
|
|
41
|
+
if match and match.group(1) == module:
|
|
42
|
+
return match.group(2)
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def line_for(text: str, field: str, expected):
|
|
47
|
+
# Line locator is verified against parsed value first, then exact key/value text.
|
|
48
|
+
key = field.rsplit(".", 1)[-1].split("[")[0]
|
|
49
|
+
target = str(expected)
|
|
50
|
+
for number, line in enumerate(text.splitlines(), 1):
|
|
51
|
+
if key in line and target in line:
|
|
52
|
+
return number
|
|
53
|
+
raise ValueError(f"cannot locate parsed value at a source line: {field}={expected!r}")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def main():
|
|
57
|
+
parser = argparse.ArgumentParser()
|
|
58
|
+
parser.add_argument("--output", type=Path, default=Path(__file__).with_name("oracle_dev.json"))
|
|
59
|
+
args = parser.parse_args()
|
|
60
|
+
spec = json.loads(MANIFEST.read_text(encoding="utf-8"))
|
|
61
|
+
report = {"schema": spec["schema"], "repositories": []}
|
|
62
|
+
for item in spec["repositories"]:
|
|
63
|
+
repo = CLONES / item["id"]
|
|
64
|
+
if git(repo, "rev-parse", "HEAD") != item["commit"]:
|
|
65
|
+
raise ValueError(f"{item['id']}: checkout HEAD differs from pinned commit")
|
|
66
|
+
tree = git(repo, "rev-parse", f"{item['commit']}^{{tree}}")
|
|
67
|
+
if item.get("tree") and tree != item["tree"]:
|
|
68
|
+
raise ValueError(f"{item['id']}: pinned tree mismatch")
|
|
69
|
+
item["tree"] = tree
|
|
70
|
+
facts = []
|
|
71
|
+
for fact in item["facts"]:
|
|
72
|
+
commit = fact.get("commit", item["commit"])
|
|
73
|
+
# Resolve and validate each revision through Git, including historical facts.
|
|
74
|
+
resolved = git(repo, "rev-parse", f"{commit}^{{commit}}")
|
|
75
|
+
if resolved != commit:
|
|
76
|
+
raise ValueError(f"{fact['id']}: revision mismatch")
|
|
77
|
+
raw = git(repo, "show", f"{commit}:{fact['path']}")
|
|
78
|
+
if fact["format"] == "json":
|
|
79
|
+
parsed = json.loads(raw)
|
|
80
|
+
value = nested(parsed, fact["field"])
|
|
81
|
+
elif fact["format"] == "toml":
|
|
82
|
+
parsed = tomllib.loads(raw)
|
|
83
|
+
value = nested(parsed, fact["field"])
|
|
84
|
+
elif fact["format"] == "go.mod":
|
|
85
|
+
value = go_mod_value(raw, fact["field"])
|
|
86
|
+
else:
|
|
87
|
+
raise ValueError(f"unknown parser: {fact['format']}")
|
|
88
|
+
rendered = json.dumps(value, ensure_ascii=False, separators=(",", ":")) if isinstance(value, list) else str(value)
|
|
89
|
+
if rendered != fact["expected"]:
|
|
90
|
+
raise ValueError(f"{fact['id']}: parsed value {rendered!r} != pinned expected value {fact['expected']!r}")
|
|
91
|
+
ln = line_for(raw, fact["field"], value if not isinstance(value, list) else rendered)
|
|
92
|
+
facts.append({"id": fact["id"], "kind": "fact", "value": value, "evidence": {"commit": commit, "path": fact["path"], "field": fact["field"], "line": ln}})
|
|
93
|
+
report["repositories"].append({"id": item["id"], "url": item["url"], "branch": item["branch"], "commit": item["commit"], "tree": tree, "license": item["license"], "facts": facts})
|
|
94
|
+
report["prose_claims"] = spec["prose_claims"]
|
|
95
|
+
questions = json.loads(Path(__file__).with_name("questions_dev.json").read_text(encoding="utf-8"))
|
|
96
|
+
known = {fact["id"] for repo in report["repositories"] for fact in repo["facts"]}
|
|
97
|
+
if any(question["fact_id"] not in known for question in questions["questions"]):
|
|
98
|
+
raise ValueError("question references an unknown fact")
|
|
99
|
+
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
100
|
+
print(f"wrote {len(known)} checked facts and {len(report['prose_claims'])} prose-claim labels to {args.output}")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
try:
|
|
105
|
+
main()
|
|
106
|
+
except (KeyError, IndexError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
|
|
107
|
+
print(f"oracle build failed closed: {exc}", file=sys.stderr)
|
|
108
|
+
raise SystemExit(2)
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Fail-closed, source-only public repository oracle builder (DEV v2)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import tomllib
|
|
12
|
+
|
|
13
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
14
|
+
CLONES = ROOT / "scratch" / "public_repo_candidates_20260927"
|
|
15
|
+
MANIFEST = Path(__file__).with_name("manifest_v2.json")
|
|
16
|
+
QUESTIONS = Path(__file__).with_name("questions_dev_v2.json")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def git(repo: Path, *args: str) -> str:
|
|
20
|
+
return subprocess.check_output(["git", "-C", str(repo), *args], text=True, stderr=subprocess.PIPE).strip()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def normalized(text: str) -> str:
|
|
24
|
+
return " ".join(text.split())
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_path(data, field):
|
|
28
|
+
for part in re.sub(r"\[(\d+)\]", r".\1", field).split("."):
|
|
29
|
+
data = data[int(part)] if part.isdigit() else data[part]
|
|
30
|
+
return data
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def go_mod(text: str):
|
|
34
|
+
"""Parse the module/go directives and require entries used by this oracle."""
|
|
35
|
+
out = {}
|
|
36
|
+
in_require_block = False
|
|
37
|
+
for line in text.splitlines():
|
|
38
|
+
m = re.match(r"^\s*(module|go)\s+(\S+)\s*$", line)
|
|
39
|
+
if m:
|
|
40
|
+
out[m.group(1)] = m.group(2)
|
|
41
|
+
continue
|
|
42
|
+
if re.match(r"^\s*require\s*\(\s*$", line):
|
|
43
|
+
in_require_block = True
|
|
44
|
+
continue
|
|
45
|
+
if in_require_block and re.match(r"^\s*\)\s*$", line):
|
|
46
|
+
in_require_block = False
|
|
47
|
+
continue
|
|
48
|
+
requirement = re.match(r"^\s*require\s+([^\s()]+)\s+(v[^\s]+)(?:\s+//.*)?$", line)
|
|
49
|
+
member = re.match(r"^\s*([^\s()]+)\s+(v[^\s]+)(?:\s+//.*)?$", line) if in_require_block else None
|
|
50
|
+
match = requirement or member
|
|
51
|
+
if match:
|
|
52
|
+
out.setdefault("require", {})[match.group(1)] = match.group(2)
|
|
53
|
+
if "module" not in out or "go" not in out:
|
|
54
|
+
raise ValueError("go.mod parser did not find module and go directives")
|
|
55
|
+
return out
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def verify_proof(repo, proof):
|
|
59
|
+
commit = git(repo, "rev-parse", f"{proof['commit']}^{{commit}}")
|
|
60
|
+
if commit != proof["commit"].rstrip("^") and not proof["commit"].endswith("^"):
|
|
61
|
+
raise ValueError(f"revision did not resolve exactly: {proof['commit']}")
|
|
62
|
+
raw = git(repo, "show", f"{proof['commit']}:{proof['path']}") if "path" in proof else git(repo, "show", "-s", "--format=%B", proof["commit"])
|
|
63
|
+
ptype = proof["type"]
|
|
64
|
+
if ptype in ("json", "json_absent"):
|
|
65
|
+
parsed = json.loads(raw)
|
|
66
|
+
if ptype == "json":
|
|
67
|
+
actual = get_path(parsed, proof["field"])
|
|
68
|
+
if str(actual) != proof["value"]:
|
|
69
|
+
raise ValueError(f"JSON mismatch {proof['field']}: {actual!r}")
|
|
70
|
+
return {"commit": commit, "path": proof["path"], "field": proof["field"], "line": source_line(raw, proof['field'].split('.')[-1], proof['value'])}
|
|
71
|
+
table = get_path(parsed, proof["field"])
|
|
72
|
+
if not isinstance(table, dict) or proof["value"] in table:
|
|
73
|
+
raise ValueError(f"bounded JSON absence disproved: {proof['field']}.{proof['value']}")
|
|
74
|
+
return {"commit": commit, "path": proof["path"], "field": proof["field"], "line": source_line(raw, f'"{proof["field"].split(".")[-1]}"', "")}
|
|
75
|
+
if ptype in ("toml", "toml_absent"):
|
|
76
|
+
parsed = tomllib.loads(raw)
|
|
77
|
+
if ptype == "toml":
|
|
78
|
+
actual = get_path(parsed, proof["field"])
|
|
79
|
+
if str(actual) != proof["value"]:
|
|
80
|
+
raise ValueError(f"TOML mismatch {proof['field']}: {actual!r}")
|
|
81
|
+
return {"commit": commit, "path": proof["path"], "field": proof["field"], "line": source_line(raw, proof['field'].split('.')[-1], proof['value'])}
|
|
82
|
+
try:
|
|
83
|
+
table = get_path(parsed, proof["field"])
|
|
84
|
+
except (KeyError, IndexError, TypeError):
|
|
85
|
+
table = []
|
|
86
|
+
if proof["value"] in table:
|
|
87
|
+
raise ValueError(f"bounded TOML absence disproved: {proof['field']} contains {proof['value']}")
|
|
88
|
+
scope = proof["field"].split(".")[0]
|
|
89
|
+
line = source_line(raw, f"[{scope}]", "")
|
|
90
|
+
return {"commit": commit, "path": proof["path"], "field": proof["field"] + " (bounded list/table)", "line": line}
|
|
91
|
+
if ptype in ("go_mod", "go_mod_absent"):
|
|
92
|
+
parsed = go_mod(raw)
|
|
93
|
+
if ptype == "go_mod":
|
|
94
|
+
actual = parsed[proof["field"]] if proof["field"] in ("module", "go") else parsed["require"][proof["field"].removeprefix("require.")]
|
|
95
|
+
if actual != proof["value"]:
|
|
96
|
+
raise ValueError(f"go.mod mismatch {proof['field']}: {actual!r}")
|
|
97
|
+
needle = proof["field"] if proof["field"] in ("module", "go") else proof["field"].removeprefix("require.")
|
|
98
|
+
return {"commit": commit, "path": proof["path"], "field": proof["field"], "line": source_line(raw, needle, proof['value'])}
|
|
99
|
+
if proof["value"] in parsed["require"]:
|
|
100
|
+
raise ValueError(f"bounded go.mod absence disproved: {proof['value']}")
|
|
101
|
+
return {"commit": commit, "path": proof["path"], "field": "require (finite module list)", "line": source_line(raw, "require", "")}
|
|
102
|
+
if ptype in ("quote", "commit_text"):
|
|
103
|
+
if normalized(proof["quote"]) not in normalized(raw):
|
|
104
|
+
raise ValueError(f"source quote not present at {proof.get('path', 'commit message')}")
|
|
105
|
+
line = quoted_start_line(raw, proof["quote"])
|
|
106
|
+
return {"commit": commit, "path": proof.get("path", "COMMIT_MESSAGE"), "field": "quoted source text", "line": line}
|
|
107
|
+
raise ValueError(f"unknown proof type: {ptype}")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def source_line(text, key, value):
|
|
111
|
+
for n, line in enumerate(text.splitlines(), 1):
|
|
112
|
+
if key in line and (not value or value in line):
|
|
113
|
+
return n
|
|
114
|
+
raise ValueError(f"cannot locate source line for {key}={value}")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def quoted_start_line(text, quote):
|
|
118
|
+
tokens = [re.sub(r"^[#*`\[(]+|[#*`\]),.;:]+$", "", token) for token in quote.split()]
|
|
119
|
+
tokens = [token for token in tokens if token]
|
|
120
|
+
for number, line in enumerate(text.splitlines(), 1):
|
|
121
|
+
if tokens and tokens[0] in line and (len(tokens) == 1 or tokens[1] in line):
|
|
122
|
+
return number
|
|
123
|
+
raise ValueError(f"cannot locate quoted passage start: {quote[:50]}")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main():
|
|
127
|
+
ap = argparse.ArgumentParser()
|
|
128
|
+
ap.add_argument("--output", type=Path, default=Path(__file__).with_name("oracle_dev_v2.json"))
|
|
129
|
+
args = ap.parse_args()
|
|
130
|
+
spec = json.loads(MANIFEST.read_text(encoding="utf-8"))
|
|
131
|
+
questions = json.loads(QUESTIONS.read_text(encoding="utf-8"))
|
|
132
|
+
for repo_spec in spec["repositories"]:
|
|
133
|
+
repo = CLONES / repo_spec["id"]
|
|
134
|
+
if git(repo, "rev-parse", "HEAD") != repo_spec["commit"]:
|
|
135
|
+
raise ValueError(f"{repo_spec['id']}: HEAD mismatch")
|
|
136
|
+
if git(repo, "rev-parse", f"{repo_spec['commit']}^{{tree}}") != repo_spec["tree"]:
|
|
137
|
+
raise ValueError(f"{repo_spec['id']}: tree mismatch")
|
|
138
|
+
fact_ids = [f["id"] for f in spec["facts"]]
|
|
139
|
+
prompt_ids = [q["prompt_id"] for q in questions["questions"]]
|
|
140
|
+
if len(fact_ids) != len(set(fact_ids)) or len(prompt_ids) != len(set(prompt_ids)):
|
|
141
|
+
raise ValueError("duplicate fact or prompt IDs")
|
|
142
|
+
projected_ids = {identifier.replace("V2-", "PR-") for identifier in fact_ids}
|
|
143
|
+
if len(spec["facts"]) != 30 or projected_ids != set(prompt_ids):
|
|
144
|
+
raise ValueError("v2 gate requires exactly 30 one-to-one fact/prompt IDs")
|
|
145
|
+
question_repos = {q["prompt_id"]: q["repo"] for q in questions["questions"]}
|
|
146
|
+
for fact in spec["facts"]:
|
|
147
|
+
prompt_id = fact["id"].replace("V2-", "PR-")
|
|
148
|
+
if question_repos.get(prompt_id) != fact["repo"]:
|
|
149
|
+
raise ValueError(f"prompt repository mismatch for {fact['id']}")
|
|
150
|
+
out_facts = []
|
|
151
|
+
for fact in spec["facts"]:
|
|
152
|
+
repo = CLONES / fact["repo"]
|
|
153
|
+
evidence = [verify_proof(repo, proof) for proof in fact["proof"]]
|
|
154
|
+
out_facts.append({"fact_id": fact["id"], "repo": fact["repo"], "stratum": fact["stratum"], "answer": fact["answer"], "kind": "fact" if fact["stratum"] not in ("decision_rationale",) else "prose_claim", "evidence": evidence})
|
|
155
|
+
required = {"current_structured", "historical_change", "decision_rationale", "conflict_supersession", "bounded_absence"}
|
|
156
|
+
strata = {f["stratum"] for f in spec["facts"]}
|
|
157
|
+
if not required <= strata:
|
|
158
|
+
raise ValueError(f"missing strata: {sorted(required-strata)}")
|
|
159
|
+
report = {"schema": spec["schema"], "repositories": spec["repositories"], "facts": out_facts, "gaps": spec["gaps"]}
|
|
160
|
+
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
161
|
+
print(f"wrote {len(out_facts)} verified facts across {len(strata)} strata")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
if __name__ == "__main__":
|
|
165
|
+
try:
|
|
166
|
+
main()
|
|
167
|
+
except (KeyError, IndexError, TypeError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
|
|
168
|
+
print(f"oracle v2 build failed closed: {exc}", file=sys.stderr)
|
|
169
|
+
raise SystemExit(2)
|