HassamGani commited on
Commit
bc1b9e6
·
1 Parent(s): 3f3eab2

Add belief probes, bootstrap intervals and a paired compare command; count unfinished carried-over work when judging retirement

Browse files
README.md CHANGED
@@ -23,6 +23,8 @@ uv run reorgbench list
23
  uv run reorgbench oracle hand-02-double-charge --trace runs/oracle-02.jsonl
24
  uv run reorgbench score runs/oracle-02.jsonl # add --json for every metric
25
  uv run pytest
 
 
26
  ```
27
 
28
  ## How an episode runs
@@ -58,7 +60,7 @@ These are computed from the trace with rules only. Messages they can't resolve a
58
  - promptness, the share of rounds in which the needed roles are present;
59
  - unnecessary hires.
60
  - **Retirement:**
61
- - kill precision and recall after a goal change;
62
  - handoff recall: did a retired agent pass on planted facts others still needed.
63
  - **Work:** waste (contributing / all actions) × parsimony (reference length / contributing), per-agent usefulness, and specialist use.
64
  - **Communication:**
@@ -67,6 +69,26 @@ These are computed from the trace with rules only. Messages they can't resolve a
67
  - whether planted facts reached the roles that need them.
68
  - **Questions:** how many the orchestrator asked, how many matched a pre-written answer, and how many only repeated what it had already been told. Questions don't count toward waste.
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  Prior-work metrics are reimplemented for comparison: AgentWorld CCE/PAC, the MultiAgentBench KPI, MS-Eval staffing F1 and ClawArena-Team tool use.
71
 
72
  ## Splits, RL and training disclosure
 
23
  uv run reorgbench oracle hand-02-double-charge --trace runs/oracle-02.jsonl
24
  uv run reorgbench score runs/oracle-02.jsonl # add --json for every metric
25
  uv run pytest
26
+ uv run reorgbench run --model claude-haiku-5-5 --split dev --runs 3 --out runs/haiku
27
+ uv run reorgbench compare runs/haiku runs/other # paired difference with 90% intervals
28
  ```
29
 
30
  ## How an episode runs
 
60
  - promptness, the share of rounds in which the needed roles are present;
61
  - unnecessary hires.
62
  - **Retirement:**
63
+ - kill precision and recall after a goal change. An agent is obsolete when it's surplus to the closest acceptable team for the new goal, counting any role whose carried-over work is still unfinished as needed. A kill also counts as correct if that work was finished by the time of the kill;
64
  - handoff recall: did a retired agent pass on planted facts others still needed.
65
  - **Work:** waste (contributing / all actions) × parsimony (reference length / contributing), per-agent usefulness, and specialist use.
66
  - **Communication:**
 
69
  - whether planted facts reached the roles that need them.
70
  - **Questions:** how many the orchestrator asked, how many matched a pre-written answer, and how many only repeated what it had already been told. Questions don't count toward waste.
71
 
72
+ ### Belief probes
73
+
74
+ Every 4 rounds, on the turn the orchestrator first reads a goal change, and on the turn it finishes, it is asked outside the run for probabilities on three kinds of statement:
75
+
76
+ - **scope:** each piece of work asked for so far is still part of the goal (only after a change, so dropped work shows up). Work a change widened, rather than dropped, still counts as part of the goal;
77
+ - **done:** each checkpoint of the current goal is already true in the world;
78
+ - **team:** each live agent's role is on the team the current goal needs (the same rule as retirement).
79
+
80
+ The truth comes from the task's own checkpoints, the verifier and the reference staffing at that moment. The question is asked on a copy of the orchestrator's conversation, so the answer never enters the run, costs no action and isn't counted against the token budget. Reported:
81
+
82
+ - the probability put on the truth, overall and per kind (1 is perfect, 0.5 is a coin flip), plus Brier scores;
83
+ - for items a goal change flipped, that probability at the first probe after the change and at the last one, which shows whether the orchestrator really updates;
84
+ - at finish, how strongly it believed checkpoints that were in fact unmet (overclaim).
85
+
86
+ `--no-probes` turns them off.
87
+
88
+ ### Uncertainty
89
+
90
+ A score is the mean over tasks of each task's mean over runs. Summaries give 90% intervals from a two-stage bootstrap (resample tasks, then runs within each task). `reorgbench compare A B` gives the paired difference between two run directories on the tasks both ran, which is far tighter than two separate intervals.
91
+
92
  Prior-work metrics are reimplemented for comparison: AgentWorld CCE/PAC, the MultiAgentBench KPI, MS-Eval staffing F1 and ClawArena-Team tool use.
93
 
94
  ## Splits, RL and training disclosure
reorgbench/cli.py CHANGED
@@ -33,6 +33,25 @@ def _print_scores(s: dict) -> None:
33
  q = s["questions"]
34
  if q["asked"]:
35
  print(f" questions: {q['asked']} asked, {q['answered']} answered, {q['repeated']} repeats")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
 
38
  def main(argv: list[str] | None = None) -> int:
@@ -55,9 +74,13 @@ def main(argv: list[str] | None = None) -> int:
55
  "(default: the pinned matcher model)")
56
  rn.add_argument("--no-questions", action="store_true",
57
  help="variant where the orchestrator can't ask the person anything")
 
58
  rn.add_argument("--runs", type=int, default=1, help="runs per task")
59
  rn.add_argument("--jobs", type=int, default=4, help="episodes in parallel")
60
  rn.add_argument("--out", type=Path, required=True, help="output directory")
 
 
 
61
  sc = sub.add_parser("score", help="score a saved trace")
62
  sc.add_argument("trace", type=Path)
63
  sc.add_argument("--json", action="store_true", help="print every metric as JSON, plus prior-work metrics")
@@ -92,14 +115,28 @@ def main(argv: list[str] | None = None) -> int:
92
 
93
  print(f"running {len(tasks)} task(s) x {args.runs} with {orch.model} / {subs.model} -> {args.out}")
94
  s = run_tasks(tasks, args.out, orch, subs, runs=args.runs, jobs=args.jobs, on_done=done, matcher=matcher,
95
- questions=not args.no_questions)
96
- o = s["overall"]
97
- print(f"success {_fmt(o['success'])} pass^k {_fmt(o['pass^k'])} staffing {_fmt(o['staffing'])} "
98
- f"efficiency {_fmt(o['efficiency'])} message yield {_fmt(o['message_yield'])} "
99
- f"tokens/run {_fmt(o['tokens'])}")
 
100
  print(f"summary: {args.out / 'summary.json'}")
101
  return 0
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  if args.cmd == "score":
104
  header, events = read_jsonl(args.trace)
105
  errs = validate_trace(events)
 
33
  q = s["questions"]
34
  if q["asked"]:
35
  print(f" questions: {q['asked']} asked, {q['answered']} answered, {q['repeated']} repeats")
36
+ b = s.get("beliefs")
37
+ if b and b["answered"]:
38
+ f = b["families"]
39
+ print(f" beliefs ({b['answered']} probes): on truth {_fmt(b['on_truth'])} scope {_fmt(f['scope']['on_truth'])}"
40
+ f" done {_fmt(f['done']['on_truth'])} team {_fmt(f['team']['on_truth'])}"
41
+ f" after a change {_fmt(b['update_first'])} -> {_fmt(b['update_last'])}")
42
+
43
+
44
+ def _ci(c: dict) -> str:
45
+ return "-" if c["mean"] is None else f"{c['mean']:.2f} [{c['lo']:.2f}, {c['hi']:.2f}]"
46
+
47
+
48
+ def _by_task(out: Path, key: str) -> dict[str, list]:
49
+ rows = json.loads((out / "summary.json").read_text())["runs"]
50
+ by: dict[str, list] = {}
51
+ for r in rows:
52
+ v = r.get(key)
53
+ by.setdefault(r["task"], []).append(float(v) if isinstance(v, bool) else v)
54
+ return by
55
 
56
 
57
  def main(argv: list[str] | None = None) -> int:
 
74
  "(default: the pinned matcher model)")
75
  rn.add_argument("--no-questions", action="store_true",
76
  help="variant where the orchestrator can't ask the person anything")
77
+ rn.add_argument("--no-probes", action="store_true", help="skip the orchestrator's belief probes")
78
  rn.add_argument("--runs", type=int, default=1, help="runs per task")
79
  rn.add_argument("--jobs", type=int, default=4, help="episodes in parallel")
80
  rn.add_argument("--out", type=Path, required=True, help="output directory")
81
+ cp = sub.add_parser("compare", help="paired difference between two run directories, on the tasks both ran")
82
+ cp.add_argument("a", type=Path)
83
+ cp.add_argument("b", type=Path)
84
  sc = sub.add_parser("score", help="score a saved trace")
85
  sc.add_argument("trace", type=Path)
86
  sc.add_argument("--json", action="store_true", help="print every metric as JSON, plus prior-work metrics")
 
115
 
116
  print(f"running {len(tasks)} task(s) x {args.runs} with {orch.model} / {subs.model} -> {args.out}")
117
  s = run_tasks(tasks, args.out, orch, subs, runs=args.runs, jobs=args.jobs, on_done=done, matcher=matcher,
118
+ questions=not args.no_questions, probes=not args.no_probes)
119
+ o, ci = s["overall"], s["ci90"]
120
+ print(f"success {_ci(ci['success'])} pass^k {_ci(ci['pass^k'])} staffing {_ci(ci['staffing'])} "
121
+ f"beliefs {_ci(ci['belief'])} (90% intervals)")
122
+ print(f"efficiency {_fmt(o['efficiency'])} message yield {_fmt(o['message_yield'])} "
123
+ f"tokens/run {_fmt(o['tokens'])} probe tokens/run {_fmt(o['probe_tokens'])}")
124
  print(f"summary: {args.out / 'summary.json'}")
125
  return 0
126
 
127
+ if args.cmd == "compare":
128
+ from .stats import paired
129
+
130
+ print(f"{args.a} minus {args.b}, paired over shared tasks, 90% intervals")
131
+ for key in ("success", "partial", "staffing", "belief", "tokens"):
132
+ d = paired(_by_task(args.a, key), _by_task(args.b, key))
133
+ if d["diff"] is None:
134
+ print(f" {key}: -")
135
+ continue
136
+ print(f" {key}: {d['diff']:+.3f} [{d['lo']:+.3f}, {d['hi']:+.3f}] over {d['tasks']} tasks, "
137
+ f"a ahead on {d['a_better']}, b ahead on {d['b_better']}")
138
+ return 0
139
+
140
  if args.cmd == "score":
141
  header, events = read_jsonl(args.trace)
142
  errs = validate_trace(events)
reorgbench/harness/policy.py CHANGED
@@ -7,6 +7,7 @@ message (the action it took). Pinned rules:
7
  - Context overflow: once the history passes HISTORY_CHAR_CAP characters, the oldest turns after the first
8
  (which holds the brief) are dropped, and the drop is recorded in the call log.
9
  - Every model call is appended to the call log, the per-call record the trace format asks for.
 
10
  """
11
 
12
  from __future__ import annotations
@@ -89,3 +90,12 @@ class LLMPolicy:
89
  out = dict(action) if action is not None else {"unparseable_output": last_text[:2000]}
90
  out["_usage"] = {"in": tin, "out": tout}
91
  return out
 
 
 
 
 
 
 
 
 
 
7
  - Context overflow: once the history passes HISTORY_CHAR_CAP characters, the oldest turns after the first
8
  (which holds the brief) are dropped, and the drop is recorded in the call log.
9
  - Every model call is appended to the call log, the per-call record the trace format asks for.
10
+ - probe() answers a belief probe on a copy of the conversation and leaves the history untouched.
11
  """
12
 
13
  from __future__ import annotations
 
90
  out = dict(action) if action is not None else {"unparseable_output": last_text[:2000]}
91
  out["_usage"] = {"in": tin, "out": tout}
92
  return out
93
+
94
+ def probe(self, question: str) -> dict[str, Any]:
95
+ """Asks on a copy of the conversation; nothing is added to the agent's history."""
96
+ convo = self.history + [{"role": "user", "content": question}]
97
+ c = self.client.complete(self.system, convo)
98
+ self.log.add({"agent": self.info.id, "role": self.info.role, "probe": True, "model": self.client.model,
99
+ "question": question, "text": c.text, "tokens_in": c.tokens_in, "tokens_out": c.tokens_out,
100
+ "request_id": c.request_id, "stop_reason": c.stop_reason})
101
+ return {"text": c.text, "tokens_in": c.tokens_in, "tokens_out": c.tokens_out}
reorgbench/harness/runner.py CHANGED
@@ -22,6 +22,7 @@ from ..reward import reward
22
  from ..runtime import Episode
23
  from ..runtime.policy import AgentInfo, InfraError
24
  from ..schema import Event, write_jsonl
 
25
  from ..tasks.spec import Task
26
  from .clients import LLMClient
27
  from .policy import CallLog, LLMPolicy
@@ -39,8 +40,12 @@ def llm_factory(task: Task, orchestrator: LLMClient, subagents: LLMClient, log:
39
  return make
40
 
41
 
 
 
 
 
42
  def run_one(task: Task, k: int, out: Path, orchestrator: LLMClient, subagents: LLMClient,
43
- matcher: Matcher | None = None, questions: bool = True) -> dict[str, Any]:
44
  d = out / task.id
45
  d.mkdir(parents=True, exist_ok=True)
46
  calls = d / f"run{k}.calls.jsonl"
@@ -48,23 +53,28 @@ def run_one(task: Task, k: int, out: Path, orchestrator: LLMClient, subagents: L
48
  log = CallLog(calls)
49
  t0 = time.monotonic()
50
  ep = Episode(task, llm_factory(task, orchestrator, subagents, log, questions), matcher=matcher,
51
- questions=questions)
52
  res = ep.run()
53
  header = {**res.header(), "run": k, "orchestrator_model": orchestrator.model, "subagent_model": subagents.model,
54
  "matcher": ep.matcher.id if questions else None,
55
- "questions_allowed": questions, "wall_s": round(time.monotonic() - t0, 1)}
 
 
56
  write_jsonl(d / f"run{k}.jsonl", header, [Event(**e) for e in res.events])
57
  s = score(task, res)
58
  (d / f"run{k}.score.json").write_text(json.dumps(s, indent=1, default=str))
59
- retries = sum(len(r["attempts"]) - 1 for r in log.records)
60
- unparsed = sum(1 for r in log.records if r["action"] is None)
 
61
  return {"task": task.id, "run": k, "success": res.verdict.success, "reward": reward(res.verdict),
62
  "partial": res.verdict.partial, "stop": res.stop_reason, "rounds": res.rounds,
63
  "staffing": s["headline"]["staffing"], "efficiency": s["headline"]["efficiency"],
64
  "message_yield": s["headline"]["message_yield"], "kill_precision": s["retirement"]["kill_precision"],
65
- "kill_recall": s["retirement"]["kill_recall"], "tokens": res.tokens_used, "calls": len(log.records),
66
  "retries": retries, "unparsed": unparsed, "errors": s["work"]["errors"],
67
  "questions": s["questions"]["asked"], "questions_answered": s["questions"]["answered"],
 
 
68
  "wall_s": header["wall_s"]}
69
 
70
 
@@ -78,20 +88,25 @@ def summarize(rows: list[dict[str, Any]]) -> dict[str, Any]:
78
  for r in rows:
79
  by_task.setdefault(r["task"], []).append(r)
80
  keys = ["success", "partial", "staffing", "efficiency", "message_yield", "kill_precision", "kill_recall",
81
- "tokens", "calls", "retries", "unparsed", "errors", "questions", "questions_answered"]
 
82
  per_task = {t: {k: _mean([float(r[k]) if isinstance(r[k], bool) else r[k] for r in rs]) for k in keys}
83
  | {"pass^k": all(r["success"] for r in rs), "runs": len(rs)} for t, rs in by_task.items()}
84
  overall = {k: _mean([v[k] for v in per_task.values()]) for k in keys}
85
  overall["pass^k"] = _mean([float(v["pass^k"]) for v in per_task.values()])
86
- return {"overall": overall, "per_task": per_task, "runs": rows}
 
 
 
87
 
88
 
89
  def run_with_reruns(task: Task, k: int, out: Path, orchestrator: LLMClient, subagents: LLMClient,
90
- matcher: Matcher | None = None, questions: bool = True, reruns: int = 2) -> dict[str, Any]:
 
91
  """Repeat a run at the same index after an infrastructure failure; never take the best of several."""
92
  for attempt in range(reruns + 1):
93
  try:
94
- row = run_one(task, k, out, orchestrator, subagents, matcher, questions)
95
  return row | {"infra_reruns": attempt}
96
  except InfraError:
97
  if attempt == reruns:
@@ -101,12 +116,13 @@ def run_with_reruns(task: Task, k: int, out: Path, orchestrator: LLMClient, suba
101
 
102
  def run_tasks(tasks: list[Task], out: Path, orchestrator: LLMClient, subagents: LLMClient, *, runs: int = 1,
103
  jobs: int = 4, on_done: Callable[[dict[str, Any]], None] | None = None,
104
- matcher: Matcher | None = None, questions: bool = True) -> dict[str, Any]:
105
  out.mkdir(parents=True, exist_ok=True)
106
  rows: list[dict[str, Any]] = []
107
  work = [(t, k) for t in tasks for k in range(runs)]
108
  with ThreadPoolExecutor(max_workers=jobs) as pool:
109
- futs = {pool.submit(run_with_reruns, t, k, out, orchestrator, subagents, matcher, questions): (t.id, k) for t, k in work}
 
110
  for f in as_completed(futs):
111
  try:
112
  row = f.result()
 
22
  from ..runtime import Episode
23
  from ..runtime.policy import AgentInfo, InfraError
24
  from ..schema import Event, write_jsonl
25
+ from ..stats import interval
26
  from ..tasks.spec import Task
27
  from .clients import LLMClient
28
  from .policy import CallLog, LLMPolicy
 
40
  return make
41
 
42
 
43
+ def _settings(c: LLMClient) -> dict[str, Any]:
44
+ return {k: getattr(c, k) for k in ("effort", "max_tokens") if hasattr(c, k)}
45
+
46
+
47
  def run_one(task: Task, k: int, out: Path, orchestrator: LLMClient, subagents: LLMClient,
48
+ matcher: Matcher | None = None, questions: bool = True, probes: bool = True) -> dict[str, Any]:
49
  d = out / task.id
50
  d.mkdir(parents=True, exist_ok=True)
51
  calls = d / f"run{k}.calls.jsonl"
 
53
  log = CallLog(calls)
54
  t0 = time.monotonic()
55
  ep = Episode(task, llm_factory(task, orchestrator, subagents, log, questions), matcher=matcher,
56
+ questions=questions, probes=probes)
57
  res = ep.run()
58
  header = {**res.header(), "run": k, "orchestrator_model": orchestrator.model, "subagent_model": subagents.model,
59
  "matcher": ep.matcher.id if questions else None,
60
+ "questions_allowed": questions, "probes": res.probes,
61
+ "settings": {"orchestrator": _settings(orchestrator), "subagents": _settings(subagents)},
62
+ "wall_s": round(time.monotonic() - t0, 1)}
63
  write_jsonl(d / f"run{k}.jsonl", header, [Event(**e) for e in res.events])
64
  s = score(task, res)
65
  (d / f"run{k}.score.json").write_text(json.dumps(s, indent=1, default=str))
66
+ acts = [r for r in log.records if not r.get("probe")]
67
+ retries = sum(len(r["attempts"]) - 1 for r in acts)
68
+ unparsed = sum(1 for r in acts if r["action"] is None)
69
  return {"task": task.id, "run": k, "success": res.verdict.success, "reward": reward(res.verdict),
70
  "partial": res.verdict.partial, "stop": res.stop_reason, "rounds": res.rounds,
71
  "staffing": s["headline"]["staffing"], "efficiency": s["headline"]["efficiency"],
72
  "message_yield": s["headline"]["message_yield"], "kill_precision": s["retirement"]["kill_precision"],
73
+ "kill_recall": s["retirement"]["kill_recall"], "tokens": res.tokens_used, "calls": len(acts),
74
  "retries": retries, "unparsed": unparsed, "errors": s["work"]["errors"],
75
  "questions": s["questions"]["asked"], "questions_answered": s["questions"]["answered"],
76
+ "belief": s["beliefs"]["on_truth"], "belief_update_first": s["beliefs"]["update_first"],
77
+ "probe_tokens": sum(p["tokens_in"] + p["tokens_out"] for p in res.probes),
78
  "wall_s": header["wall_s"]}
79
 
80
 
 
88
  for r in rows:
89
  by_task.setdefault(r["task"], []).append(r)
90
  keys = ["success", "partial", "staffing", "efficiency", "message_yield", "kill_precision", "kill_recall",
91
+ "tokens", "calls", "retries", "unparsed", "errors", "questions", "questions_answered",
92
+ "belief", "belief_update_first", "probe_tokens"]
93
  per_task = {t: {k: _mean([float(r[k]) if isinstance(r[k], bool) else r[k] for r in rs]) for k in keys}
94
  | {"pass^k": all(r["success"] for r in rs), "runs": len(rs)} for t, rs in by_task.items()}
95
  overall = {k: _mean([v[k] for v in per_task.values()]) for k in keys}
96
  overall["pass^k"] = _mean([float(v["pass^k"]) for v in per_task.values()])
97
+ ci = {k: interval({t: [float(r[k]) if isinstance(r[k], bool) else r[k] for r in rs] for t, rs in by_task.items()})
98
+ for k in ("success", "partial", "staffing", "belief")}
99
+ ci["pass^k"] = interval({t: [float(v["pass^k"])] for t, v in per_task.items()})
100
+ return {"overall": overall, "ci90": ci, "per_task": per_task, "runs": rows}
101
 
102
 
103
  def run_with_reruns(task: Task, k: int, out: Path, orchestrator: LLMClient, subagents: LLMClient,
104
+ matcher: Matcher | None = None, questions: bool = True, probes: bool = True,
105
+ reruns: int = 2) -> dict[str, Any]:
106
  """Repeat a run at the same index after an infrastructure failure; never take the best of several."""
107
  for attempt in range(reruns + 1):
108
  try:
109
+ row = run_one(task, k, out, orchestrator, subagents, matcher, questions, probes)
110
  return row | {"infra_reruns": attempt}
111
  except InfraError:
112
  if attempt == reruns:
 
116
 
117
  def run_tasks(tasks: list[Task], out: Path, orchestrator: LLMClient, subagents: LLMClient, *, runs: int = 1,
118
  jobs: int = 4, on_done: Callable[[dict[str, Any]], None] | None = None,
119
+ matcher: Matcher | None = None, questions: bool = True, probes: bool = True) -> dict[str, Any]:
120
  out.mkdir(parents=True, exist_ok=True)
121
  rows: list[dict[str, Any]] = []
122
  work = [(t, k) for t in tasks for k in range(runs)]
123
  with ThreadPoolExecutor(max_workers=jobs) as pool:
124
+ futs = {pool.submit(run_with_reruns, t, k, out, orchestrator, subagents, matcher, questions, probes): (t.id, k)
125
+ for t, k in work}
126
  for f in as_completed(futs):
127
  try:
128
  row = f.result()
reorgbench/metrics/score.py CHANGED
@@ -14,6 +14,7 @@ from functools import lru_cache
14
  from typing import Any
15
 
16
  from ..env.roles import specialist_tools
 
17
  from ..runtime.episode import EpisodeResult
18
  from ..tasks.spec import Task
19
  from .graph import ACTION_TYPES, CausalGraph, build_graph, salient_tokens
@@ -39,6 +40,21 @@ def _match(hired: Counter, staffings: list[list[str]]) -> tuple[Counter, float,
39
  return best
40
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  def _phase_bounds(res: EpisodeResult) -> list[tuple[int, int]]:
43
  starts = [1] + [e["round"] for e in res.events if e["type"] == "intervention"]
44
  return [(s, (starts[i + 1] - 1 if i + 1 < len(starts) else res.rounds)) for i, s in enumerate(starts)]
@@ -78,15 +94,22 @@ def retirement(task: Task, res: EpisodeResult, g: CausalGraph) -> dict[str, Any]
78
  for e in ivs:
79
  k, t = e["phase"], e["round"]
80
  alive = [a for a in subs.values() if _alive(a, t, res.rounds) and a["id"] not in obsolete]
81
- need, _, _ = _match(Counter(a["role"] for a in alive), task.phases[k].staffings)
82
- # surplus agents of each role are obsolete; keep the earliest-hired ones
83
- for a in sorted(alive, key=lambda a: a["spawn_round"]):
84
- if need[a["role"]] > 0:
85
- need[a["role"]] -= 1
86
- else:
87
  obsolete[a["id"]] = e["round"]
88
  scored = [k for k in kills if ivs and k["id"] > ivs[0]["id"]]
89
- good = [k for k in scored if k["payload"]["target"] in obsolete]
 
 
 
 
 
 
 
 
 
 
90
  retired = {k["payload"]["target"]: k["round"] for k in kills}
91
  timely = [a for a, t in obsolete.items() if a in retired and retired[a] - t <= KILL_WINDOW]
92
 
@@ -237,5 +260,6 @@ def score(task: Task, res: EpisodeResult, *, lstar: int | None = None) -> dict[s
237
  "stop_reason": res.stop_reason, "rounds": res.rounds, "actions": res.actions_used,
238
  "tokens": res.tokens_used, "interventions": res.interventions},
239
  "staffing": st, "retirement": ret, "work": work, "communication": comm, "questions": qs,
 
240
  "graph": {"seeds": sorted(g.seeds), "edges": sum(len(v) for v in g.parents.values())},
241
  }
 
14
  from typing import Any
15
 
16
  from ..env.roles import specialist_tools
17
+ from ..probes import score_probes
18
  from ..runtime.episode import EpisodeResult
19
  from ..tasks.spec import Task
20
  from .graph import ACTION_TYPES, CausalGraph, build_graph, salient_tokens
 
40
  return best
41
 
42
 
43
+ def needed_agents(task: Task, phase: int, alive: list[dict[str, Any]], open_ids=()) -> set[str]:
44
+ """Agents the phase still needs: the closest acceptable staffing, plus one agent for each role whose
45
+ carried-over checkpoint is still unmet. Surplus agents of a role are the latest-hired ones."""
46
+ need, _, _ = _match(Counter(a["role"] for a in alive), task.phases[phase].staffings)
47
+ for c in task.phases[phase].checkpoints:
48
+ if c.id in open_ids and c.capability and not c.negative:
49
+ need[c.capability] = max(need[c.capability], 1)
50
+ keep = set()
51
+ for a in sorted(alive, key=lambda a: a["spawn_round"]):
52
+ if need[a["role"]] > 0:
53
+ need[a["role"]] -= 1
54
+ keep.add(a["id"])
55
+ return keep
56
+
57
+
58
  def _phase_bounds(res: EpisodeResult) -> list[tuple[int, int]]:
59
  starts = [1] + [e["round"] for e in res.events if e["type"] == "intervention"]
60
  return [(s, (starts[i + 1] - 1 if i + 1 < len(starts) else res.rounds)) for i, s in enumerate(starts)]
 
94
  for e in ivs:
95
  k, t = e["phase"], e["round"]
96
  alive = [a for a in subs.values() if _alive(a, t, res.rounds) and a["id"] not in obsolete]
97
+ keep = needed_agents(task, k, alive, e["payload"].get("open_checks", ()))
98
+ for a in alive:
99
+ if a["id"] not in keep:
 
 
 
100
  obsolete[a["id"]] = e["round"]
101
  scored = [k for k in kills if ivs and k["id"] > ivs[0]["id"]]
102
+
103
+ def fine_kill(k: dict[str, Any]) -> bool:
104
+ # obsolete at the change, or its carried-over work was finished by the time it was killed
105
+ if k["payload"]["target"] in obsolete:
106
+ return True
107
+ if "open_checks" not in k["payload"]:
108
+ return False
109
+ alive = [a for a in subs.values() if _alive(a, k["round"], res.rounds)]
110
+ return k["payload"]["target"] not in needed_agents(task, k["phase"], alive, k["payload"]["open_checks"])
111
+
112
+ good = [k for k in scored if fine_kill(k)]
113
  retired = {k["payload"]["target"]: k["round"] for k in kills}
114
  timely = [a for a, t in obsolete.items() if a in retired and retired[a] - t <= KILL_WINDOW]
115
 
 
260
  "stop_reason": res.stop_reason, "rounds": res.rounds, "actions": res.actions_used,
261
  "tokens": res.tokens_used, "interventions": res.interventions},
262
  "staffing": st, "retirement": ret, "work": work, "communication": comm, "questions": qs,
263
+ "beliefs": score_probes(res.probes),
264
  "graph": {"seeds": sorted(g.seeds), "edges": sum(len(v) for v in g.parents.values())},
265
  }
reorgbench/probes.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Belief probes: what the orchestrator thinks about the goal, its progress and its team.
2
+
3
+ At fixed points the orchestrator is asked, outside the run, for probabilities on three kinds of statement,
4
+ and each is scored against the truth at that moment:
5
+ - scope: "this is still part of the current goal" (after a change only). Truth: the item is a checkpoint of
6
+ the active phase, or one it supersedes. Items come from every phase so far, so dropped work shows up here.
7
+ - done: "this is already true in our systems". Truth: the verifier's check on the world right now.
8
+ - team: "the team the current goal needs includes this agent's role". Truth: the agent isn't surplus to the
9
+ closest acceptable staffing, counting roles whose carried-over work is still unmet; the same rule the
10
+ retirement metric uses.
11
+
12
+ The probe is asked on a copy of the orchestrator's conversation. Its answer never enters the run, it costs
13
+ no action, and its tokens are counted apart from the episode's. Probes run every PROBE_EVERY rounds, on the
14
+ turn the orchestrator first reads a goal change, and on the turn it finishes.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import re
21
+ from typing import Any
22
+
23
+ from .env.world import World
24
+ from .tasks.spec import EpisodeView, Task
25
+
26
+ PROBE_EVERY = 4
27
+ PROBE_VERSION = "p1"
28
+
29
+ _OBJ = re.compile(r"\{.*\}", re.S)
30
+
31
+
32
+ def _positive(task: Task, phase: int) -> list:
33
+ return [c for c in task.phases[phase].checkpoints if not c.negative]
34
+
35
+
36
+ def build_items(task: Task, world: World, view: EpisodeView, phase: int,
37
+ alive: list[dict[str, Any]]) -> list[dict[str, Any]]:
38
+ """alive: live subagents as {"id", "role", "spawn_round"}."""
39
+ from .metrics.score import needed_agents # late import: metrics imports the runtime
40
+
41
+ def required(p: int) -> set[str]:
42
+ cps = _positive(task, p)
43
+ return {c.id for c in cps} | {old for c in cps for old in c.supersedes}
44
+
45
+ def open_ids(p: int) -> set[str]:
46
+ return {c.id for c in _positive(task, p) if not c.check(world, view)}
47
+
48
+ items: list[dict[str, Any]] = []
49
+ if phase > 0:
50
+ active, before = required(phase), required(phase - 1)
51
+ seen: dict[str, Any] = {}
52
+ for p in range(phase + 1):
53
+ for c in _positive(task, p):
54
+ seen.setdefault(c.id, c)
55
+ for c in seen.values():
56
+ items.append({"family": "scope", "key": c.id, "text": c.description,
57
+ "truth": c.id in active, "prev_truth": c.id in before})
58
+ for c in _positive(task, phase):
59
+ items.append({"family": "done", "key": c.id, "text": c.description, "truth": bool(c.check(world, view))})
60
+ now = needed_agents(task, phase, alive, open_ids(phase))
61
+ prev = needed_agents(task, phase - 1, alive, open_ids(phase - 1)) if phase > 0 else now
62
+ for a in alive:
63
+ items.append({"family": "team", "key": a["id"], "text": f"{a['id']} ({a['role']})",
64
+ "truth": a["id"] in now, "prev_truth": a["id"] in prev})
65
+ for i, it in enumerate(items, 1):
66
+ it["id"] = f"{it['family'][0].upper()}{i}"
67
+ return items
68
+
69
+
70
+ _HEADINGS = {
71
+ "scope": "Is each of these still part of the current goal? (1: still required. 0: dropped, or never asked for.)",
72
+ "done": "Is each of these already true in our systems right now?",
73
+ "team": "Does the team the current goal needs include this agent's role? Judge the role, not whether the "
74
+ "agent's own work is finished. (0: surplus, or no longer needed.)",
75
+ }
76
+
77
+
78
+ def probe_prompt(items: list[dict[str, Any]]) -> str:
79
+ parts = ["OUT-OF-RUN CHECK. This is not part of the work: nobody in the run sees your answer, it changes "
80
+ "nothing, and it costs no action. Answer from what you know right now.",
81
+ "Give a probability from 0 to 1 for each statement."]
82
+ for fam, head in _HEADINGS.items():
83
+ rows = [f" {it['id']}: {it['text']}" for it in items if it["family"] == fam]
84
+ if rows:
85
+ parts.append(head + "\n" + "\n".join(rows))
86
+ parts.append('Reply with only a JSON object mapping each id to a probability, like {"D1": 0.8, "T2": 1}.')
87
+ return "\n\n".join(parts)
88
+
89
+
90
+ def parse_probe(text: str, items: list[dict[str, Any]]) -> dict[str, float] | None:
91
+ m = _OBJ.search(text or "")
92
+ if not m:
93
+ return None
94
+ try:
95
+ raw = json.loads(m.group(0))
96
+ except json.JSONDecodeError:
97
+ return None
98
+ if not isinstance(raw, dict):
99
+ return None
100
+ ids = {it["id"] for it in items}
101
+ out = {}
102
+ for k, v in raw.items():
103
+ if k in ids and isinstance(v, (int, float)) and not isinstance(v, bool):
104
+ out[k] = min(1.0, max(0.0, float(v)))
105
+ return out or None
106
+
107
+
108
+ def _on_truth(it: dict[str, Any]) -> float:
109
+ return it["p"] if it["truth"] else 1 - it["p"]
110
+
111
+
112
+ def _mean(xs: list[float]) -> float | None:
113
+ return sum(xs) / len(xs) if xs else None
114
+
115
+
116
+ def score_probes(probes: list[dict[str, Any]]) -> dict[str, Any]:
117
+ """Probability on the truth (1 is perfect, .5 is a coin flip) and Brier score, per family; how fast beliefs
118
+ move to the truth for items a goal change flipped; and what the orchestrator believed when it finished."""
119
+ answered = [pr for pr in probes if pr.get("answered")]
120
+ items = [it for pr in answered for it in pr["items"] if it.get("p") is not None]
121
+ fams = {}
122
+ for fam in ("scope", "done", "team"):
123
+ xs = [it for it in items if it["family"] == fam]
124
+ fams[fam] = {"n": len(xs), "on_truth": _mean([_on_truth(it) for it in xs]),
125
+ "brier": _mean([(it["p"] - it["truth"]) ** 2 for it in xs])}
126
+ # beliefs about items a change flipped, probe by probe after the change
127
+ after: dict[int, list[float | None]] = {}
128
+ for pr in answered:
129
+ if pr["phase"] == 0:
130
+ continue
131
+ flipped = [it for it in pr["items"] if it.get("p") is not None and "prev_truth" in it
132
+ and it["truth"] != it["prev_truth"]]
133
+ after.setdefault(pr["phase"], []).append(_mean([_on_truth(it) for it in flipped]))
134
+ first = [s[0] for s in after.values() if s and s[0] is not None]
135
+ last = [s[-1] for s in after.values() if s and s[-1] is not None]
136
+ fin = next((pr for pr in reversed(answered) if pr["trigger"] == "finish"), None)
137
+ at_finish = None
138
+ if fin:
139
+ done = [it for it in fin["items"] if it["family"] == "done" and it.get("p") is not None]
140
+ false = [it for it in done if not it["truth"]]
141
+ at_finish = {"done_on_truth": _mean([_on_truth(it) for it in done]),
142
+ "overclaim": _mean([it["p"] for it in false]), "unmet": len(false)}
143
+ return {
144
+ "version": PROBE_VERSION, "probes": len(probes), "answered": len(answered),
145
+ "on_truth": _mean([_on_truth(it) for it in items]), "families": fams,
146
+ "after_change": {str(k): v for k, v in after.items()},
147
+ "update_first": _mean(first), "update_last": _mean(last), "at_finish": at_finish,
148
+ }
reorgbench/runtime/episode.py CHANGED
@@ -13,6 +13,8 @@ Pinned harness rules (changing any of them is a version bump):
13
  - ask_human is the orchestrator's too. The answer arrives at the start of its next turn and costs one
14
  action, like any other.
15
  - Malformed actions are logged as errors and treated as no-ops; retries belong to the policy.
 
 
16
  """
17
 
18
  from __future__ import annotations
@@ -26,6 +28,7 @@ from ..env.roles import ROLES, role_caps
26
  from ..env.tools import TOOLS, ToolArgError, call_tool, deliver_scheduled
27
  from ..env.world import AccessLog, World
28
  from ..human import HumanSimulator, KeywordMatcher, Matcher, answer_question
 
29
  from ..schema import Event
30
  from ..tasks.spec import EpisodeView, Intervention, Task
31
  from ..verify import Verdict, verify
@@ -68,6 +71,7 @@ class EpisodeResult:
68
  verdict: Verdict
69
  actions_used: int
70
  tokens_used: int
 
71
 
72
  def header(self) -> dict[str, Any]:
73
  return {
@@ -75,7 +79,7 @@ class EpisodeResult:
75
  "final_phase": self.phase, "agents": self.agents, "interventions": self.interventions,
76
  "success": self.verdict.success, "partial": self.verdict.partial, "checks": self.verdict.checks,
77
  "actions_used": self.actions_used, "tokens_used": self.tokens_used, "tokenizer": TOKENIZER_ID,
78
- "world_digest": self.world.digest(), "final_world": self.world.snapshot(),
79
  }
80
 
81
  @classmethod
@@ -84,15 +88,17 @@ class EpisodeResult:
84
  verdict = Verdict(header["final_phase"], header["checks"], header["success"], header["partial"])
85
  return cls(header["task_id"], header["stop_reason"], header["rounds"], header["final_phase"], events,
86
  World.from_snapshot(header["final_world"]), header["agents"], header["interventions"],
87
- verdict, header["actions_used"], header["tokens_used"])
88
 
89
 
90
  class Episode:
91
  def __init__(self, task: Task, factory: PolicyFactory, *, matcher: Matcher | None = None,
92
- questions: bool = True, _blank: bool = False):
93
  self.task, self.factory = task, factory
94
  self.matcher: Matcher = matcher or KeywordMatcher()
95
  self.questions = questions # False: the no-questions variant, where ask_human is refused
 
 
96
  self.world: World = task.world()
97
  self.human = HumanSimulator(task.interventions)
98
  self.events: list[Event] = []
@@ -181,6 +187,8 @@ class Episode:
181
  except Exception as e: # a crashing policy is the agent's failure, not the runtime's
182
  action = {"_policy_error": f"{type(e).__name__}: {e}"}
183
  self.submit(a, action)
 
 
184
  self.end_round()
185
 
186
  # The round broken into resumable pieces, so an outside caller (an RL trainer) can supply actions.
@@ -232,6 +240,11 @@ class Episode:
232
  a.end_round = self.round
233
  self._emit(None, "system", {"episode_end": self.stop_reason})
234
 
 
 
 
 
 
235
  def _fire_intervention(self, iv: Intervention, how: str) -> None:
236
  self.phase += 1
237
  content = {"intervention_id": iv.id, "change": iv.change, "text": iv.text}
@@ -242,6 +255,7 @@ class Episode:
242
  for oid, data in iv.world_effects.items():
243
  self.world.put(oid, data, log)
244
  self.fired[iv.id] = eid
 
245
  self._enqueue("orch", "intervention", content, eid)
246
  # the orchestrator acts first each round, so a change fired at round start is seen this round
247
  self.agents["orch"].queue[-1]["at"] = self.round
@@ -350,7 +364,8 @@ class Episode:
350
  if tgt not in self._descendants(a.id) or self.agents[tgt].status != "alive":
351
  return self._error(a, "permission", f"{tgt!r} is not a live descendant of {a.id}", act, usage)
352
  cascade = [tgt] + [d for d in self._descendants(tgt) if self.agents[d].status == "alive"]
353
- eid = self._emit(a, "kill", {"target": tgt, "cascade": cascade}, recipients=cascade, **usage)
 
354
  for d in cascade:
355
  s = self.agents[d]
356
  s.status, s.relay_round = "relaying", self.round + 1
@@ -384,6 +399,39 @@ class Episode:
384
  self._emit(a, "finish", {"answer": act.get("answer", ""), "intercepted": False}, **usage)
385
  self.stop_reason = "finished"
386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  # ---- results and snapshots -------------------------------------------------------------
388
 
389
  def view(self) -> EpisodeView:
@@ -394,7 +442,8 @@ class Episode:
394
  verdict = verify(self.task, self.world, view, self.phase, self.stop_reason == "finished")
395
  agents = [{k: v for k, v in asdict(self.agents[i]).items() if k not in ("queue", "book")} for i in self.order]
396
  return EpisodeResult(self.task.id, self.stop_reason or "running", self.round, self.phase, view.events,
397
- self.world, agents, list(self.human.log), verdict, self.actions_used, self.tokens_used)
 
398
 
399
  def snapshot(self) -> dict[str, Any]:
400
  """Full runtime state between rounds. Policies are not included; restore rebuilds them."""
@@ -403,14 +452,14 @@ class Episode:
403
  "world": self.world.snapshot(), "agents": {k: asdict(v) for k, v in self.agents.items()},
404
  "order": self.order, "human": self.human.state(), "actions_used": self.actions_used,
405
  "tokens_used": self.tokens_used, "stop_reason": self.stop_reason, "fired": self.fired,
406
- "agent_counter": self.agent_counter,
407
  })
408
 
409
  @classmethod
410
  def restore(cls, task: Task, snap: dict[str, Any], factory: PolicyFactory,
411
- matcher: Matcher | None = None, questions: bool = True) -> "Episode":
412
  snap = copy.deepcopy(snap)
413
- ep = cls(task, factory, matcher=matcher, questions=questions, _blank=True)
414
  ep.round, ep.phase = snap["round"], snap["phase"]
415
  ep.events = [Event(**d) for d in snap["events"]]
416
  ep.world = World.from_snapshot(snap["world"])
@@ -419,5 +468,6 @@ class Episode:
419
  ep.human.load(snap["human"])
420
  ep.actions_used, ep.tokens_used = snap["actions_used"], snap["tokens_used"]
421
  ep.stop_reason, ep.fired, ep.agent_counter = snap["stop_reason"], snap["fired"], snap["agent_counter"]
 
422
  ep.policies = {aid: factory(ep._info(a)) for aid, a in ep.agents.items() if a.status != "dead"}
423
  return ep
 
13
  - ask_human is the orchestrator's too. The answer arrives at the start of its next turn and costs one
14
  action, like any other.
15
  - Malformed actions are logged as errors and treated as no-ops; retries belong to the policy.
16
+ - Belief probes (optional, see probes.py) are asked on a copy of the orchestrator's conversation. They never
17
+ enter the run and cost no action, and their tokens aren't counted against the budget.
18
  """
19
 
20
  from __future__ import annotations
 
28
  from ..env.tools import TOOLS, ToolArgError, call_tool, deliver_scheduled
29
  from ..env.world import AccessLog, World
30
  from ..human import HumanSimulator, KeywordMatcher, Matcher, answer_question
31
+ from ..probes import PROBE_EVERY, build_items, parse_probe, probe_prompt
32
  from ..schema import Event
33
  from ..tasks.spec import EpisodeView, Intervention, Task
34
  from ..verify import Verdict, verify
 
71
  verdict: Verdict
72
  actions_used: int
73
  tokens_used: int
74
+ probes: list[dict[str, Any]] = field(default_factory=list)
75
 
76
  def header(self) -> dict[str, Any]:
77
  return {
 
79
  "final_phase": self.phase, "agents": self.agents, "interventions": self.interventions,
80
  "success": self.verdict.success, "partial": self.verdict.partial, "checks": self.verdict.checks,
81
  "actions_used": self.actions_used, "tokens_used": self.tokens_used, "tokenizer": TOKENIZER_ID,
82
+ "world_digest": self.world.digest(), "final_world": self.world.snapshot(), "probes": self.probes,
83
  }
84
 
85
  @classmethod
 
88
  verdict = Verdict(header["final_phase"], header["checks"], header["success"], header["partial"])
89
  return cls(header["task_id"], header["stop_reason"], header["rounds"], header["final_phase"], events,
90
  World.from_snapshot(header["final_world"]), header["agents"], header["interventions"],
91
+ verdict, header["actions_used"], header["tokens_used"], header.get("probes", []))
92
 
93
 
94
  class Episode:
95
  def __init__(self, task: Task, factory: PolicyFactory, *, matcher: Matcher | None = None,
96
+ questions: bool = True, probes: bool = False, _blank: bool = False):
97
  self.task, self.factory = task, factory
98
  self.matcher: Matcher = matcher or KeywordMatcher()
99
  self.questions = questions # False: the no-questions variant, where ask_human is refused
100
+ self.probing = probes
101
+ self.probes: list[dict[str, Any]] = []
102
  self.world: World = task.world()
103
  self.human = HumanSimulator(task.interventions)
104
  self.events: list[Event] = []
 
187
  except Exception as e: # a crashing policy is the agent's failure, not the runtime's
188
  action = {"_policy_error": f"{type(e).__name__}: {e}"}
189
  self.submit(a, action)
190
+ if a.id == "orch" and self.probing:
191
+ self._maybe_probe(obs)
192
  self.end_round()
193
 
194
  # The round broken into resumable pieces, so an outside caller (an RL trainer) can supply actions.
 
240
  a.end_round = self.round
241
  self._emit(None, "system", {"episode_end": self.stop_reason})
242
 
243
+ def _open_checks(self) -> list[str]:
244
+ """The current goal's unmet checkpoints; recorded at changes and kills so retirement can be judged."""
245
+ view = self.view()
246
+ return [c.id for c in self.task.phases[self.phase].checkpoints if not c.negative and not c.check(self.world, view)]
247
+
248
  def _fire_intervention(self, iv: Intervention, how: str) -> None:
249
  self.phase += 1
250
  content = {"intervention_id": iv.id, "change": iv.change, "text": iv.text}
 
255
  for oid, data in iv.world_effects.items():
256
  self.world.put(oid, data, log)
257
  self.fired[iv.id] = eid
258
+ self.events[eid].payload["open_checks"] = self._open_checks()
259
  self._enqueue("orch", "intervention", content, eid)
260
  # the orchestrator acts first each round, so a change fired at round start is seen this round
261
  self.agents["orch"].queue[-1]["at"] = self.round
 
364
  if tgt not in self._descendants(a.id) or self.agents[tgt].status != "alive":
365
  return self._error(a, "permission", f"{tgt!r} is not a live descendant of {a.id}", act, usage)
366
  cascade = [tgt] + [d for d in self._descendants(tgt) if self.agents[d].status == "alive"]
367
+ eid = self._emit(a, "kill", {"target": tgt, "cascade": cascade, "open_checks": self._open_checks()},
368
+ recipients=cascade, **usage)
369
  for d in cascade:
370
  s = self.agents[d]
371
  s.status, s.relay_round = "relaying", self.round + 1
 
399
  self._emit(a, "finish", {"answer": act.get("answer", ""), "intercepted": False}, **usage)
400
  self.stop_reason = "finished"
401
 
402
+ # ---- belief probes ---------------------------------------------------------------------
403
+
404
+ def _maybe_probe(self, obs: Observation) -> None:
405
+ orch = self.agents["orch"]
406
+ if any(q["kind"] == "intervention" for q in orch.queue):
407
+ return # a change it hasn't read yet would make the truth unfair
408
+ if self.stop_reason == "finished":
409
+ trigger = "finish"
410
+ elif any(it["kind"] == "intervention" for it in obs.items):
411
+ trigger = "change"
412
+ elif self.round % PROBE_EVERY == 0:
413
+ trigger = "periodic"
414
+ else:
415
+ return
416
+ ask = getattr(self.policies.get("orch"), "probe", None)
417
+ if ask is None:
418
+ return
419
+ alive = [{"id": x.id, "role": x.role, "spawn_round": x.spawn_round}
420
+ for x in self.agents.values() if x.id != "orch" and x.status == "alive"]
421
+ items = build_items(self.task, self.world, self.view(), self.phase, alive)
422
+ try:
423
+ out = ask(probe_prompt(items))
424
+ except InfraError:
425
+ raise
426
+ except Exception as e:
427
+ out = {"text": "", "error": f"{type(e).__name__}: {e}"}
428
+ answers = parse_probe(out.get("text", ""), items) or {}
429
+ for it in items:
430
+ it["p"] = answers.get(it["id"])
431
+ self.probes.append({"round": self.round, "phase": self.phase, "trigger": trigger, "items": items,
432
+ "answered": bool(answers), "tokens_in": out.get("tokens_in", 0),
433
+ "tokens_out": out.get("tokens_out", 0), **({"error": out["error"]} if "error" in out else {})})
434
+
435
  # ---- results and snapshots -------------------------------------------------------------
436
 
437
  def view(self) -> EpisodeView:
 
442
  verdict = verify(self.task, self.world, view, self.phase, self.stop_reason == "finished")
443
  agents = [{k: v for k, v in asdict(self.agents[i]).items() if k not in ("queue", "book")} for i in self.order]
444
  return EpisodeResult(self.task.id, self.stop_reason or "running", self.round, self.phase, view.events,
445
+ self.world, agents, list(self.human.log), verdict, self.actions_used, self.tokens_used,
446
+ copy.deepcopy(self.probes))
447
 
448
  def snapshot(self) -> dict[str, Any]:
449
  """Full runtime state between rounds. Policies are not included; restore rebuilds them."""
 
452
  "world": self.world.snapshot(), "agents": {k: asdict(v) for k, v in self.agents.items()},
453
  "order": self.order, "human": self.human.state(), "actions_used": self.actions_used,
454
  "tokens_used": self.tokens_used, "stop_reason": self.stop_reason, "fired": self.fired,
455
+ "agent_counter": self.agent_counter, "probes": self.probes,
456
  })
457
 
458
  @classmethod
459
  def restore(cls, task: Task, snap: dict[str, Any], factory: PolicyFactory,
460
+ matcher: Matcher | None = None, questions: bool = True, probes: bool = False) -> "Episode":
461
  snap = copy.deepcopy(snap)
462
+ ep = cls(task, factory, matcher=matcher, questions=questions, probes=probes, _blank=True)
463
  ep.round, ep.phase = snap["round"], snap["phase"]
464
  ep.events = [Event(**d) for d in snap["events"]]
465
  ep.world = World.from_snapshot(snap["world"])
 
468
  ep.human.load(snap["human"])
469
  ep.actions_used, ep.tokens_used = snap["actions_used"], snap["tokens_used"]
470
  ep.stop_reason, ep.fired, ep.agent_counter = snap["stop_reason"], snap["fired"], snap["agent_counter"]
471
+ ep.probes = snap.get("probes", [])
472
  ep.policies = {aid: factory(ep._info(a)) for aid, a in ep.agents.items() if a.status != "dead"}
473
  return ep
reorgbench/stats.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Uncertainty for benchmark numbers.
2
+
3
+ A score is the mean over tasks of each task's mean over runs. Its interval comes from a two-stage bootstrap:
4
+ resample tasks, then resample runs within each task, so both task choice and run-to-run noise count. Two
5
+ configurations are compared on the tasks they share, resampling the same tasks for both (a paired
6
+ difference), which is much tighter than two separate intervals. Seeds are fixed so reports reproduce.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import random
12
+ from typing import Any
13
+
14
+ B = 2000
15
+ LEVEL = 0.90
16
+
17
+
18
+ def _mean(xs: list[float]) -> float:
19
+ return sum(xs) / len(xs)
20
+
21
+
22
+ def _quantiles(xs: list[float], level: float) -> tuple[float, float]:
23
+ xs = sorted(xs)
24
+ lo = xs[int((1 - level) / 2 * (len(xs) - 1))]
25
+ hi = xs[int((1 + level) / 2 * (len(xs) - 1))]
26
+ return lo, hi
27
+
28
+
29
+ def _resampled_task_mean(rng: random.Random, runs: list[float]) -> float:
30
+ return _mean([runs[rng.randrange(len(runs))] for _ in runs])
31
+
32
+
33
+ def interval(by_task: dict[str, list[float]], *, b: int = B, level: float = LEVEL, seed: int = 0) -> dict[str, Any]:
34
+ """by_task: task -> per-run values (None values dropped). Mean over tasks with a two-stage bootstrap interval."""
35
+ data = {t: [float(x) for x in xs if x is not None] for t, xs in by_task.items()}
36
+ data = {t: xs for t, xs in data.items() if xs}
37
+ if not data:
38
+ return {"mean": None, "lo": None, "hi": None, "tasks": 0}
39
+ tasks = sorted(data)
40
+ rng = random.Random(seed)
41
+ boots = []
42
+ for _ in range(b):
43
+ pick = [tasks[rng.randrange(len(tasks))] for _ in tasks]
44
+ boots.append(_mean([_resampled_task_mean(rng, data[t]) for t in pick]))
45
+ lo, hi = _quantiles(boots, level)
46
+ return {"mean": _mean([_mean(data[t]) for t in tasks]), "lo": lo, "hi": hi, "tasks": len(tasks)}
47
+
48
+
49
+ def paired(a: dict[str, list[float]], b_: dict[str, list[float]], *, b: int = B, level: float = LEVEL,
50
+ seed: int = 0) -> dict[str, Any]:
51
+ """Difference a - b over the tasks both have, resampling the same tasks for both sides."""
52
+ a = {t: [float(x) for x in xs if x is not None] for t, xs in a.items()}
53
+ b_ = {t: [float(x) for x in xs if x is not None] for t, xs in b_.items()}
54
+ tasks = sorted(t for t in a if t in b_ and a[t] and b_[t])
55
+ if not tasks:
56
+ return {"diff": None, "lo": None, "hi": None, "tasks": 0}
57
+ per = {t: _mean(a[t]) - _mean(b_[t]) for t in tasks}
58
+ rng = random.Random(seed)
59
+ boots = []
60
+ for _ in range(b):
61
+ pick = [tasks[rng.randrange(len(tasks))] for _ in tasks]
62
+ boots.append(_mean([_resampled_task_mean(rng, a[t]) - _resampled_task_mean(rng, b_[t]) for t in pick]))
63
+ lo, hi = _quantiles(boots, level)
64
+ return {"diff": _mean(list(per.values())), "lo": lo, "hi": hi, "tasks": len(tasks),
65
+ "a_better": sum(v > 0 for v in per.values()), "b_better": sum(v < 0 for v in per.values()),
66
+ "per_task": per}
reorgbench/tasks/hand/t07_trial_cleanup.py CHANGED
@@ -102,9 +102,11 @@ TASK = Task(
102
  goal=GOAL0 + " " + RELAX,
103
  checkpoints=[
104
  Checkpoint("all_expired_archived", "all three expired trials archived, held one included",
105
- _archived(BASE_ARCHIVED + [HELD]), capability="analyst", realized_by=ARCHIVE_REALIZERS),
 
106
  Checkpoint("cleanup_listed_all", "doc lists all three archived trials",
107
- _doc_lists(BASE_ARCHIVED + [HELD]), realized_by=objs("docs/trial-cleanup")),
 
108
  ACTIVE_UNTOUCHED,
109
  ],
110
  staffings=STAFFINGS,
 
102
  goal=GOAL0 + " " + RELAX,
103
  checkpoints=[
104
  Checkpoint("all_expired_archived", "all three expired trials archived, held one included",
105
+ _archived(BASE_ARCHIVED + [HELD]), capability="analyst", realized_by=ARCHIVE_REALIZERS,
106
+ supersedes=["expired_archived"]),
107
  Checkpoint("cleanup_listed_all", "doc lists all three archived trials",
108
+ _doc_lists(BASE_ARCHIVED + [HELD]), realized_by=objs("docs/trial-cleanup"),
109
+ supersedes=["cleanup_listed"]),
110
  ACTIVE_UNTOUCHED,
111
  ],
112
  staffings=STAFFINGS,
reorgbench/tasks/spec.py CHANGED
@@ -43,6 +43,8 @@ class Checkpoint:
43
  negative: bool = False
44
  # object ids whose final versions realize this checkpoint; their last writers seed the causal graph
45
  realized_by: Callable[[World], list[str]] | None = None
 
 
46
 
47
 
48
  def objs(*oids: str) -> Callable[[World], list[str]]:
 
43
  negative: bool = False
44
  # object ids whose final versions realize this checkpoint; their last writers seed the causal graph
45
  realized_by: Callable[[World], list[str]] | None = None
46
+ # earlier checkpoints this one widens: they stay part of the goal inside it rather than being dropped
47
+ supersedes: list[str] = field(default_factory=list)
48
 
49
 
50
  def objs(*oids: str) -> Callable[[World], list[str]]:
tests/test_probes.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Belief probes and the statistics behind reported intervals."""
2
+
3
+ import json
4
+
5
+ from reorgbench.harness import FakeClient, LLMPolicy
6
+ from reorgbench.harness.policy import CallLog
7
+ from reorgbench.oracle import oracle_factory
8
+ from reorgbench.probes import PROBE_EVERY, parse_probe, probe_prompt, score_probes
9
+ from reorgbench.runtime import Episode
10
+ from reorgbench.runtime.policy import AgentInfo, Observation
11
+ from reorgbench.stats import interval, paired
12
+ from reorgbench.tasks.hand import HAND_TASKS
13
+
14
+ T5 = HAND_TASKS["hand-05-pdf-export"]
15
+
16
+
17
+ def probing(factory, answer):
18
+ """Wraps the orchestrator's policy with a probe() that answers by answer(items_by_id)."""
19
+ asked = []
20
+
21
+ def make(info):
22
+ inner = factory(info)
23
+ if info.role != "orchestrator":
24
+ return inner
25
+
26
+ class P:
27
+ def act(self, obs):
28
+ return inner.act(obs)
29
+
30
+ def probe(self, question):
31
+ asked.append(question)
32
+ ids = [line.split(":")[0].strip() for line in question.splitlines() if line.startswith(" ")]
33
+ return {"text": json.dumps({i: answer(i) for i in ids}), "tokens_in": 100, "tokens_out": 10}
34
+
35
+ return P()
36
+
37
+ return make, asked
38
+
39
+
40
+ def test_probes_run_outside_the_episode():
41
+ plain = Episode(T5, oracle_factory(T5)).run()
42
+ make, asked = probing(oracle_factory(T5), lambda i: 0.5)
43
+ res = Episode(T5, make, probes=True).run()
44
+ assert res.world.digest() == plain.world.digest() and len(res.events) == len(plain.events)
45
+ assert res.tokens_used == plain.tokens_used and res.actions_used == plain.actions_used
46
+ triggers = [p["trigger"] for p in res.probes]
47
+ assert triggers[-1] == "finish" and "change" in triggers
48
+ assert all(p["round"] % PROBE_EVERY == 0 for p in res.probes if p["trigger"] == "periodic")
49
+ assert len(asked) == len(res.probes) and all(p["answered"] for p in res.probes)
50
+
51
+
52
+ def test_probe_truth_follows_the_goal_change():
53
+ make, _ = probing(oracle_factory(T5), lambda i: 0.5)
54
+ res = Episode(T5, make, probes=True).run()
55
+ change = next(p for p in res.probes if p["trigger"] == "change")
56
+ scope = {it["key"]: it for it in change["items"] if it["family"] == "scope"}
57
+ assert scope["docuforge_po"]["truth"] is False and scope["docuforge_po"]["prev_truth"] is True
58
+ assert scope["pdf_on_render"]["truth"] is True and scope["pdf_on_render"]["prev_truth"] is False
59
+ assert not any(it["family"] == "scope" for p in res.probes if p["phase"] == 0 for it in p["items"])
60
+ fin = res.probes[-1]
61
+ assert all(it["truth"] for it in fin["items"] if it["family"] == "done") # the oracle finishes the job
62
+ # the prompt never shows the truth
63
+ assert "truth" not in probe_prompt(change["items"]) and "docuforge_po" not in probe_prompt(change["items"])
64
+
65
+
66
+ def test_probe_scores_reward_beliefs_on_the_truth():
67
+ probes = [{"phase": 1, "trigger": "change", "answered": True, "items": [
68
+ {"family": "scope", "truth": False, "prev_truth": True, "p": 0.9},
69
+ {"family": "done", "truth": True, "p": 1.0}]},
70
+ {"phase": 1, "trigger": "finish", "answered": True, "items": [
71
+ {"family": "scope", "truth": False, "prev_truth": True, "p": 0.1},
72
+ {"family": "done", "truth": False, "p": 0.8}]}]
73
+ s = score_probes(probes)
74
+ assert abs(s["update_first"] - 0.1) < 1e-9 and abs(s["update_last"] - 0.9) < 1e-9
75
+ assert abs(s["at_finish"]["overclaim"] - 0.8) < 1e-9 and s["at_finish"]["unmet"] == 1
76
+ assert abs(s["families"]["done"]["on_truth"] - 0.6) < 1e-9
77
+ assert score_probes([])["on_truth"] is None
78
+
79
+
80
+ def test_probe_answers_are_parsed_strictly():
81
+ items = [{"id": "D1"}, {"id": "T2"}]
82
+ assert parse_probe('ok {"D1": 1.4, "T2": -1, "X9": 0.5}', items) == {"D1": 1.0, "T2": 0.0}
83
+ assert parse_probe('{"D1": "high", "T2": true}', items) is None
84
+ assert parse_probe("no idea", items) is None
85
+
86
+
87
+ def test_llm_probe_leaves_the_conversation_alone(tmp_path):
88
+ client = FakeClient(lambda s, m: '{"type": "noop"}' if "OUT-OF-RUN" not in m[-1]["content"] else '{"D1": 0.3}')
89
+ log = CallLog(tmp_path / "c.jsonl")
90
+ pol = LLMPolicy(AgentInfo("orch", "orchestrator", None, 0, "", 0, [], T5.catalog), client, log,
91
+ round_cap=10, action_cap=10)
92
+ pol.act(Observation("orch", "orchestrator", 1, 0, [{"kind": "brief", "content": "GOAL: x", "event": None}]))
93
+ before = list(pol.history)
94
+ out = pol.probe("OUT-OF-RUN CHECK ...")
95
+ assert out["text"] == '{"D1": 0.3}' and pol.history == before
96
+ assert log.records[-1]["probe"] is True
97
+
98
+
99
+ def test_intervals_and_paired_differences():
100
+ flat = interval({"a": [1, 1], "b": [0, 0]})
101
+ assert flat["mean"] == 0.5 and flat["lo"] <= 0.5 <= flat["hi"]
102
+ assert interval({"a": [1, 1, 1], "b": [1, 1]})["lo"] == 1.0
103
+ d = paired({"a": [1, 1], "b": [1, 0], "c": [0]}, {"a": [0, 0], "b": [1, 0], "d": [1]})
104
+ assert d["tasks"] == 2 and d["diff"] == 0.5 and d["a_better"] == 1 and d["b_better"] == 0
105
+ assert interval({})["mean"] is None
106
+
107
+
108
+ def test_widened_work_stays_in_scope():
109
+ t7 = HAND_TASKS["hand-07-trial-cleanup"]
110
+ make, _ = probing(oracle_factory(t7), lambda i: 0.5)
111
+ res = Episode(t7, make, probes=True).run()
112
+ change = next(p for p in res.probes if p["trigger"] == "change")
113
+ scope = {it["key"]: it["truth"] for it in change["items"] if it["family"] == "scope"}
114
+ assert scope["expired_archived"] and scope["cleanup_listed"] and scope["all_expired_archived"]
115
+
116
+
117
+ def test_unfinished_carried_over_work_keeps_its_agent_needed():
118
+ from reorgbench.metrics.score import needed_agents
119
+ t2 = HAND_TASKS["hand-02-double-charge"]
120
+ team = [{"id": "a1", "role": "engineer", "spawn_round": 1}, {"id": "a2", "role": "finance", "spawn_round": 1},
121
+ {"id": "a3", "role": "support", "spawn_round": 2}, {"id": "a4", "role": "support", "spawn_round": 3}]
122
+ assert needed_agents(t2, 1, team) == {"a2"}
123
+ assert needed_agents(t2, 1, team, ["customer_replied", "purchase_order"]) == {"a2", "a3"}