Files
NODEDC_MISSION_CORE/simulation/semantic-learning/agent_cycle.py
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

688 lines
30 KiB
Python

"""Bounded, root-gated annotation workflow; executor is the active Codex session.
Uses separate tables in the Worker learning queue. Never consumes builder jobs,
launches a model, promotes supervision or writes a live map. Actor identities are
assigned by the trusted dispatcher, not supplied by an LLM response. This local
ledger is an orchestration boundary, not an authentication service.
"""
import argparse
import json
import re
import sqlite3
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
from dataset_store import checksum, confined, digest
from region_coverage import validate_packet
SCHEMA = "missioncore.semantic-agent-cycle/v1"
SCHEMA_V2 = "missioncore.semantic-agent-cycle/v2"
MAX_JSON = 2 * 1024**2
MAX_LEDGER_JSON = 128 * 1024**2
MAX_PLAN = 256 * 1024
MAX_RESULT = 48 * 1024
MAX_ROOT_REVIEW = 32 * 1024
def encode(value):
result = json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False)
if len(result.encode()) > MAX_JSON:
raise ValueError("Agent record byte budget exceeded")
return result
def text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 4096:
raise ValueError("Bounded nonempty text required")
return value
def actor_id(value):
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_./:-]{1,160}", value):
raise ValueError("Bounded canonical actor or unit ID required")
return value
class Cycle:
def __init__(self, root, *, clock=time.time):
self.root, self.clock = Path(root).resolve(), clock
self.root.mkdir(parents=True, exist_ok=True)
self.db = sqlite3.connect(self.root / "queue.sqlite3", timeout=10)
self.db.row_factory = sqlite3.Row
self.db.execute("PRAGMA synchronous=FULL")
self.db.executescript("""
CREATE TABLE IF NOT EXISTS agent_cycles (
id TEXT PRIMARY KEY, plan TEXT NOT NULL, state TEXT NOT NULL,
created REAL NOT NULL, deadline REAL NOT NULL, root_review TEXT);
CREATE TABLE IF NOT EXISTS agent_tasks (
cycle TEXT NOT NULL, unit TEXT NOT NULL, stage TEXT NOT NULL,
state TEXT NOT NULL, attempt INTEGER NOT NULL DEFAULT 0,
token TEXT, actor TEXT, expires REAL, result TEXT, result_sha TEXT,
PRIMARY KEY(cycle, unit, stage));
CREATE TABLE IF NOT EXISTS agent_attempts (
token TEXT PRIMARY KEY, cycle TEXT NOT NULL, unit TEXT NOT NULL,
stage TEXT NOT NULL, actor TEXT NOT NULL, started REAL NOT NULL,
finished REAL, result TEXT, result_sha TEXT, stopped_evidence TEXT);
CREATE TABLE IF NOT EXISTS agent_dispatch_receipts (
token TEXT PRIMARY KEY, executor_ref TEXT NOT NULL,
recorded REAL NOT NULL, evidence TEXT NOT NULL);
""")
def close(self):
self.db.close()
@contextmanager
def transaction(self):
self.db.execute("BEGIN IMMEDIATE")
try:
yield
self.db.commit()
except BaseException:
self.db.rollback()
raise
def pins(self, unit):
for pin in unit["sources"]:
if set(pin) != {"path", "sha256", "bytes"}:
raise ValueError("Exact source pin required")
path = confined(self.root, pin["path"])
if not 0 < pin["bytes"] <= 24 * 1024**2:
raise ValueError("Source byte budget exceeded")
if path.stat().st_size != pin["bytes"] or checksum(path) != pin["sha256"]:
raise ValueError("Pinned source changed")
validate_packet(self.root, unit)
def capacity(self, additional):
used = 0
for table, column in (
("agent_cycles", "plan"),
("agent_cycles", "root_review"),
("agent_tasks", "result"),
("agent_attempts", "result"),
("agent_dispatch_receipts", "executor_ref"),
("agent_dispatch_receipts", "evidence"),
):
used += self.db.execute(
f"SELECT COALESCE(SUM(length(CAST({column} AS BLOB))),0) FROM {table}"
).fetchone()[0]
if used + additional > MAX_LEDGER_JSON:
raise ValueError("Agent evidence quota reached; archive closed cycles first")
@staticmethod
def fingerprint(plan):
units = [
dict(
group=u["physical_group"],
payload=u["payload"],
sources=sorted(p["sha256"] for p in u["sources"]),
)
for u in plan["units"]
]
return digest(
dict(
recipe=plan["recipe"],
baseline=plan["baseline_sha256"],
units=sorted(units, key=digest),
)
)
def begin(self, plan):
encoded, identity = encode(plan), digest(plan)
if len(encoded.encode()) > MAX_PLAN:
raise ValueError("Plan byte budget exceeded")
version = plan.get("schema_version")
if set(plan) != {
"schema_version",
"root_actor",
"objective",
"baseline_sha256",
"recipe",
"acceptance",
"limits",
"units",
"parent",
} | ({"objective_contract"} if version == SCHEMA_V2 else set()) or version not in {
SCHEMA,
SCHEMA_V2,
}:
raise ValueError("Unsupported agent plan")
for key in ("root_actor", "objective", "baseline_sha256", "recipe", "acceptance"):
text(plan[key])
actor_id(plan["root_actor"])
limits = plan["limits"]
ceilings = dict(parallel=3, attempts=2, dispatches=48, seconds=86400, lease_seconds=3600)
if set(limits) != set(ceilings) or any(
type(limits[k]) is not int or not 1 <= limits[k] <= cap for k, cap in ceilings.items()
):
raise ValueError("Invalid bounded limits")
if limits["lease_seconds"] > limits["seconds"]:
raise ValueError("Lease exceeds iteration deadline")
units = plan["units"]
if not 1 <= len(units) <= 12 or len({u["id"] for u in units}) != len(units):
raise ValueError("One to twelve unique units required")
for unit in units:
if set(unit) != {"id", "physical_group", "split", "sources", "payload"}:
raise ValueError("Invalid unit packet")
actor_id(unit["id"])
text(unit["physical_group"])
if unit["split"] != "train" or not 1 <= len(unit["sources"]) <= 16:
raise ValueError("Pilot accepts only pinned TRAIN evidence")
self.pins(unit)
if version == SCHEMA_V2:
contract = plan["objective_contract"]
if not isinstance(contract, dict) or set(contract) != {
"deliverable",
"min_admitted_units",
"required_checks",
}:
raise ValueError("Explicit annotation objective contract required")
text(contract["deliverable"])
target, checks = contract["min_admitted_units"], contract["required_checks"]
if type(target) is not int or not 1 <= target <= len(units):
raise ValueError("Objective target must be feasible for planned units")
if limits["dispatches"] < 2 * target:
raise ValueError("Dispatch budget cannot satisfy annotation and review target")
if not isinstance(checks, list) or not 1 <= len(checks) <= 12:
raise ValueError("One to twelve frozen objective checks required")
for check in checks:
actor_id(check)
if len(set(checks)) != len(checks):
raise ValueError("Unique objective checks required")
if limits["parallel"] > 2:
raise ValueError("V2 permits at most two active executors")
now = self.clock()
with self.transaction():
old = self.db.execute("SELECT id FROM agent_cycles WHERE id=?", (identity,)).fetchone()
if old:
return identity
if self.db.execute("SELECT 1 FROM agent_cycles WHERE state!='closed'").fetchone():
raise ValueError("Root must close the current iteration first")
parent = plan["parent"]
latest = self.db.execute(
"SELECT * FROM agent_cycles ORDER BY created DESC, rowid DESC LIMIT 1"
).fetchone()
if latest:
review = json.loads(latest["root_review"])
if parent != latest["id"] or review["next"] == "stop":
raise ValueError("Successor needs the latest root continuation")
old_plan = json.loads(latest["plan"])
if self.fingerprint(plan) == self.fingerprint(old_plan):
raise ValueError("No progress: revise evidence or recipe before retrying")
elif parent is not None:
raise ValueError("Unknown parent")
self.capacity(len(encoded.encode()))
self.db.execute(
"INSERT INTO agent_cycles VALUES(?,?,?,?,?,NULL)",
(identity, encoded, "running", now, now + limits["seconds"]),
)
self.db.executemany(
"INSERT INTO agent_tasks(cycle,unit,stage,state) VALUES(?,?,?,?)",
[(identity, u["id"], "annotate", "ready") for u in units],
)
return identity
def _cycle(self, identity):
row = self.db.execute("SELECT * FROM agent_cycles WHERE id=?", (identity,)).fetchone()
if row is None:
raise ValueError("Unknown iteration")
return row, json.loads(row["plan"])
def _settle(self, identity):
row, plan = self._cycle(identity)
if row["state"] == "closed":
return
now = self.clock()
self.db.execute(
"UPDATE agent_tasks SET state='interrupted' "
"WHERE cycle=? AND state='active' AND expires<=?",
(identity, now),
)
dispatched = self.db.execute(
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (identity,)
).fetchone()[0]
if now >= row["deadline"] or dispatched >= plan["limits"]["dispatches"]:
self.db.execute(
"UPDATE agent_tasks SET state='blocked' WHERE cycle=? AND state='ready'",
(identity,),
)
if now >= row["deadline"]:
self.db.execute(
"UPDATE agent_tasks SET state='interrupted' WHERE cycle=? AND state='active'",
(identity,),
)
pending = self.db.execute(
"SELECT 1 FROM agent_tasks WHERE cycle=? AND state IN ('ready','active')", (identity,)
).fetchone()
self.db.execute(
"UPDATE agent_cycles SET state=? WHERE id=?",
("running" if pending else "root_pending", identity),
)
def claim(self, identity, unit_id, stage, actor):
actor_id(actor)
with self.transaction():
self._settle(identity)
now = self.clock()
row, plan = self._cycle(identity)
if row["state"] != "running":
raise ValueError("Iteration is waiting for root")
task = self.db.execute(
"SELECT * FROM agent_tasks WHERE cycle=? AND unit=? AND stage=?",
(identity, unit_id, stage),
).fetchone()
if task is None or task["state"] != "ready":
raise ValueError("Task is not claimable")
if plan["schema_version"] == SCHEMA_V2:
if self._unconfirmed_handoffs(identity):
raise ValueError("Confirm outstanding handoff or reconcile it before claiming")
if (
stage == "annotate"
and self.db.execute(
"SELECT 1 FROM agent_tasks WHERE cycle=? "
"AND stage='review' AND state='ready'",
(identity,),
).fetchone()
):
raise ValueError("Ready reviews must be dispatched before another author")
active = self.db.execute(
"SELECT COUNT(*) FROM agent_tasks WHERE state IN ('active','interrupted')"
).fetchone()[0]
if active >= plan["limits"]["parallel"]:
raise ValueError("Global agent concurrency exhausted")
if stage == "review":
author = self.db.execute(
"SELECT actor FROM agent_tasks WHERE cycle=? AND unit=? AND stage='annotate'",
(identity, unit_id),
).fetchone()[0]
if actor == author:
raise ValueError("Author cannot review their own proposal")
unit = next(u for u in plan["units"] if u["id"] == unit_id)
self.pins(unit)
now = self.clock()
if now >= row["deadline"]:
raise ValueError("Iteration deadline passed during input verification")
token = uuid.uuid4().hex
expires = min(now + plan["limits"]["lease_seconds"], row["deadline"])
self.db.execute(
"UPDATE agent_tasks SET state='active',attempt=attempt+1,token=?,actor=?,expires=? "
"WHERE cycle=? AND unit=? AND stage=?",
(token, actor, expires, identity, unit_id, stage),
)
self.db.execute(
"INSERT INTO agent_attempts(token,cycle,unit,stage,actor,started) "
"VALUES(?,?,?,?,?,?)",
(token, identity, unit_id, stage, actor, now),
)
packet = dict(
cycle=identity, unit=unit, stage=stage, token=token, actor=actor, expires=expires
)
if stage == "review":
proposal = self.db.execute(
"SELECT result,result_sha FROM agent_tasks "
"WHERE cycle=? AND unit=? AND stage='annotate'",
(identity, unit_id),
).fetchone()
packet.update(proposal=json.loads(proposal[0]), proposal_sha256=proposal[1])
return packet
def _unconfirmed_handoffs(self, identity):
return [
dict(row)
for row in self.db.execute(
"SELECT t.token,t.unit,t.stage,t.actor,t.expires FROM agent_tasks t "
"LEFT JOIN agent_dispatch_receipts d ON d.token=t.token "
"WHERE t.cycle=? AND t.state IN ('active','interrupted') AND d.token IS NULL "
"ORDER BY t.unit,t.stage",
(identity,),
)
]
def confirm_dispatch(self, token, root_actor, executor_ref, evidence):
"""Record a real handoff after sending; absence never proves no executor exists."""
actor_id(executor_ref)
text(evidence)
with self.transaction():
attempt = self.db.execute(
"SELECT * FROM agent_attempts WHERE token=?", (token,)
).fetchone()
if attempt is None:
raise ValueError("Unknown claim")
row, plan = self._cycle(attempt["cycle"])
if root_actor != plan["root_actor"] or plan["schema_version"] != SCHEMA_V2:
raise ValueError("V2 root dispatch confirmation required")
previous = self.db.execute(
"SELECT * FROM agent_dispatch_receipts WHERE token=?", (token,)
).fetchone()
if previous:
if (previous["executor_ref"], previous["evidence"]) != (executor_ref, evidence):
raise ValueError("Conflicting dispatch receipt")
return dict(previous)
task = self.db.execute("SELECT * FROM agent_tasks WHERE token=?", (token,)).fetchone()
if (
task is None
or task["state"] not in {"active", "interrupted", "done"}
or (row["state"] == "closed" and task["state"] != "done")
):
raise ValueError("Cannot confirm a closed or superseded handoff")
self.capacity(len(executor_ref.encode()) + len(evidence.encode()))
recorded = self.clock()
self.db.execute(
"INSERT INTO agent_dispatch_receipts VALUES(?,?,?,?)",
(token, executor_ref, recorded, evidence),
)
return dict(
token=token, executor_ref=executor_ref, recorded=recorded, evidence=evidence
)
def complete(self, token, actor, result):
encoded, sha = encode(result), digest(result)
if len(encoded.encode()) > MAX_RESULT:
raise ValueError("Result byte budget exceeded")
with self.transaction():
attempt = self.db.execute(
"SELECT * FROM agent_attempts WHERE token=?", (token,)
).fetchone()
if attempt is None or attempt["actor"] != actor:
raise ValueError("Claim ownership mismatch")
if attempt["result"] is not None:
if attempt["result_sha"] != sha:
raise ValueError("Changed duplicate completion")
return sha
identity, unit_id, stage = (attempt[k] for k in ("cycle", "unit", "stage"))
row, plan = self._cycle(identity)
task = self.db.execute(
"SELECT * FROM agent_tasks WHERE cycle=? AND unit=? AND stage=?",
(identity, unit_id, stage),
).fetchone()
if (
row["state"] == "closed"
or task["token"] != token
or task["state"] != "active"
or self.clock() >= min(task["expires"], row["deadline"])
):
raise ValueError("Expired or superseded claim; root must reconcile executor")
self.pins(next(u for u in plan["units"] if u["id"] == unit_id))
text(result.get("reason"))
if stage == "review":
proposal = self.db.execute(
"SELECT result_sha FROM agent_tasks "
"WHERE cycle=? AND unit=? AND stage='annotate'",
(identity, unit_id),
).fetchone()[0]
if result.get("proposal_sha256") != proposal or result.get("verdict") not in {
"accept",
"reject",
}:
raise ValueError("Review must bind the exact proposal")
self.capacity(2 * len(encoded.encode()))
now = self.clock()
if now >= min(task["expires"], row["deadline"]):
raise ValueError(
"Claim expired during result validation; root must reconcile executor"
)
self.db.execute(
"UPDATE agent_attempts SET finished=?,result=?,result_sha=? WHERE token=?",
(now, encoded, sha, token),
)
self.db.execute(
"UPDATE agent_tasks SET state='done',result=?,result_sha=? WHERE token=?",
(encoded, sha, token),
)
if stage == "annotate":
self.db.execute(
"INSERT INTO agent_tasks(cycle,unit,stage,state) VALUES(?,?,'review','ready')",
(identity, unit_id),
)
self._settle(identity)
return sha
def reconcile(self, token, root_actor, stopped_evidence, *, retry=False):
"""Trusted root verifies executor termination BEFORE releasing reservation."""
text(stopped_evidence)
with self.transaction():
task = self.db.execute("SELECT * FROM agent_tasks WHERE token=?", (token,)).fetchone()
if task is None:
raise ValueError("Unknown claim")
row, plan = self._cycle(task["cycle"])
if root_actor != plan["root_actor"] or row["state"] == "closed":
raise ValueError("Root reconciliation required")
if task["state"] not in {"active", "interrupted"}:
raise ValueError("Only unfinished executor may be reconciled")
count = self.db.execute(
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (task["cycle"],)
).fetchone()[0]
allowed = (
task["attempt"] < plan["limits"]["attempts"]
and count < plan["limits"]["dispatches"]
and self.clock() < row["deadline"]
)
if retry and not allowed:
raise ValueError("Retry budget exhausted")
self.db.execute(
"UPDATE agent_attempts SET finished=?,stopped_evidence=? WHERE token=?",
(self.clock(), stopped_evidence, token),
)
self.db.execute(
"UPDATE agent_tasks SET state=?,token=NULL WHERE token=?",
("ready" if retry else "blocked", token),
)
self._settle(task["cycle"])
def cancel_ready(self, identity, root_actor, reason):
"""Root cancels undispatched work without releasing executor reservations."""
text(reason)
result = dict(reason=reason, disposition="cancelled_by_root")
encoded, sha = encode(result), digest(result)
with self.transaction():
row, plan = self._cycle(identity)
if root_actor != plan["root_actor"] or row["state"] == "closed":
raise ValueError("Root cancellation requires an open iteration")
count = self.db.execute(
"SELECT COUNT(*) FROM agent_tasks WHERE cycle=? AND state='ready'",
(identity,),
).fetchone()[0]
if count:
self.capacity(count * len(encoded.encode()))
self.db.execute(
"UPDATE agent_tasks SET state='blocked',result=?,result_sha=? "
"WHERE cycle=? AND state='ready'",
(encoded, sha, identity),
)
self._settle(identity)
return dict(cancelled=count)
def status(self, identity):
with self.transaction():
return self._status(identity)
def _status(self, identity):
"""Read settled state while the caller holds the transaction."""
self._settle(identity)
row, plan = self._cycle(identity)
tasks = [
dict(r)
for r in self.db.execute(
"SELECT * FROM agent_tasks WHERE cycle=? ORDER BY unit,stage", (identity,)
)
]
for task in tasks:
if task["result"]:
task["result"] = json.loads(task["result"])
sample = min((u["id"] for u in plan["units"]), key=lambda u: digest([identity, u]))
flagged = sorted(
{
t["unit"]
for t in tasks
if t["state"] != "done"
or (t["stage"] == "review" and t["result"]["verdict"] == "reject")
}
)
snapshot = dict(
id=identity,
state=row["state"],
plan=plan,
tasks=tasks,
root_required_units=sorted({sample, *flagged}),
dispatches=self.db.execute(
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (identity,)
).fetchone()[0],
root_review=json.loads(row["root_review"]) if row["root_review"] else None,
)
if plan["schema_version"] == SCHEMA_V2:
review = snapshot["root_review"] or {}
snapshot.update(
unconfirmed_handoffs=self._unconfirmed_handoffs(identity),
ready_tasks=[
dict(unit=t["unit"], stage=t["stage"])
for t in sorted(
(t for t in tasks if t["state"] == "ready"),
key=lambda t: (t["stage"] != "review", t["unit"]),
)
],
progress=dict(
planned=len(plan["units"]),
proposed=sum(t["stage"] == "annotate" and t["state"] == "done" for t in tasks),
reviewed=sum(t["stage"] == "review" and t["state"] == "done" for t in tasks),
review_accepted=sum(
t["stage"] == "review"
and t["state"] == "done"
and t["result"]["verdict"] == "accept"
for t in tasks
),
admitted=len(review.get("admitted_units", [])),
blocked=sum(t["state"] == "blocked" for t in tasks),
unreconciled=sum(t["state"] == "interrupted" for t in tasks),
target=plan["objective_contract"]["min_admitted_units"],
objective_outcome=review.get("objective_outcome"),
),
)
return snapshot
def decide(self, identity, actor, review):
encoded = encode(review)
if len(encoded.encode()) > MAX_ROOT_REVIEW:
raise ValueError("Root review byte budget exceeded")
with self.transaction():
snapshot = self._status(identity)
plan = snapshot["plan"]
if actor != plan["root_actor"] or snapshot["state"] != "root_pending":
raise ValueError("Root decision only at terminal iteration")
if any(t["state"] == "interrupted" for t in snapshot["tasks"]):
raise ValueError("Unconfirmed executors still reserve resources")
if (
set(review)
!= {
"verdict",
"next",
"reason",
"inspected_units",
"admitted_units",
"checks",
"tuning",
}
| (
{"objective_outcome", "objective_checks", "outcome_reason", "remaining_work"}
if plan["schema_version"] == SCHEMA_V2
else set()
)
or review["verdict"] not in {"accepted", "rejected"}
or review["next"] not in {"continue", "revise", "stop"}
):
raise ValueError("Explicit root verdict and next action required")
text(review["reason"])
text(review["tuning"])
if plan["schema_version"] == SCHEMA_V2:
contract, checks = plan["objective_contract"], review["objective_checks"]
outcome = review["objective_outcome"]
if (
outcome not in {"achieved", "not_achieved", "inconclusive"}
or not isinstance(checks, dict)
or set(checks) != set(contract["required_checks"])
or any(type(v) is not bool for v in checks.values())
):
raise ValueError("Exact frozen objective checks and outcome required")
text(review["outcome_reason"])
remaining = review["remaining_work"]
if not isinstance(remaining, list) or len(remaining) > 12:
raise ValueError("Bounded remaining work required")
for item in remaining:
text(item)
if outcome == "achieved":
if (
review["verdict"] != "accepted"
or not all(checks.values())
or len(review["admitted_units"]) < contract["min_admitted_units"]
or remaining
):
raise ValueError("Objective target/checks not achieved")
elif not remaining:
raise ValueError("Unmet objective needs remaining work or blocker")
if not set(snapshot["root_required_units"]).issubset(review["inspected_units"]):
raise ValueError("Inspect flagged and preselected units")
admitted = review["admitted_units"]
if not isinstance(admitted, list) or len(set(admitted)) != len(admitted):
raise ValueError("Unique admitted unit list required")
approved = {
t["unit"]
for t in snapshot["tasks"]
if t["stage"] == "review"
and t["state"] == "done"
and t["result"]["verdict"] == "accept"
}
if review["verdict"] == "accepted":
if (
not admitted
or not set(admitted).issubset(approved)
or not review["checks"]
or any(v is not True for v in review["checks"].values())
):
raise ValueError("Cannot accept failed or incomplete evidence")
for unit in plan["units"]:
self.pins(unit)
elif admitted or review["next"] == "continue":
raise ValueError("Rejected iteration cannot admit units or continue unchanged")
self.capacity(len(encoded.encode()))
self.db.execute(
"UPDATE agent_cycles SET state='closed',root_review=? WHERE id=?",
(encoded, identity),
)
return digest(review)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--store", required=True)
parser.add_argument(
"action",
choices=[
"begin",
"status",
"claim",
"confirm_dispatch",
"complete",
"reconcile",
"cancel_ready",
"decide",
],
)
parser.add_argument(
"--request", required=True, help="Bounded JSON arguments; actor assigned by dispatcher"
)
args = parser.parse_args()
path = Path(args.request)
if path.stat().st_size > MAX_JSON:
raise ValueError("Request too large")
request = json.loads(path.read_text(encoding="utf-8"))
cycle = Cycle(args.store)
try:
print(encode(getattr(cycle, args.action)(**request)))
finally:
cycle.close()
if __name__ == "__main__":
main()