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,593 @@
|
|
|
1
|
+
"""Tool-free, per-case native Codex judge for a sealed LongMemEval-S run.
|
|
2
|
+
|
|
3
|
+
Preparation is local. Run is one shot and sequential; each case gets a fresh
|
|
4
|
+
Codex thread and empty working directory. This is an independent agent score,
|
|
5
|
+
not the official OpenAI API score.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import asyncio
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
import platform
|
|
18
|
+
import sys
|
|
19
|
+
import time
|
|
20
|
+
import uuid
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from benchmarks import longmemeval_actor as actor
|
|
24
|
+
from benchmarks import longmemeval_full as full
|
|
25
|
+
from benchmarks.longmemeval_judge import OFFICIAL_EVALUATOR_SHA256, load_rubric
|
|
26
|
+
|
|
27
|
+
MODEL = "gpt-6.1-sol"
|
|
28
|
+
REASONING = "low"
|
|
29
|
+
CASE_TIMEOUT_SECONDS = 120
|
|
30
|
+
MAX_WALL_SECONDS = 2 * 60 * 60
|
|
31
|
+
POLL_SECONDS = 30
|
|
32
|
+
SCHEMA = "longmemeval-s.agent-judge-prepared.v1"
|
|
33
|
+
DISABLED_CODE_MODE_NOTICE = (
|
|
34
|
+
"Code Mode is unavailable because code-mode host is disabled. Code mode will fail closed; "
|
|
35
|
+
"enable `features.code_mode_host` and install `codex-code-mode-host`."
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _sha_bytes(data: bytes) -> str:
|
|
40
|
+
return hashlib.sha256(data).hexdigest()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _sha(path: Path) -> str:
|
|
44
|
+
digest = hashlib.sha256()
|
|
45
|
+
with path.open("rb") as stream:
|
|
46
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
47
|
+
digest.update(chunk)
|
|
48
|
+
return digest.hexdigest()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _json_bytes(value: Any) -> bytes:
|
|
52
|
+
return (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _write_new(path: Path, data: bytes) -> None:
|
|
56
|
+
with path.open("xb") as stream:
|
|
57
|
+
stream.write(data)
|
|
58
|
+
stream.flush()
|
|
59
|
+
os.fsync(stream.fileno())
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _append_jsonl(path: Path, value: Any) -> None:
|
|
63
|
+
with path.open("ab") as stream:
|
|
64
|
+
stream.write(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n")
|
|
65
|
+
stream.flush()
|
|
66
|
+
os.fsync(stream.fileno())
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _utc_now() -> str:
|
|
70
|
+
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _sealed_full(full_root: Path) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, Any]]:
|
|
74
|
+
"""Fail closed on every upstream gate before opening coordinator-only gold."""
|
|
75
|
+
manifest = full.validate_manifest(full_root)
|
|
76
|
+
work = full_root / "execution"
|
|
77
|
+
result = json.loads((work / "result.json").read_text(encoding="utf-8"))
|
|
78
|
+
if (result.get("status") != "ANSWERS_SEALED" or result.get("selected") != full.FULL_CASES
|
|
79
|
+
or result.get("completed_hypotheses") != full.FULL_CASES):
|
|
80
|
+
raise ValueError("full run is not a complete sealed 500-hypothesis result")
|
|
81
|
+
if manifest.get("judge", {}).get("official_evaluator_sha256") != OFFICIAL_EVALUATOR_SHA256:
|
|
82
|
+
raise ValueError("full-run official judge rubric identity differs from the pinned source")
|
|
83
|
+
cases = manifest.get("cases")
|
|
84
|
+
qids = [row.get("question_id") for row in cases] if isinstance(cases, list) else []
|
|
85
|
+
if (len(qids) != full.FULL_CASES or any(not isinstance(q, str) or not q for q in qids)
|
|
86
|
+
or len(set(qids)) != full.FULL_CASES):
|
|
87
|
+
raise ValueError("full manifest does not contain exactly 500 unique question IDs")
|
|
88
|
+
hyp_path = work / "hypotheses.jsonl"
|
|
89
|
+
hyp_raw = hyp_path.read_bytes()
|
|
90
|
+
hyp_sha = _sha_bytes(hyp_raw)
|
|
91
|
+
if (hyp_sha != (work / "hypotheses.sha256").read_text(encoding="ascii").strip()
|
|
92
|
+
or hyp_sha != result.get("hypotheses_sha256")):
|
|
93
|
+
raise ValueError("full hypothesis seal differs from result or seal file")
|
|
94
|
+
hypotheses = [json.loads(line) for line in hyp_raw.decode("utf-8").splitlines() if line]
|
|
95
|
+
hyp_ids = [row.get("question_id") for row in hypotheses]
|
|
96
|
+
if (len(hypotheses) != full.FULL_CASES or len(set(hyp_ids)) != full.FULL_CASES
|
|
97
|
+
or set(hyp_ids) != set(qids)
|
|
98
|
+
or any(set(row) != {"question_id", "hypothesis"}
|
|
99
|
+
or not isinstance(row.get("hypothesis"), str) or not row["hypothesis"]
|
|
100
|
+
for row in hypotheses)):
|
|
101
|
+
raise ValueError("sealed hypotheses are missing, extra, duplicated, or malformed")
|
|
102
|
+
|
|
103
|
+
# Retained actor evidence is part of the prerequisite, not an optional audit.
|
|
104
|
+
for index, row in enumerate(cases, 1):
|
|
105
|
+
case_name = row.get("case_name")
|
|
106
|
+
if case_name != f"case-{index:04d}":
|
|
107
|
+
raise ValueError("full manifest case order or case names changed")
|
|
108
|
+
case_receipt = json.loads((work / f"{case_name}.receipt.json").read_text(encoding="utf-8"))
|
|
109
|
+
if case_receipt.get("question_id") != row["question_id"]:
|
|
110
|
+
raise ValueError("full case receipt question ID mismatch")
|
|
111
|
+
for role in ("writer", "reader"):
|
|
112
|
+
receipt_path = work / f"{case_name}.{role}.receipt.json"
|
|
113
|
+
receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
|
|
114
|
+
audit = receipt.get("native_trace_audit")
|
|
115
|
+
if (receipt.get("status") != "PASS" or receipt.get("role") != role
|
|
116
|
+
or receipt.get("model") != manifest.get("model")
|
|
117
|
+
or not isinstance(audit, dict) or audit.get("status") != "PASS"):
|
|
118
|
+
raise ValueError(f"{case_name} {role} actor receipt or native audit is not PASS")
|
|
119
|
+
summary = case_receipt.get(role, {})
|
|
120
|
+
if (summary.get("status") != "PASS"
|
|
121
|
+
or summary.get("native_trace_audit", {}).get("status") != "PASS"
|
|
122
|
+
or summary.get("native_trace_audit", {}).get("thread_id") != audit.get("thread_id")):
|
|
123
|
+
raise ValueError(f"{case_name} composite receipt does not link the {role} native audit")
|
|
124
|
+
full._usage(receipt, Path(receipt["events_path"]), manifest["model"], role)
|
|
125
|
+
for key in ("source_path", "tool_trace_path"):
|
|
126
|
+
path = Path(audit.get(key, ""))
|
|
127
|
+
if not path.is_file():
|
|
128
|
+
raise ValueError(f"{case_name} {role} retained native audit file is missing")
|
|
129
|
+
final_path = Path(receipt.get("final_path", ""))
|
|
130
|
+
if not final_path.is_file():
|
|
131
|
+
raise ValueError(f"{case_name} {role} final receipt file is missing")
|
|
132
|
+
final_raw = final_path.read_bytes()
|
|
133
|
+
final_message = receipt.get("final_message")
|
|
134
|
+
if not isinstance(final_message, str) or final_raw.decode("utf-8") != final_message:
|
|
135
|
+
raise ValueError(f"{case_name} {role} final receipt does not match its actor receipt")
|
|
136
|
+
if role == "reader":
|
|
137
|
+
by_id = next(item for item in hypotheses if item["question_id"] == row["question_id"])
|
|
138
|
+
if final_message != by_id["hypothesis"]:
|
|
139
|
+
raise ValueError(f"{case_name} reader receipt does not match sealed hypothesis")
|
|
140
|
+
|
|
141
|
+
# This is the first access to reference records, after all answer gates pass.
|
|
142
|
+
refs = json.loads((full_root / "references.json").read_text(encoding="utf-8"))
|
|
143
|
+
by_id = {row.get("question_id"): row for row in refs if isinstance(row, dict)}
|
|
144
|
+
if len(refs) != full.FULL_CASES or len(by_id) != full.FULL_CASES or set(by_id) != set(qids):
|
|
145
|
+
raise ValueError("sealed references do not exactly cover all 500 cases")
|
|
146
|
+
# Upstream answers include JSON numbers. Its rubric uses str.format on
|
|
147
|
+
# the original value; do not impose a text-only schema or rewrite gold.
|
|
148
|
+
if any("answer" not in by_id[q]
|
|
149
|
+
or any(not isinstance(by_id[q].get(field), str)
|
|
150
|
+
for field in ("question_type", "question"))
|
|
151
|
+
for q in qids):
|
|
152
|
+
raise ValueError("sealed reference fields are malformed")
|
|
153
|
+
return manifest, hypotheses, by_id
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def prepare(full_root: Path, evaluator: Path, output: Path) -> dict[str, Any]:
|
|
157
|
+
if output.exists() or not output.parent.is_dir():
|
|
158
|
+
raise FileExistsError("agent-judge output must be a new directory under an existing parent")
|
|
159
|
+
manifest, hypotheses, refs = _sealed_full(full_root)
|
|
160
|
+
rubric = load_rubric(evaluator)
|
|
161
|
+
codex = Path(manifest["executables"]["codex"]["path"]).resolve()
|
|
162
|
+
output.mkdir()
|
|
163
|
+
cases = []
|
|
164
|
+
for ordinal, hyp in enumerate(hypotheses, 1):
|
|
165
|
+
qid = hyp["question_id"]
|
|
166
|
+
ref = refs[qid]
|
|
167
|
+
prompt = rubric(ref["question_type"], ref["question"], ref["answer"], hyp["hypothesis"],
|
|
168
|
+
abstention="_abs" in qid)
|
|
169
|
+
raw = prompt.encode("utf-8")
|
|
170
|
+
name = f"case-{ordinal:04d}.rubric.txt"
|
|
171
|
+
_write_new(output / name, raw)
|
|
172
|
+
cases.append({"ordinal": ordinal, "question_id": qid, "prompt_file": name,
|
|
173
|
+
"prompt_sha256": _sha_bytes(raw),
|
|
174
|
+
"hypothesis_sha256": _sha_bytes(hyp["hypothesis"].encode("utf-8"))})
|
|
175
|
+
amendment = {
|
|
176
|
+
"schema": SCHEMA,
|
|
177
|
+
"authorization_basis": "User-authorized independent native agent scoring; separate amendment to sealed full-run evidence.",
|
|
178
|
+
"full_run_path": str(full_root.resolve()),
|
|
179
|
+
"full_manifest_sha256": _sha(full_root / "manifest.json"),
|
|
180
|
+
"full_result_sha256": _sha(full_root / "execution" / "result.json"),
|
|
181
|
+
"hypotheses_sha256": _sha(full_root / "execution" / "hypotheses.jsonl"),
|
|
182
|
+
"references_sha256": _sha(full_root / "references.json"),
|
|
183
|
+
"evaluator_path": str(evaluator.resolve()),
|
|
184
|
+
"official_evaluator_sha256": OFFICIAL_EVALUATOR_SHA256,
|
|
185
|
+
"adapter_sha256": _sha(Path(__file__)),
|
|
186
|
+
"codex_executable": str(codex),
|
|
187
|
+
"codex_executable_sha256": _sha(codex),
|
|
188
|
+
"runtime": {"python": platform.python_version(), "platform": platform.platform()},
|
|
189
|
+
"model": MODEL, "reasoning_effort": REASONING,
|
|
190
|
+
"case_deadline_seconds": CASE_TIMEOUT_SECONDS, "wall_deadline_seconds": MAX_WALL_SECONDS,
|
|
191
|
+
"concurrency": 1,
|
|
192
|
+
"input_contract": "One exact official rubric prompt as the sole stdin per fresh native Codex invocation.",
|
|
193
|
+
"cases": cases,
|
|
194
|
+
"scoring_label": "NONOFFICIAL_AGENT_JUDGE",
|
|
195
|
+
"official_score": None,
|
|
196
|
+
}
|
|
197
|
+
raw = _json_bytes(amendment)
|
|
198
|
+
_write_new(output / "manifest.json", raw)
|
|
199
|
+
_write_new(output / "manifest.sha256", (_sha_bytes(raw) + "\n").encode("ascii"))
|
|
200
|
+
return {"status": "PREPARED", "cases": full.FULL_CASES,
|
|
201
|
+
"manifest_sha256": _sha_bytes(raw)}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _validate_prepared(output: Path, *, for_run: bool = False) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
|
205
|
+
raw = (output / "manifest.json").read_bytes()
|
|
206
|
+
if _sha_bytes(raw) != (output / "manifest.sha256").read_text(encoding="ascii").strip():
|
|
207
|
+
raise ValueError("agent-judge manifest seal mismatch")
|
|
208
|
+
amendment = json.loads(raw)
|
|
209
|
+
if amendment.get("schema") != SCHEMA or amendment.get("model") != MODEL:
|
|
210
|
+
raise ValueError("unexpected agent-judge contract")
|
|
211
|
+
if amendment.get("adapter_sha256") != _sha(Path(__file__)):
|
|
212
|
+
raise ValueError("agent-judge source changed after preparation")
|
|
213
|
+
if amendment.get("official_evaluator_sha256") != OFFICIAL_EVALUATOR_SHA256:
|
|
214
|
+
raise ValueError("pinned official evaluator identity changed")
|
|
215
|
+
codex = Path(amendment["codex_executable"])
|
|
216
|
+
if not codex.is_file() or _sha(codex) != amendment["codex_executable_sha256"]:
|
|
217
|
+
raise ValueError("validated Codex executable changed after preparation")
|
|
218
|
+
root = Path(amendment["full_run_path"])
|
|
219
|
+
_manifest, hypotheses, _refs = _sealed_full(root)
|
|
220
|
+
if (_sha(root / "manifest.json") != amendment["full_manifest_sha256"]
|
|
221
|
+
or _sha(root / "execution" / "result.json") != amendment["full_result_sha256"]
|
|
222
|
+
or _sha(root / "execution" / "hypotheses.jsonl") != amendment["hypotheses_sha256"]):
|
|
223
|
+
raise ValueError("sealed full-run inputs changed after preparation")
|
|
224
|
+
cases = amendment.get("cases")
|
|
225
|
+
if not isinstance(cases, list) or len(cases) != full.FULL_CASES:
|
|
226
|
+
raise ValueError("prepared run does not contain exactly 500 cases")
|
|
227
|
+
for index, (item, hyp) in enumerate(zip(cases, hypotheses), 1):
|
|
228
|
+
if (item.get("ordinal") != index or item.get("question_id") != hyp["question_id"]
|
|
229
|
+
or item.get("hypothesis_sha256") != _sha_bytes(hyp["hypothesis"].encode("utf-8"))):
|
|
230
|
+
raise ValueError("prepared case-to-hypothesis mapping changed")
|
|
231
|
+
prompt_path = output / item["prompt_file"]
|
|
232
|
+
if _sha(prompt_path) != item["prompt_sha256"]:
|
|
233
|
+
raise ValueError("prepared exact rubric prompt changed")
|
|
234
|
+
if for_run and (output / "execution").exists():
|
|
235
|
+
raise FileExistsError("agent-judge execution already started; no reruns or resume")
|
|
236
|
+
return amendment, cases
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _codex_command(codex: Path, cwd: Path, final_path: Path) -> list[str]:
|
|
240
|
+
if cwd.exists() and any(cwd.iterdir()):
|
|
241
|
+
raise ValueError("per-case Codex cwd must be empty")
|
|
242
|
+
if not cwd.is_dir():
|
|
243
|
+
raise ValueError("per-case Codex cwd must be created before invocation")
|
|
244
|
+
command = [str(codex), "exec", "--ignore-user-config", "--ignore-rules",
|
|
245
|
+
"--strict-config", "--skip-git-repo-check", "--json",
|
|
246
|
+
"--model", MODEL, "--sandbox", "read-only", "--cd", str(cwd),
|
|
247
|
+
"--output-last-message", str(final_path)]
|
|
248
|
+
for feature in actor.DISABLED_FEATURES:
|
|
249
|
+
command += ["--disable", feature]
|
|
250
|
+
command += ["--disable", "code_mode_host",
|
|
251
|
+
"-c", "project_doc_max_bytes=0", "-c", 'web_search="disabled"',
|
|
252
|
+
"-c", "features.code_mode.enabled=false", "-c", "mcp_servers={}",
|
|
253
|
+
"-c", 'model_reasoning_effort="low"', "-"]
|
|
254
|
+
return command
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _parse_event_lines(raw: bytes) -> list[dict[str, Any]]:
|
|
258
|
+
rows = []
|
|
259
|
+
for line in raw.splitlines():
|
|
260
|
+
if line.strip():
|
|
261
|
+
value = json.loads(line.decode("utf-8"))
|
|
262
|
+
if not isinstance(value, dict):
|
|
263
|
+
raise ValueError("native Codex emitted a non-object event")
|
|
264
|
+
rows.append(value)
|
|
265
|
+
return rows
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _verdict(final: str) -> str:
|
|
269
|
+
value = final.strip().lower()
|
|
270
|
+
if value not in {"yes", "no"}:
|
|
271
|
+
raise ValueError("native Codex judge final output is not exactly yes or no")
|
|
272
|
+
return value
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _audit_native(events: list[dict[str, Any]], journal_root: Path, audit_path: Path,
|
|
276
|
+
deadline: float, prompt: str) -> dict[str, Any]:
|
|
277
|
+
thread_ids = [event.get("thread_id") for event in events if event.get("type") == "thread.started"]
|
|
278
|
+
if len(thread_ids) != 1:
|
|
279
|
+
raise ValueError("expected one native Codex thread identity")
|
|
280
|
+
thread_id = str(uuid.UUID(thread_ids[0]))
|
|
281
|
+
while True:
|
|
282
|
+
matches = list(journal_root.rglob(f"*-{thread_id}.jsonl")) if journal_root.is_dir() else []
|
|
283
|
+
if len(matches) > 1:
|
|
284
|
+
raise ValueError("native Codex journal identity is ambiguous")
|
|
285
|
+
journal_path = matches[0] if matches else None
|
|
286
|
+
journal_raw = journal_path.read_bytes() if journal_path and journal_path.is_file() else b""
|
|
287
|
+
try:
|
|
288
|
+
journal = _parse_event_lines(journal_raw) if journal_raw.endswith(b"\n") else []
|
|
289
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
290
|
+
journal = []
|
|
291
|
+
started_count = sum(row.get("type") == "event_msg"
|
|
292
|
+
and row.get("payload", {}).get("type") == "task_started" for row in journal)
|
|
293
|
+
complete_count = sum(row.get("type") == "event_msg"
|
|
294
|
+
and row.get("payload", {}).get("type") == "task_complete" for row in journal)
|
|
295
|
+
if started_count == complete_count == 1:
|
|
296
|
+
break
|
|
297
|
+
if time.monotonic() >= deadline:
|
|
298
|
+
raise TimeoutError("complete native Codex journal unavailable before original deadline")
|
|
299
|
+
time.sleep(min(0.05, max(0, deadline - time.monotonic())))
|
|
300
|
+
calls = [row for row in journal if row.get("type") == "response_item"
|
|
301
|
+
and row.get("payload", {}).get("type") in {
|
|
302
|
+
"function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output"}]
|
|
303
|
+
if calls:
|
|
304
|
+
raise ValueError("native Codex journal contains a tool call")
|
|
305
|
+
user_messages = [row.get("payload", {}) for row in journal
|
|
306
|
+
if row.get("type") == "response_item"
|
|
307
|
+
and row.get("payload", {}).get("type") == "message"
|
|
308
|
+
and row.get("payload", {}).get("role") == "user"]
|
|
309
|
+
if not user_messages:
|
|
310
|
+
raise ValueError("native Codex journal has no user prompt")
|
|
311
|
+
content = user_messages[-1].get("content")
|
|
312
|
+
actual_prompt = "".join(part.get("text", "") for part in content
|
|
313
|
+
if isinstance(part, dict) and part.get("type") == "input_text") \
|
|
314
|
+
if isinstance(content, list) else ""
|
|
315
|
+
if actual_prompt != prompt:
|
|
316
|
+
raise ValueError("last native user message differs from the exact rubric stdin")
|
|
317
|
+
contexts = []
|
|
318
|
+
for row in journal:
|
|
319
|
+
payload = row.get("payload", {})
|
|
320
|
+
if row.get("type") == "turn_context":
|
|
321
|
+
contexts.append(payload if isinstance(payload, dict) else {})
|
|
322
|
+
elif row.get("type") == "event_msg" and payload.get("type") == "turn_context":
|
|
323
|
+
contexts.append(payload)
|
|
324
|
+
models = [row.get("model") for row in contexts]
|
|
325
|
+
if len(models) != 1 or models[0] != MODEL:
|
|
326
|
+
raise ValueError("native journal does not confirm exactly one requested model turn_context")
|
|
327
|
+
for row in journal:
|
|
328
|
+
if row.get("type") == "session_meta":
|
|
329
|
+
payload = row.get("payload", {})
|
|
330
|
+
if any(payload.get(key) for key in ("resumed_from", "parent_thread_id", "forked_from")):
|
|
331
|
+
raise ValueError("native Codex journal indicates a resumed or forked session")
|
|
332
|
+
_write_new(audit_path, journal_raw)
|
|
333
|
+
return {"status": "PASS", "thread_id": thread_id, "journal_source": str(journal_path),
|
|
334
|
+
"journal_copy": str(audit_path), "journal_sha256": _sha_bytes(journal_raw),
|
|
335
|
+
"observed_turn_context_models": models, "tool_calls": 0}
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
async def _invoke(codex: Path, prompt: bytes, cwd: Path, journal_root: Path,
|
|
339
|
+
receipts: Path, prefix: str, timeout: int = CASE_TIMEOUT_SECONDS) -> dict[str, Any]:
|
|
340
|
+
cwd = cwd.resolve()
|
|
341
|
+
journal_root = journal_root.resolve()
|
|
342
|
+
receipts = receipts.resolve()
|
|
343
|
+
cwd.mkdir()
|
|
344
|
+
events_path = receipts / f"{prefix}.stdout.jsonl"
|
|
345
|
+
stderr_path = receipts / f"{prefix}.stderr.log"
|
|
346
|
+
final_path = receipts / f"{prefix}.final.txt"
|
|
347
|
+
audit_path = receipts / f"{prefix}.native-journal.jsonl"
|
|
348
|
+
started = time.monotonic()
|
|
349
|
+
command = _codex_command(codex, cwd, final_path)
|
|
350
|
+
proc = await asyncio.create_subprocess_exec(
|
|
351
|
+
*command, cwd=str(cwd), stdin=asyncio.subprocess.PIPE,
|
|
352
|
+
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
|
|
353
|
+
**({"start_new_session": True} if os.name != "nt" else {}))
|
|
354
|
+
stdout = bytearray()
|
|
355
|
+
stderr = bytearray()
|
|
356
|
+
|
|
357
|
+
async def drain(reader: asyncio.StreamReader, store: bytearray, *, mirror: bool = False) -> None:
|
|
358
|
+
while chunk := await reader.readline():
|
|
359
|
+
store.extend(chunk)
|
|
360
|
+
if mirror:
|
|
361
|
+
sys.stdout.buffer.write(chunk)
|
|
362
|
+
sys.stdout.buffer.flush()
|
|
363
|
+
|
|
364
|
+
async def communicate() -> None:
|
|
365
|
+
assert proc.stdin is not None and proc.stdout is not None and proc.stderr is not None
|
|
366
|
+
proc.stdin.write(prompt)
|
|
367
|
+
await proc.stdin.drain()
|
|
368
|
+
proc.stdin.close()
|
|
369
|
+
await asyncio.gather(drain(proc.stdout, stdout, mirror=True), drain(proc.stderr, stderr))
|
|
370
|
+
await proc.wait()
|
|
371
|
+
|
|
372
|
+
task = asyncio.create_task(communicate())
|
|
373
|
+
try:
|
|
374
|
+
await asyncio.wait_for(asyncio.shield(task), timeout=timeout)
|
|
375
|
+
except asyncio.TimeoutError:
|
|
376
|
+
await actor._terminate_process_tree(proc)
|
|
377
|
+
try:
|
|
378
|
+
await asyncio.wait_for(asyncio.shield(task), timeout=5)
|
|
379
|
+
except asyncio.TimeoutError:
|
|
380
|
+
task.cancel()
|
|
381
|
+
events_path.write_bytes(stdout)
|
|
382
|
+
stderr_path.write_bytes(stderr)
|
|
383
|
+
raise TimeoutError(f"native Codex judge exceeded original {timeout}s deadline") from None
|
|
384
|
+
except Exception:
|
|
385
|
+
await actor._terminate_process_tree(proc)
|
|
386
|
+
events_path.write_bytes(stdout)
|
|
387
|
+
stderr_path.write_bytes(stderr)
|
|
388
|
+
raise
|
|
389
|
+
events_path.write_bytes(stdout)
|
|
390
|
+
stderr_path.write_bytes(stderr)
|
|
391
|
+
if proc.returncode != 0:
|
|
392
|
+
raise RuntimeError(f"native Codex judge exited with code {proc.returncode}; receipts retained")
|
|
393
|
+
events = _parse_event_lines(bytes(stdout))
|
|
394
|
+
startup_notices = []
|
|
395
|
+
for event in events:
|
|
396
|
+
if event.get("type") in {"thread.started", "turn.started", "turn.completed"}:
|
|
397
|
+
continue
|
|
398
|
+
if event.get("type") not in {"item.started", "item.updated", "item.completed"}:
|
|
399
|
+
raise ValueError(f"native Codex event rejected: {event.get('type')}")
|
|
400
|
+
item = event.get("item")
|
|
401
|
+
if (event.get("type") == "item.completed" and isinstance(item, dict)
|
|
402
|
+
and item.get("type") == "error"
|
|
403
|
+
and item.get("message") == DISABLED_CODE_MODE_NOTICE):
|
|
404
|
+
startup_notices.append(item["message"])
|
|
405
|
+
continue
|
|
406
|
+
if (not isinstance(item, dict)
|
|
407
|
+
or item.get("type") not in {"agent_message", "reasoning", "plan", "todo_list"}):
|
|
408
|
+
raise ValueError("native Codex emitted an error or tool-call item")
|
|
409
|
+
if not any(row.get("type") == "turn.completed" for row in events):
|
|
410
|
+
raise ValueError("native Codex judge emitted no turn.completed event")
|
|
411
|
+
final = final_path.read_text(encoding="utf-8")
|
|
412
|
+
verdict = _verdict(final)
|
|
413
|
+
audit = _audit_native(events, journal_root, audit_path, started + timeout,
|
|
414
|
+
prompt.decode("utf-8"))
|
|
415
|
+
completed = [row for row in events if row.get("type") == "turn.completed"]
|
|
416
|
+
usage = [row.get("usage") for row in completed]
|
|
417
|
+
if len(completed) != 1 or any(not isinstance(row, dict) for row in usage):
|
|
418
|
+
raise ValueError("native Codex judge usage is missing or malformed")
|
|
419
|
+
counters = usage[0]
|
|
420
|
+
if (any(type(counters.get(key)) is not int or counters[key] < 0
|
|
421
|
+
for key in ("input_tokens", "cached_input_tokens", "output_tokens"))
|
|
422
|
+
or counters["cached_input_tokens"] > counters["input_tokens"]):
|
|
423
|
+
raise ValueError("native Codex usage counters are incomplete or malformed")
|
|
424
|
+
return {"status": "PASS", "elapsed_seconds": round(time.monotonic() - started, 3),
|
|
425
|
+
"final_sha256": _sha(final_path), "events_sha256": _sha(events_path),
|
|
426
|
+
"stderr_sha256": _sha(stderr_path), "usage": usage, "native_audit": audit,
|
|
427
|
+
"startup_notices": startup_notices,
|
|
428
|
+
"verdict": verdict}
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _metrics(rows: list[dict[str, Any]], refs: dict[str, Any]) -> dict[str, Any]:
|
|
432
|
+
row_ids = [row.get("question_id") for row in rows]
|
|
433
|
+
if (len(rows) != full.FULL_CASES or len(refs) != full.FULL_CASES
|
|
434
|
+
or len(set(row_ids)) != full.FULL_CASES or set(row_ids) != set(refs)
|
|
435
|
+
or any(type(row.get("correct")) is not bool for row in rows)):
|
|
436
|
+
raise ValueError("judge score coverage incomplete")
|
|
437
|
+
by_category: dict[str, list[bool]] = {}
|
|
438
|
+
abstentions: list[bool] = []
|
|
439
|
+
for row in rows:
|
|
440
|
+
correct = row["correct"]
|
|
441
|
+
category = refs[row["question_id"]]["question_type"]
|
|
442
|
+
by_category.setdefault(category, []).append(correct)
|
|
443
|
+
if "_abs" in row["question_id"]:
|
|
444
|
+
abstentions.append(correct)
|
|
445
|
+
return {"accuracy": sum(row["correct"] for row in rows) / len(rows),
|
|
446
|
+
"correct_count": sum(row["correct"] for row in rows),
|
|
447
|
+
"macro_category_accuracy": sum(sum(items) / len(items) for items in by_category.values()) / len(by_category),
|
|
448
|
+
"category_accuracy": {key: sum(items) / len(items) for key, items in sorted(by_category.items())},
|
|
449
|
+
"category_counts": {key: len(items) for key, items in sorted(by_category.items())},
|
|
450
|
+
"abstention_subset": {"count": len(abstentions),
|
|
451
|
+
"correct_count": sum(abstentions),
|
|
452
|
+
"accuracy": sum(abstentions) / len(abstentions) if abstentions else None}}
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
async def run(output: Path, *, codex_path: Path | None = None,
|
|
456
|
+
journal_root: Path | None = None) -> dict[str, Any]:
|
|
457
|
+
manifest, cases = _validate_prepared(output, for_run=True)
|
|
458
|
+
if codex_path is not None and codex_path.resolve() != Path(manifest["codex_executable"]).resolve():
|
|
459
|
+
raise ValueError("Codex executable differs from validated preparation")
|
|
460
|
+
work = output / "execution"
|
|
461
|
+
work.mkdir()
|
|
462
|
+
receipts = work / "receipts"
|
|
463
|
+
receipts.mkdir()
|
|
464
|
+
ledger = work / "progress.jsonl"
|
|
465
|
+
_write_new(ledger, b"")
|
|
466
|
+
started = time.monotonic()
|
|
467
|
+
deadline = started + MAX_WALL_SECONDS
|
|
468
|
+
journal_root = journal_root or (Path.home() / ".codex" / "sessions")
|
|
469
|
+
_full_manifest, hypotheses, refs = _sealed_full(Path(manifest["full_run_path"]))
|
|
470
|
+
rows = []
|
|
471
|
+
try:
|
|
472
|
+
for item in cases:
|
|
473
|
+
remaining = deadline - time.monotonic()
|
|
474
|
+
if remaining < 1:
|
|
475
|
+
raise TimeoutError("two-hour judge wall deadline reached")
|
|
476
|
+
prefix = f"case-{item['ordinal']:04d}"
|
|
477
|
+
prompt_path = output / item["prompt_file"]
|
|
478
|
+
prompt = prompt_path.read_bytes()
|
|
479
|
+
if _sha_bytes(prompt) != item["prompt_sha256"]:
|
|
480
|
+
raise ValueError("exact rubric prompt changed after preparation")
|
|
481
|
+
case_dir = work / prefix
|
|
482
|
+
case_dir.mkdir()
|
|
483
|
+
cwd = case_dir / "cwd"
|
|
484
|
+
_append_jsonl(ledger, {"event": "CASE_STARTED", "ordinal": item["ordinal"],
|
|
485
|
+
"question_id": item["question_id"], "started_at": _utc_now()})
|
|
486
|
+
receipt = await _invoke(Path(manifest["codex_executable"]), prompt, cwd,
|
|
487
|
+
journal_root, receipts, prefix,
|
|
488
|
+
timeout=max(1, min(CASE_TIMEOUT_SECONDS, int(remaining))))
|
|
489
|
+
# Keep the upstream criterion literal: official scoring checks for
|
|
490
|
+
# the substring yes, even though judge output itself is constrained.
|
|
491
|
+
reference_match = "yes" in receipt["verdict"].lower()
|
|
492
|
+
row = {"ordinal": item["ordinal"], "question_id": item["question_id"],
|
|
493
|
+
"verdict": receipt["verdict"], "correct": reference_match,
|
|
494
|
+
"receipt": receipt}
|
|
495
|
+
rows.append(row)
|
|
496
|
+
_append_jsonl(ledger, {"event": "CASE_COMPLETED", "ordinal": item["ordinal"],
|
|
497
|
+
"question_id": item["question_id"],
|
|
498
|
+
"receipt_sha256": _sha_bytes(_json_bytes(receipt)),
|
|
499
|
+
"correct": reference_match, "ended_at": _utc_now()})
|
|
500
|
+
labels_path = work / "labels.jsonl"
|
|
501
|
+
with labels_path.open("ab") as stream:
|
|
502
|
+
stream.write(json.dumps(row, ensure_ascii=False).encode("utf-8") + b"\n")
|
|
503
|
+
stream.flush(); os.fsync(stream.fileno())
|
|
504
|
+
metrics = _metrics(rows, refs)
|
|
505
|
+
result = {"status": "COMPLETE_NONOFFICIAL_AGENT_JUDGE", "completed": full.FULL_CASES,
|
|
506
|
+
"selected": full.FULL_CASES, "scoring_label": "NONOFFICIAL_AGENT_JUDGE",
|
|
507
|
+
"official_score": None, **metrics, "labels_sha256": _sha(work / "labels.jsonl"),
|
|
508
|
+
"full_manifest_sha256": _sha(Path(manifest["full_run_path"]) / "manifest.json"),
|
|
509
|
+
"hypotheses_sha256": manifest["hypotheses_sha256"],
|
|
510
|
+
"elapsed_seconds": round(time.monotonic() - started, 3)}
|
|
511
|
+
_write_new(work / "result.json", _json_bytes(result))
|
|
512
|
+
return result
|
|
513
|
+
except Exception as exc:
|
|
514
|
+
failure = {"status": "STOPPED_AGENT_JUDGE", "completed": len(rows), "selected": full.FULL_CASES,
|
|
515
|
+
"error_type": type(exc).__name__, "official_score": None,
|
|
516
|
+
"elapsed_seconds": round(time.monotonic() - started, 3)}
|
|
517
|
+
_write_new(work / "failure.json", _json_bytes(failure))
|
|
518
|
+
raise
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def probe(output: Path, codex: Path, *, journal_root: Path | None = None) -> dict[str, Any]:
|
|
522
|
+
"""Verify the native, isolated, no-tools route before a long campaign."""
|
|
523
|
+
codex = codex.resolve()
|
|
524
|
+
if output.exists() or not output.parent.is_dir() or not codex.is_file():
|
|
525
|
+
raise ValueError("probe output must be new and Codex executable must exist")
|
|
526
|
+
output.mkdir()
|
|
527
|
+
_write_new(output / "manifest.json", _json_bytes({"schema": "longmemeval-agent-judge-probe.v1",
|
|
528
|
+
"model": MODEL, "reasoning_effort": REASONING, "codex_path": str(codex),
|
|
529
|
+
"codex_sha256": _sha(codex)}))
|
|
530
|
+
rows = []
|
|
531
|
+
root = journal_root or (Path.home() / ".codex" / "sessions")
|
|
532
|
+
for index, (prompt, expected) in enumerate((
|
|
533
|
+
("Judge this probe: Is 2 equal to 2? Reply with exactly yes or no.", "yes"),
|
|
534
|
+
("Judge this probe: Is 2 equal to 3? Reply with exactly yes or no.", "no")), 1):
|
|
535
|
+
case = output / f"probe-{index:02d}"
|
|
536
|
+
case.mkdir()
|
|
537
|
+
receipt = asyncio.run(_invoke(codex, prompt.encode("utf-8"), case / "cwd", root, case,
|
|
538
|
+
f"probe-{index:02d}"))
|
|
539
|
+
if receipt["verdict"] != expected:
|
|
540
|
+
raise ValueError("neutral probe verdict does not match its expected control")
|
|
541
|
+
rows.append(receipt)
|
|
542
|
+
result = {"status": "PASS", "cases": len(rows), "model": MODEL, "tool_calls": 0,
|
|
543
|
+
"receipts": [{"final_sha256": row["final_sha256"], "events_sha256": row["events_sha256"],
|
|
544
|
+
"native_audit": row["native_audit"]} for row in rows]}
|
|
545
|
+
_write_new(output / "result.json", _json_bytes(result))
|
|
546
|
+
return result
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def wait_and_run(full_root: Path, evaluator: Path, output: Path, wait_seconds: int = 10800) -> dict[str, Any]:
|
|
550
|
+
"""Wait only for the already-running full result, bounded by its original 8h window."""
|
|
551
|
+
if wait_seconds < 0 or wait_seconds > 10800:
|
|
552
|
+
raise ValueError("wait-seconds must be between zero and 10800")
|
|
553
|
+
run_path = full_root / "execution" / "run.json"
|
|
554
|
+
run_info = json.loads(run_path.read_text(encoding="utf-8"))
|
|
555
|
+
started_at = datetime.fromisoformat(run_info["started_at"].replace("Z", "+00:00"))
|
|
556
|
+
deadline = started_at.timestamp() + full.MAX_WALL_SECONDS + 30
|
|
557
|
+
stop = min(time.monotonic() + wait_seconds, time.monotonic() + max(0, deadline - time.time()))
|
|
558
|
+
result_path = full_root / "execution" / "result.json"
|
|
559
|
+
while not result_path.is_file() and time.monotonic() < stop:
|
|
560
|
+
time.sleep(min(POLL_SECONDS, max(0, stop - time.monotonic())))
|
|
561
|
+
if not result_path.is_file():
|
|
562
|
+
raise TimeoutError("full-run result did not arrive before the original actor deadline")
|
|
563
|
+
result = json.loads(result_path.read_text(encoding="utf-8"))
|
|
564
|
+
if result.get("status") != "ANSWERS_SEALED":
|
|
565
|
+
raise ValueError("full run ended without ANSWERS_SEALED; refusing agent scoring")
|
|
566
|
+
prepare(full_root, evaluator, output)
|
|
567
|
+
return asyncio.run(run(output))
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def main() -> None:
|
|
571
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
572
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
573
|
+
prep = commands.add_parser("prepare")
|
|
574
|
+
prep.add_argument("full_root", type=Path); prep.add_argument("evaluator", type=Path); prep.add_argument("output", type=Path)
|
|
575
|
+
execute = commands.add_parser("run"); execute.add_argument("output", type=Path)
|
|
576
|
+
waiting = commands.add_parser("wait-and-run")
|
|
577
|
+
waiting.add_argument("full_root", type=Path); waiting.add_argument("evaluator", type=Path); waiting.add_argument("output", type=Path)
|
|
578
|
+
waiting.add_argument("--wait-seconds", type=int, default=10800)
|
|
579
|
+
test = commands.add_parser("probe"); test.add_argument("output", type=Path); test.add_argument("--codex", type=Path, required=True)
|
|
580
|
+
args = parser.parse_args()
|
|
581
|
+
if args.command == "prepare":
|
|
582
|
+
result = prepare(args.full_root, args.evaluator, args.output)
|
|
583
|
+
elif args.command == "run":
|
|
584
|
+
result = asyncio.run(run(args.output))
|
|
585
|
+
elif args.command == "wait-and-run":
|
|
586
|
+
result = wait_and_run(args.full_root, args.evaluator, args.output, args.wait_seconds)
|
|
587
|
+
else:
|
|
588
|
+
result = probe(args.output, args.codex)
|
|
589
|
+
print(json.dumps(result, separators=(",", ":")))
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
if __name__ == "__main__":
|
|
593
|
+
main()
|