Files
NODEDC_MISSION_CORE/simulation/semantic-learning/research_gate.py
T
DCCONSTRUCTIONS 25dc0a1b44 feat(semantics): add portable annotation, learning and review contracts
Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
2026-10-29 09:10:00 +03:00

189 lines
7.9 KiB
Python

"""Read-only research proposals -> bounded root decision, never executable work.
The active root session supplies identities and verifies facts. This validates
artifact structure/provenance, not truth or authentication. It neither schedules
agents nor mutates the annotation queue, source labels, models or infrastructure.
"""
import argparse
import json
from pathlib import Path
from urllib.parse import urlparse
from dataset_store import checksum, confined, digest, write
SCHEMA = "missioncore.semantic-research/v1"
MAX_BYTES = 32 * 1024
def bounded(value):
if len(json.dumps(value, ensure_ascii=False, allow_nan=False).encode()) > MAX_BYTES:
raise ValueError("Research artifact byte limit exceeded")
return value
def keys(value, fields):
if not isinstance(value, dict) or set(value) != set(fields.split()):
raise ValueError("Unexpected research fields")
def text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 4000:
raise ValueError("Bounded nonempty explanation required")
def review_research(workspace, brief, report, decision):
for value in (brief, report, decision):
bounded(value)
keys(brief, "schema_version root_actor scout_actor trigger question baseline")
if brief["schema_version"] != SCHEMA:
raise ValueError("Unsupported research schema")
for field in ("root_actor", "scout_actor", "question"):
text(brief[field])
if brief["root_actor"] == brief["scout_actor"]:
raise ValueError("Scout cannot be root decision maker")
if brief["trigger"] not in {"user_request", "new_class", "stagnation", "cost_regression"}:
raise ValueError("An explicit research trigger is required")
keys(brief["baseline"], "path sha256")
baseline = confined(Path(workspace).resolve(), brief["baseline"]["path"])
if not baseline.is_file() or baseline.stat().st_size > MAX_BYTES:
raise ValueError("Bounded existing baseline evidence required")
if checksum(baseline) != brief["baseline"]["sha256"]:
raise ValueError("Baseline evidence changed")
keys(report, "brief_sha256 baseline_option sources ideas unknowns recommendation")
if report["brief_sha256"] != digest(brief):
raise ValueError("Research answered a different brief")
for field in ("baseline_option", "unknowns", "recommendation"):
text(report[field])
if not isinstance(report["sources"], list) or len(report["sources"]) > 6:
raise ValueError("Research source budget exceeded")
sources = {}
for source in report["sources"]:
keys(source, "id title url kind checked_utc supports limitations")
for field in source:
text(source[field])
url = urlparse(source["url"])
if url.scheme != "https" or not url.hostname or url.username or url.password:
raise ValueError("Public HTTPS citation required")
if source["kind"] not in {"official_docs", "official_repo", "paper"}:
raise ValueError("Primary sources required")
if source["id"] in sources:
raise ValueError("Duplicate source")
sources[source["id"]] = source
if not isinstance(report["ideas"], list) or len(report["ideas"]) > 3:
raise ValueError("At most three research ideas")
ideas = {}
for idea in report["ideas"]:
keys(
idea,
"id title basis source_ids evidence hypothesis minimal_test "
"success failure cost risks not_applicable",
)
for field in set(idea) - {"source_ids"}:
text(idea[field])
refs = idea["source_ids"]
if (
not isinstance(refs, list)
or len(set(refs)) != len(refs)
or not set(refs).issubset(sources)
):
raise ValueError("Idea has unbound citations")
if idea["basis"] not in {"local_baseline", "external"} or (
idea["basis"] == "external" and not refs
):
raise ValueError("External idea needs evidence; baseline uses the pinned local result")
if idea["id"] in ideas:
raise ValueError("Duplicate idea")
ideas[idea["id"]] = idea
keys(decision, "actor report_sha256 source_checks verdicts test_plan")
if decision["actor"] != brief["root_actor"]:
raise ValueError("Only assigned root may decide")
if decision["report_sha256"] != digest(report):
raise ValueError("Stale root research review")
checks = decision["source_checks"]
if (
not isinstance(checks, list)
or len(set(checks)) != len(checks)
or not set(checks).issubset(sources)
):
raise ValueError("Unknown root source checks")
seen, selected = set(), []
for verdict in decision["verdicts"]:
keys(verdict, "idea_id outcome reason revisit_when")
idea_id = verdict["idea_id"]
if idea_id not in ideas or idea_id in seen:
raise ValueError("Every verdict needs one known idea")
seen.add(idea_id)
if verdict["outcome"] not in {"test", "defer", "reject"}:
raise ValueError("Root must test, defer or reject")
text(verdict["reason"])
text(verdict["revisit_when"])
if verdict["outcome"] == "test":
if not set(ideas[idea_id]["source_ids"]).issubset(checks):
raise ValueError("Root must verify a selected idea's source claims")
selected.append(idea_id)
if seen != set(ideas) or len(selected) > 1:
raise ValueError("Decide every idea and select at most one cheap test")
plan = decision["test_plan"]
if not selected:
if plan is not None:
raise ValueError("No test was selected")
else:
keys(plan, "idea_id control data_selection metric success failure budget")
if plan["idea_id"] != selected[0]:
raise ValueError("Test is not the root-selected idea")
for field in ("control", "data_selection", "metric", "success", "failure"):
text(plan[field])
keys(plan["budget"], "max_units max_dispatches max_wall_seconds gpu_training_runs")
for field, cap in (("max_units", 8), ("max_dispatches", 16), ("max_wall_seconds", 3600)):
value = plan["budget"][field]
if type(value) is not int or not 1 <= value <= cap:
raise ValueError("Cheap experiment draft budget exceeded")
if (
type(plan["budget"]["gpu_training_runs"]) is not int
or plan["budget"]["gpu_training_runs"] != 0
):
raise ValueError("Research cannot authorize training")
return bounded(
dict(
schema_version=SCHEMA,
brief_sha256=digest(brief),
report_sha256=digest(report),
decision_sha256=digest(decision),
selected_idea=selected[0] if selected else None,
next_action="freeze_separate_experiment" if selected else "keep_current_workflow",
execution_authorized=False,
training_authorized=False,
map_write_authorized=False,
verdicts=decision["verdicts"],
draft_test=plan,
)
)
def load(path):
path = Path(path)
if path.stat().st_size > MAX_BYTES:
raise ValueError("Research input exceeds byte limit")
return json.loads(path.read_text(encoding="utf-8"))
def main():
parser = argparse.ArgumentParser(description=__doc__)
for field in ("workspace", "brief", "report", "decision", "output"):
parser.add_argument("--" + field, required=True)
args = parser.parse_args()
result = review_research(
args.workspace, load(args.brief), load(args.report), load(args.decision)
)
output = Path(args.output)
if output.exists() and load(output) != result:
raise ValueError("Research decision artifact already exists with different content")
if not output.exists():
write(output, result)
print(json.dumps(result, ensure_ascii=False))
if __name__ == "__main__":
main()