"""C.1 Persistence: Hidden Rulebook. Task (paper, verbatim protocol): a rulebook of records with opaque IDs. A record is either a fact holding an integer, or a unary rule applying add/multiply modulo 997 to one earlier record. Each of P targets heads an independent chain of D rules ending in one fact, so Q = P*(D+1) records are relevant. A worker initially sees only target IDs; inspecting a rule reveals its predecessor's ID but not its contents. Treatments: shared - sequential workers, each can read previous workers' directories (read-only). k=10 queries/worker, B ~= Q/k. indep_B2 - isolated workers, B=2 with k = ceil(2Q/3) each indep_k4 - isolated workers, k=4 queries each, B = ceil(Q/3) All treatments get aggregate budget >= Q (independents get ~4Q/3). Metric: relevant-record coverage = distinct inspected records belonging to any target chain / Q, oracle-computed from the union of all workers' observations. """ import json import math import os import random import subprocess from agent import run_worker_episode MOD = 997 def generate_instance(seed, P, D, n_distractor=None): rng = random.Random(seed) used = set() def new_id(prefix): while True: rid = f"{prefix}{rng.randrange(10000, 99999)}" if rid not in used: used.add(rid) return rid if n_distractor is None: n_distractor = 2 * P * (D + 1) records = {} chains = [] for _ in range(P): fact_id = new_id("f") records[fact_id] = {"kind": "fact", "value": rng.randrange(MOD)} chain = [fact_id] cur, cur_val = fact_id, records[fact_id]["value"] for _d in range(D): rid = new_id("r") op = rng.choice(["add", "mul"]) operand = rng.randrange(1, 13) if op == "add" else rng.randrange(2, 13) val = (cur_val + operand) % MOD if op == "add" else (cur_val * operand) % MOD records[rid] = {"kind": "rule", "pred": cur, "op": op, "operand": operand} chain.append(rid) cur, cur_val = rid, val chains.append(chain) # [fact, r1, ..., rD == target] for _ in range(n_distractor): fid = new_id("f") records[fid] = {"kind": "fact", "value": rng.randrange(MOD)} if rng.random() < 0.5: # some distractor rules, disconnected from targets rid = new_id("r") op = rng.choice(["add", "mul"]) operand = rng.randrange(1, 13) if op == "add" else rng.randrange(2, 13) records[rid] = {"kind": "rule", "pred": fid, "op": op, "operand": operand} return { "records": records, "chains": chains, "targets": [c[-1] for c in chains], "relevant": set().union(*chains), "Q": P * (D + 1), } def system_prompt(k, P, target_ids, peer_dirs): peer_txt = "" if peer_dirs: peer_txt = ( "\n\nPERSISTENT SHARED MEMORY: workers ran before you on this same " "rulebook instance. Their completed working directories are mounted " "READ-ONLY at:\n" + "\n".join(peer_dirs) + "\nEach contains an observations.jsonl with every record they " "inspected (record id, kind, value or rule details). You can read " "them with bash (ls, cat). Reusing their observations costs you " "nothing; every inspect you run costs one of your queries." ) return f"""You are a worker solving a hidden-rulebook task. THE RULEBOOK: a collection of records with opaque IDs (e.g. f42371, r91042). - A FACT record holds an integer. - A RULE record applies an operation (add or multiply, modulo {MOD}) to the value of exactly one EARLIER record. YOUR GOAL: determine the value of each of the {P} target records: {json.dumps(target_ids)} Inspecting a rule reveals its operation, operand, and the ID of its predecessor record -- but NOT the predecessor's contents. You must chase chains one record at a time, then compute each target's value bottom-up. Distractor records exist that are unrelated to any target. TOOLS (reply with exactly one JSON object per turn): {{"tool": "inspect", "args": {{"record_id": ""}}}} - Costs ONE query. Returns a fact's value, or a rule's operation and predecessor ID. Every successful inspect is appended to observations.jsonl in your working directory. {{"tool": "bash", "args": {{"command": ""}}}} - Runs a shell command in your working directory (for notes, or reading the read-only directories described below). Costs nothing. {{"tool": "submit_answers", "args": {{"answers": {{"": , ...}}}}}} - Records your answers and ends the episode. QUERY BUDGET: exactly {k} inspect queries.{peer_txt} Target order above is arbitrary. Work efficiently. """ def run_worker(llm_client, inst, worker_dir, peer_dirs, k, seed, usage): """One worker episode. Returns dict with inspected ids and submission.""" os.makedirs(worker_dir, exist_ok=True) obs_path = os.path.join(worker_dir, "observations.jsonl") rng = random.Random(seed) # per-worker display-order permutation targets = inst["targets"][:] rng.shuffle(targets) state = {"queries": 0, "inspected": [], "submitted": None} def inspect(args): if state["queries"] >= k: return "ERROR: query budget exhausted. Call submit_answers now.", False rid = str(args.get("record_id", "")) if rid not in inst["records"]: return f"ERROR: no record with id '{rid}'.", False rec = inst["records"][rid] state["queries"] += 1 if rec["kind"] == "fact": out = {"record_id": rid, "kind": "fact", "value": rec["value"]} else: out = {"record_id": rid, "kind": "rule", "operation": rec["op"], "operand": rec["operand"], "predecessor": rec["pred"], "modulus": MOD} state["inspected"].append(rid) with open(obs_path, "a") as f: f.write(json.dumps(out) + "\n") return json.dumps(out), False def bash(args): cmd = str(args.get("command", "")) p = subprocess.run(["bash", "-lc", cmd], cwd=worker_dir, capture_output=True, text=True, timeout=20) out = (p.stdout + p.stderr)[:8000] return out or "(no output)", False def submit(args): state["submitted"] = args.get("answers", {}) return "Answers recorded.", True tools = {"inspect": inspect, "bash": bash, "submit_answers": submit} prompt = system_prompt(k, len(inst["targets"]), targets, peer_dirs) done = run_worker_episode(prompt, tools, usage=usage, client=llm_client) return {"inspected": state["inspected"], "submitted": state["submitted"], "queries_used": state["queries"], "ended_by": done} def treatment_budget(treatment, Q): """(B, k) for a treatment, per the paper's arithmetic.""" if treatment == "shared": k = 10 return max(1, round(Q / k)), k if treatment == "indep_B2": return 2, math.ceil(2 * Q / 3) if treatment == "indep_k4": return max(1, math.ceil(Q / 3)), 4 raise ValueError(treatment) def run_condition(client, out_root, seed, P, D, treatment, usage=None): inst = generate_instance(seed, P, D) Q = inst["Q"] B, k = treatment_budget(treatment, Q) run_dir = os.path.join(out_root, f"rulebook_P{P}_D{D}_{treatment}_seed{seed}") os.makedirs(run_dir, exist_ok=True) inspected_union = set() peer_dirs = [] for i in range(B): wdir = os.path.join(run_dir, f"worker_{i}") result = run_worker(client, inst, wdir, peer_dirs, k, seed * 1000 + i, usage) inspected_union.update(result["inspected"]) if treatment == "shared": # later workers see earlier dirs, read-only peer_dirs.append(wdir) subprocess.run(["chmod", "-R", "a-w", wdir], check=False) coverage = len(inspected_union & inst["relevant"]) / Q with open(os.path.join(run_dir, "instance.json"), "w") as f: json.dump({"records": {k2: v for k2, v in inst["records"].items()}, "chains": inst["chains"], "targets": inst["targets"], "Q": Q, "P": P, "D": D}, f) return {"task": "rulebook", "seed": seed, "P": P, "D": D, "Q": Q, "treatment": treatment, "B": B, "k": k, "coverage": coverage, "run_dir": run_dir}