File size: 22,561 Bytes
fe0ff58 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 | """Shared Cryptographic Seal Resolver, Ledger Auditor, Bridge Fairness & Task Grader."""
from __future__ import annotations
import hashlib
import json
import math
import os
import time
from typing import Any
from core.pack_registry import get_task_bundle, load_task_evaluator, load_task_vault
from core.plugin_base import TaskEvaluatorContext, VerifiedCall
from core.schema_contract import (
all_tokens_well_formed_hex,
extract_seal_tokens,
make_grade_report,
)
from core.vault_bins import resolve_pack_engine
from core.ztp_client import (
McpStdioClient,
is_valid_sha384_hex,
verify_receipt_offline_bytes,
)
def compute_ledger_entry_hash(entry_without_hash: dict[str, Any]) -> str:
"""Compute chained SHA-384 digest over one `call_ledger.jsonl` entry."""
canon = json.dumps(entry_without_hash, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha384(canon).hexdigest()
def extract_model_id_from_call(tool_name: str, args: dict[str, Any], parsed_ans: Any = None) -> str:
"""Infer canonical `<domain>/<card>` or `<solver>` identifier from an MCP tool call."""
if tool_name in ("run_trajectory", "compute_step", "describe_card"):
dom = args.get("domain")
card = args.get("card")
if dom and card:
return f"{dom}/{card}"
if tool_name in ("solve", "describe_solver"):
sol = args.get("solver")
if sol:
return str(sol)
if tool_name in ("run_dataset",):
ds = args.get("dataset") or args.get("domain")
if ds:
return str(ds)
if isinstance(parsed_ans, dict):
if parsed_ans.get("model"):
return str(parsed_ans["model"])
if parsed_ans.get("solver"):
return str(parsed_ans["solver"])
return tool_name
def extract_seals_from_answer(parsed_ans: Any) -> list[str]:
"""Collect all lowercase 96-hex SHA-384 seal fields from an engine JSON response."""
if not isinstance(parsed_ans, dict):
return []
out: list[str] = []
for k in ("run_seal", "solution_seal", "receipt_sha384", "commitment", "seal"):
v = parsed_ans.get(k)
if is_valid_sha384_hex(v) and v not in out:
out.append(v)
chain = parsed_ans.get("chain")
if isinstance(chain, dict):
cs = chain.get("chain_seal")
if is_valid_sha384_hex(cs) and cs not in out:
out.append(cs)
return out
def verify_call_ledger(
ledger_path: str,
*,
task_id: str | None = None,
max_discovery_calls: int | None = None,
max_sim_calls: int | None = None,
) -> dict[str, Any]:
"""Verify SHA-384 chaining & budget counts across `call_ledger.jsonl`."""
if not os.path.isfile(ledger_path):
return {
"ledger_verified": False,
"errors": [f"Missing call_ledger.jsonl at {ledger_path}"],
"records": [],
"discovery_calls_used": 0,
"sim_calls_used": 0,
"disabled_tool_attempts": 0,
"budget_rejected_calls": 0,
}
errors: list[str] = []
records: list[dict[str, Any]] = []
expected_prev = "0" * 96
seq_expected = 0
disc_used = 0
sim_used = 0
disabled_attempts = 0
budget_rejected = 0
with open(ledger_path, "r", encoding="utf-8") as fh:
for line_no, raw_line in enumerate(fh, 1):
s = raw_line.strip()
if not s:
continue
try:
rec = json.loads(s)
except ValueError as exc:
errors.append(f"Line {line_no}: malformed JSON ({exc})")
continue
seq_expected += 1
if rec.get("seq") != seq_expected:
errors.append(f"Line {line_no}: expected seq {seq_expected}, got {rec.get('seq')}")
if rec.get("prev_sha384") != expected_prev:
errors.append(f"Line {line_no}: prev_sha384 chain mismatch")
claimed_hash = rec.get("entry_sha384")
body = {k: v for k, v in rec.items() if k != "entry_sha384"}
recomputed = compute_ledger_entry_hash(body)
if claimed_hash != recomputed:
errors.append(f"Line {line_no}: entry_sha384 tamper detected")
expected_prev = str(claimed_hash or recomputed)
if task_id is not None and rec.get("task_id") != task_id:
errors.append(f"Line {line_no}: expected task_id={task_id!r}, got {rec.get('task_id')!r}")
disc_used = max(disc_used, int(rec.get("discovery_used", 0)))
sim_used = max(sim_used, int(rec.get("sim_used", 0)))
if rec.get("disabled_tool"):
disabled_attempts += 1
if rec.get("budget_rejected") and not rec.get("disabled_tool"):
budget_rejected += 1
records.append(rec)
if max_discovery_calls is not None and disc_used > max_discovery_calls:
errors.append(f"Discovery budget exceeded: {disc_used} > {max_discovery_calls}")
if max_sim_calls is not None and sim_used > max_sim_calls:
errors.append(f"Simulation budget exceeded: {sim_used} > {max_sim_calls}")
return {
"ledger_verified": len(errors) == 0,
"errors": errors,
"records": records,
"entry_count": len(records),
"discovery_calls_used": disc_used,
"sim_calls_used": sim_used,
"disabled_tool_attempts": disabled_attempts,
"budget_rejected_calls": budget_rejected,
}
def _verify_single_recomputed_call(
*,
client: McpStdioClient,
submitted_seal: str,
tool: str,
model_id: str,
args: dict[str, Any],
expected_answer_sha384: str,
) -> tuple[bool, VerifiedCall | None, str]:
"""Deterministically re-run `(tool, args)` on `mcp_stdio` and verify SHA-384 proofs."""
parsed, raw_text, is_err = client.call_json(tool, args)
if is_err or not isinstance(parsed, dict):
return False, None, f"Engine recomputation errored for seal {submitted_seal[:16]}... ({tool} on {model_id}): {raw_text[:200]}"
actual_ans_hash = hashlib.sha384(raw_text.encode("utf-8")).hexdigest()
if expected_answer_sha384 and actual_ans_hash != expected_answer_sha384:
return (
False,
None,
f"Determinism mismatch on recomputation for seal {submitted_seal[:16]}... ({model_id}): ledger SHA-384 {expected_answer_sha384[:16]} != fresh {actual_ans_hash[:16]}",
)
ok_rec, rec_msg = verify_receipt_offline_bytes(raw_text)
if not ok_rec:
return False, None, f"Offline receipt check failed for {model_id} seal {submitted_seal[:16]}...: {rec_msg}"
emitted_seals = extract_seals_from_answer(parsed)
if submitted_seal not in emitted_seals:
return (
False,
None,
f"Seal {submitted_seal[:16]}... not emitted by fresh {tool} recomputation on {model_id}.",
)
# Verify engine cryptographic integrity (`verify_tape` / `verify_solution`)
if tool == "run_trajectory" and parsed.get("run_seal"):
vt_ans, vt_raw, vt_err = client.call_json(
"verify_tape", {"request": args, "run_seal": parsed["run_seal"]}
)
if vt_err or not isinstance(vt_ans, dict) or not vt_ans.get("holds"):
return (
False,
None,
f"Engine verify_tape rejected {model_id} seal {submitted_seal[:16]}...: {vt_raw[:200]}",
)
elif tool == "solve" and parsed.get("solution_seal"):
vs_ans, vs_raw, vs_err = client.call_json(
"verify_solution", {"request": args, "solution_seal": parsed["solution_seal"]}
)
if vs_err or not isinstance(vs_ans, dict) or not vs_ans.get("holds"):
return (
False,
None,
f"Engine verify_solution rejected {model_id} seal {submitted_seal[:16]}...: {vs_raw[:200]}",
)
primary_seal = str(
parsed.get("run_seal")
or parsed.get("solution_seal")
or parsed.get("receipt_sha384")
or submitted_seal
)
vc = VerifiedCall(
submitted_seal=submitted_seal,
model_id=model_id,
tool=tool,
args=args,
answer=parsed,
raw_text=raw_text,
answer_sha384=actual_ans_hash,
receipt_sha384=str(parsed.get("receipt_sha384") or rec_msg),
primary_seal=primary_seal,
)
return True, vc, "ok"
def resolve_and_verify_seals(
*,
seal_tokens: list[str],
ledger_records: list[dict[str, Any]],
client: McpStdioClient,
) -> tuple[bool, list[VerifiedCall], dict[str, list[VerifiedCall]], str]:
"""Resolve list-or-dict seals against `call_ledger.jsonl` and recompute via `mcp_stdio`."""
ok_hex, bad_tok = all_tokens_well_formed_hex(seal_tokens)
if not ok_hex:
return (
False,
[],
{},
f"Invalid SHA-384 seal string {bad_tok!r}: expected 96 lowercase hexadecimal characters.",
)
# Build lookup index from every verified non-error ledger entry & embedded plugin step records
seal_index: dict[str, dict[str, Any]] = {}
for rec in ledger_records:
if rec.get("is_error") or rec.get("budget_rejected"):
continue
cs = rec.get("call_spec")
if isinstance(cs, dict) and cs.get("tool") in ("run_trajectory", "compute_step", "solve", "run_dataset"):
for sh in rec.get("extracted_seals") or []:
seal_index[sh] = {
"tool": cs["tool"],
"model_id": cs.get("model_id") or extract_model_id_from_call(cs["tool"], cs.get("args") or {}),
"args": cs.get("args") or {},
"answer_sha384": str(rec.get("answer_sha384") or ""),
}
for step_rec in rec.get("step_call_records") or []:
if not isinstance(step_rec, dict):
continue
scs = step_rec.get("call_spec") or {}
tname = scs.get("tool") or step_rec.get("tool")
targs = scs.get("args") or step_rec.get("args") or {}
mid = scs.get("model_id") or step_rec.get("model_id") or extract_model_id_from_call(str(tname), targs)
ans_h = str(step_rec.get("answer_sha384") or "")
for sh in step_rec.get("extracted_seals") or []:
seal_index[sh] = {
"tool": tname,
"model_id": mid,
"args": targs,
"answer_sha384": ans_h,
}
resolved: list[VerifiedCall] = []
by_model: dict[str, list[VerifiedCall]] = {}
recompute_cache: dict[str, VerifiedCall] = {}
for tok in seal_tokens:
entry = seal_index.get(tok)
if entry is None:
return (
False,
[],
{},
f"Seal {tok[:20]}... not found in session call_ledger.jsonl (orphaned, stale, or forged seal).",
)
ans_key = f"{entry['tool']}::{entry['answer_sha384']}::{json.dumps(entry['args'], sort_keys=True)}"
cached = recompute_cache.get(ans_key)
if cached is not None:
# Verify tok matches an emitted seal on the already-verified call
if tok not in extract_seals_from_answer(cached.answer):
return (
False,
[],
{},
f"Seal {tok[:20]}... does not match recomputed engine output for {entry['model_id']}.",
)
resolved.append(cached)
continue
ok, vc, msg = _verify_single_recomputed_call(
client=client,
submitted_seal=tok,
tool=entry["tool"],
model_id=entry["model_id"],
args=entry["args"],
expected_answer_sha384=entry["answer_sha384"],
)
if not ok or vc is None:
return False, [], {}, msg
recompute_cache[ans_key] = vc
resolved.append(vc)
by_model.setdefault(vc.model_id, []).append(vc)
return True, resolved, by_model, "All submitted seals verified against call_ledger.jsonl and fresh mcp_stdio recomputation."
def collect_plugin_episodes(ledger_records: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Extract chronological `CLC`/`FLT` plugin step & finalize records from `call_ledger.jsonl`."""
episodes: list[dict[str, Any]] = []
cur: dict[str, Any] | None = None
for rec in ledger_records:
if rec.get("is_error") or rec.get("budget_rejected"):
continue
ep_ev = rec.get("plugin_event")
if not isinstance(ep_ev, dict):
continue
kind = ep_ev.get("kind")
if kind == "reset_episode":
cur = {"reset": ep_ev, "steps": [], "finalized": False}
episodes.append(cur)
elif kind == "step_env":
if cur is None:
cur = {"reset": None, "steps": [], "finalized": False}
episodes.append(cur)
cur["steps"].append(ep_ev)
elif kind == "finalize_episode" and cur is not None:
cur["finalized"] = True
cur["finalize"] = ep_ev
return episodes
def collect_plugin_probes(ledger_records: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Extract valid `FLT` diagnostic `inject_probe` events from `call_ledger.jsonl`."""
probes: list[dict[str, Any]] = []
for rec in ledger_records:
if rec.get("is_error") or rec.get("budget_rejected"):
continue
ep_ev = rec.get("plugin_event")
if isinstance(ep_ev, dict) and ep_ev.get("kind") == "inject_probe":
probes.append(ep_ev)
return probes
def check_bridge_value(
expected: float,
observed: Any,
unit: str,
bridge_name: str,
*,
mode: str = "exact",
rel_tol: float = 1e-6,
abs_tol: float = 1e-12,
) -> tuple[bool, dict[str, Any]]:
"""Conservation & continuity bridge check with JSON float tolerance & optional conservative margin.
- `mode == "exact"`: `|observed - expected| <= max(abs_tol, rel_tol * |expected|)`
- `mode == "ge"`: `observed >= expected - tol` (conservative upward safety load margin)
- `mode == "le"`: `observed <= expected + tol` (conservative colder/harsher boundary margin)
"""
try:
exp = float(expected)
obs = float(observed)
except (TypeError, ValueError):
return False, {"bridge": bridge_name, "unit": unit, "holds": False, "error": "non-numeric value"}
if not (math.isfinite(exp) and math.isfinite(obs)):
return False, {"bridge": bridge_name, "unit": unit, "holds": False, "error": "non-finite value"}
tol = max(abs_tol, rel_tol * abs(exp))
diff = abs(obs - exp)
if mode == "exact":
holds = diff <= tol
elif mode == "ge":
holds = obs >= (exp - tol)
elif mode == "le":
holds = obs <= (exp + tol)
else:
raise ValueError(f"Unknown bridge mode {mode!r}")
return holds, {
"bridge": bridge_name,
"unit": unit,
"mode": mode,
"expected_upstream": exp,
"observed_downstream": obs,
"abs_diff": diff,
"tolerance": tol,
"holds": holds,
}
def grade_task(
task_id: str,
submission: dict[str, Any] | None,
*,
pack_name: str = "flagship_monolith_30",
pack_dir: str | None = None,
ledger_path: str | None = None,
vault_dir: str | None = None,
engine_bin: str | None = None,
seal_bin: str | None = None,
) -> dict[str, Any]:
"""Grade one task submission end-to-end with cryptographic recomputation & autopsy."""
t0 = time.monotonic()
bundle = get_task_bundle(task_id=task_id, pack_name=pack_name, pack_dir=pack_dir)
tspec = bundle["task_spec"]
tdir = bundle["task_dir"]
pdir = bundle["pack_dir"]
budget = tspec.get("budget") or {}
max_disc = int(budget.get("max_discovery_calls", 120))
max_sim = int(budget.get("max_sim_calls", 40))
if submission is None or not isinstance(submission, dict):
return make_grade_report(
task_id=task_id,
binary_reward=0,
shaped_score=0.0,
seals_verified=False,
failure_reason="schema_error",
autopsy="Missing or non-object submission.json.",
stage_breakdown={"schema": {"holds": False}},
ledger_audit=None,
verification_ms=(time.monotonic() - t0) * 1000.0,
)
ledger_audit: dict[str, Any] | None = None
ledger_records: list[dict[str, Any]] = []
if ledger_path is not None:
ledger_audit = verify_call_ledger(
ledger_path,
task_id=task_id,
max_discovery_calls=max_disc,
max_sim_calls=max_sim,
)
ledger_records = list(ledger_audit.get("records") or [])
if not ledger_audit["ledger_verified"]:
return make_grade_report(
task_id=task_id,
binary_reward=0,
shaped_score=0.0,
seals_verified=False,
failure_reason="seal_invalid",
autopsy=f"Ledger SHA-384 chain verification failed: {'; '.join(ledger_audit['errors'])}",
stage_breakdown={"ledger": {"holds": False, "errors": ledger_audit["errors"]}},
ledger_audit={k: v for k, v in ledger_audit.items() if k != "records"},
verification_ms=(time.monotonic() - t0) * 1000.0,
)
eval_mod = load_task_evaluator(task_id=task_id, task_dir=tdir)
vault = load_task_vault(task_id=task_id, vault_dir=vault_dir, pack_dir=pdir)
# First check schema + extract candidate seal tokens via task schema or fallback helper
if hasattr(eval_mod, "validate_schema"):
schema_ok, schema_errs, seal_tokens = eval_mod.validate_schema(submission)
else:
ok_s, seal_tokens, err_s = extract_seal_tokens(submission.get("seals"))
schema_ok = ok_s and submission.get("task_id") == task_id
schema_errs = [err_s] if err_s else []
if submission.get("task_id") != task_id:
schema_errs.append(f"Expected task_id={task_id!r}, got {submission.get('task_id')!r}")
compact_ledger = {k: v for k, v in ledger_audit.items() if k != "records"} if ledger_audit else None
if not schema_ok:
is_budget_empty_seals = False
if (
isinstance(submission, dict)
and submission.get("seals") in ([], {})
and any(r.get("budget_rejected") and not r.get("disabled_tool") for r in ledger_records)
):
probe_sub = dict(submission)
probe_sub["seals"] = ["0" * 96]
if hasattr(eval_mod, "validate_schema"):
probe_ok, _, _ = eval_mod.validate_schema(probe_sub)
else:
probe_ok = submission.get("task_id") == task_id
is_budget_empty_seals = bool(probe_ok)
if is_budget_empty_seals:
return make_grade_report(
task_id=task_id,
binary_reward=0,
shaped_score=0.0,
seals_verified=False,
failure_reason="budget_exhausted",
autopsy=(
"BUDGET_EXHAUSTED [SHA-384 autopsy]: Task wall timeout or simulation call budget "
"exhausted before cryptographic seals were minted."
),
stage_breakdown={"schema": {"holds": False, "errors": schema_errs}, "budget_exhausted": True},
ledger_audit=compact_ledger,
verification_ms=(time.monotonic() - t0) * 1000.0,
)
return make_grade_report(
task_id=task_id,
binary_reward=0,
shaped_score=0.0,
seals_verified=False,
failure_reason="schema_error",
autopsy="Schema validation failed: " + " | ".join(schema_errs),
stage_breakdown={"schema": {"holds": False, "errors": schema_errs}},
ledger_audit=compact_ledger,
verification_ms=(time.monotonic() - t0) * 1000.0,
)
if engine_bin is None:
engine_bin = resolve_pack_engine(pack_name=pack_name, pack_dir=pack_dir)
with McpStdioClient(engine_bin=engine_bin) as client:
seals_ok, resolved, by_model, seal_msg = resolve_and_verify_seals(
seal_tokens=seal_tokens,
ledger_records=ledger_records,
client=client,
)
if not seals_ok:
return make_grade_report(
task_id=task_id,
binary_reward=0,
shaped_score=0.0,
seals_verified=False,
failure_reason="seal_invalid",
autopsy=f"Cryptographic seal verification failed: {seal_msg}",
stage_breakdown={"seals": {"holds": False, "message": seal_msg}},
ledger_audit=compact_ledger,
verification_ms=(time.monotonic() - t0) * 1000.0,
)
ctx = TaskEvaluatorContext(
task_id=task_id,
task_dir=tdir,
task_spec=tspec,
pack_dir=pdir,
client=client,
seal_bin=seal_bin,
vault=vault,
ledger_records=ledger_records,
ledger_audit=compact_ledger,
resolved_seals=resolved,
verified_by_model=by_model,
plugin_episodes=collect_plugin_episodes(ledger_records),
)
res = eval_mod.evaluate(submission, ctx)
# Upgrade failure_reason from physics_violation to budget_exhausted if required proofs
# were missing strictly after hitting a daemon budget wall.
failure_reason = str(res["failure_reason"])
if (
int(res["binary_reward"]) == 0
and failure_reason == "physics_violation"
and compact_ledger is not None
and int(compact_ledger.get("budget_rejected_calls", 0)) > 0
and not bool(res.get("all_required_models_present", True))
):
failure_reason = "budget_exhausted"
return make_grade_report(
task_id=task_id,
binary_reward=int(res["binary_reward"]),
shaped_score=float(res["shaped_score"]),
seals_verified=True,
failure_reason=failure_reason,
autopsy=str(res["autopsy"]),
stage_breakdown=dict(res["stage_breakdown"]),
ledger_audit=compact_ledger,
verification_ms=(time.monotonic() - t0) * 1000.0,
)
|