HassamGani commited on
Commit
3d1499e
·
1 Parent(s): 0aa9d9e

Add the task generator: three scenario templates, 210 train tasks; staffing and retirement handle carried-over work

Browse files
README.md CHANGED
@@ -13,13 +13,14 @@ A benchmark for LLM orchestrators that hire, re-staff and retire a team of agent
13
 
14
  An orchestrator gets a task in a simulated company workspace and decides which specialists to hire from a role catalog. Each role can use only its own tools: code repo, database, support tickets, ledger, vendors and contracts, plus shared docs. Subagents can hire one more level of helpers. Agents only see each other through messages, and an orchestrator can inspect or shut down anyone below it. Midway through, a simulated human adds to, changes or cancels part of the goal, and the team has to adapt.
15
 
16
- > Status: early development (v0.1.0.dev0). In place: the environment, runtime, simulated human, verifier, scripted oracle, rule-based metrics and hand-written tasks, and a reference LLM harness. Not yet: the LLM-judge tier, the task generator and the leaderboard.
17
 
18
  ## Quick start
19
 
20
  ```bash
21
  uv sync
22
  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
@@ -56,11 +57,11 @@ These are computed from the trace with rules only. Messages they can't resolve a
56
  - vendor replies
57
  - value flow: an ID or amount that first entered an agent's context through some event, then shows up in that agent's later action
58
  - **Staffing:**
59
- - per-phase precision and recall against the acceptable teams;
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:**
@@ -97,12 +98,12 @@ ReOrgBench is one environment and one task generator, used both as a benchmark a
97
 
98
  | split | visibility | use |
99
  |---|---|---|
100
- | `train` | public | RL and other training (generated) |
101
  | `dev` | public | development and ablations; the hand-written tasks live here |
102
  | `test` | private | the leaderboard; generated from held-out scenario templates and secret seeds |
103
 
104
  - **Templates, not just seeds.** The test split holds out whole scenario templates, and some task shapes and change types. Splitting by template is what stops a model from scoring by memorizing templates. A small lite split, a stratified subset of test, is meant for cheap runs.
105
- - **Filtering.** `uv run reorgbench list --split dev` lists one split. Add `--tier hard` to list or run only the hard tier.
106
  - **Tiers.** Each split has a standard and a hard tier, with the same verifier rules. Hard tasks have three phases with compound changes, at least three roles across the episode, and budgets of 1.5× the oracle's rounds and actions (2.7–4× for standard tasks). A hard task's oracle makes the lookups a careful team can't skip, such as reading each ticket to see whose it is, so the budget isn't set by a plan that already knows the answers. They also plant traps that only the data resolves:
107
  - near-duplicate records;
108
  - a lapsed contract term or an expired quote;
@@ -132,6 +133,60 @@ Each episode writes a JSONL trace. The first line is a header with the outcome;
132
 
133
  Events record which world objects they read and wrote, and how many tokens each event added to which agent's context. See `reorgbench/schema.py`.
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  ## Tasks
136
 
137
  Ten hand-written tasks, all in `dev`:
 
13
 
14
  An orchestrator gets a task in a simulated company workspace and decides which specialists to hire from a role catalog. Each role can use only its own tools: code repo, database, support tickets, ledger, vendors and contracts, plus shared docs. Subagents can hire one more level of helpers. Agents only see each other through messages, and an orchestrator can inspect or shut down anyone below it. Midway through, a simulated human adds to, changes or cancels part of the goal, and the team has to adapt.
15
 
16
+ > Status: early development (v0.1.0.dev0). In place: the environment, runtime, simulated human, verifier, scripted oracle, rule-based metrics, hand-written tasks, the task generator and a reference LLM harness. Not yet: the LLM-judge tier and the leaderboard.
17
 
18
  ## Quick start
19
 
20
  ```bash
21
  uv sync
22
  uv run reorgbench list
23
+ uv run reorgbench show gen-region-migration-0002 # goal, changes, staffing references, budgets
24
  uv run reorgbench oracle hand-02-double-charge --trace runs/oracle-02.jsonl
25
  uv run reorgbench score runs/oracle-02.jsonl # add --json for every metric
26
  uv run pytest
 
57
  - vendor replies
58
  - value flow: an ID or amount that first entered an agent's context through some event, then shows up in that agent's later action
59
  - **Staffing:**
60
+ - per-phase precision and recall against the acceptable teams. An agent retired soon after a change isn't counted in the new phase's team; the grace window grows by a round for each retirement already made, and it never applies to an agent that stays on into the next phase. An agent retired once it finishes its own role's carried-over work isn't counted either;
61
  - promptness, the share of rounds in which the needed roles are present;
62
  - unnecessary hires.
63
  - **Retirement:**
64
+ - 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. Agents still finishing carried-over work count as needed: every agent of that role that writes that work after the change, and at least one. A kill also counts as correct if that work was finished by the time of the kill;
65
  - handoff recall: did a retired agent pass on planted facts others still needed.
66
  - **Work:** waste (contributing / all actions) × parsimony (reference length / contributing), per-agent usefulness, and specialist use.
67
  - **Communication:**
 
98
 
99
  | split | visibility | use |
100
  |---|---|---|
101
+ | `train` | public | RL and other training; 70 generated seeds of each public template |
102
  | `dev` | public | development and ablations; the hand-written tasks live here |
103
  | `test` | private | the leaderboard; generated from held-out scenario templates and secret seeds |
104
 
105
  - **Templates, not just seeds.** The test split holds out whole scenario templates, and some task shapes and change types. Splitting by template is what stops a model from scoring by memorizing templates. A small lite split, a stratified subset of test, is meant for cheap runs.
106
+ - **Filtering.** `uv run reorgbench list --split dev` lists one split. Add `--tier hard` to list or run only the hard tier, `--template` for one scenario template, and `--limit` to cap the count.
107
  - **Tiers.** Each split has a standard and a hard tier, with the same verifier rules. Hard tasks have three phases with compound changes, at least three roles across the episode, and budgets of 1.5× the oracle's rounds and actions (2.7–4× for standard tasks). A hard task's oracle makes the lookups a careful team can't skip, such as reading each ticket to see whose it is, so the budget isn't set by a plan that already knows the answers. They also plant traps that only the data resolves:
108
  - near-duplicate records;
109
  - a lapsed contract term or an expired quote;
 
133
 
134
  Events record which world objects they read and wrote, and how many tokens each event added to which agent's context. See `reorgbench/schema.py`.
135
 
136
+ ## Generated tasks
137
+
138
+ `reorgbench.gen` builds tasks from scenario templates, τ²-Bench style: a goal is composed from units of work, each tied to one role, and each unit carries its own oracle steps, check and mutants. A unit is one of the following:
139
+
140
+ - updating a field on customer records;
141
+ - replying on each customer's ticket with a per-customer figure or a vendor's reference code;
142
+ - a credit or refund;
143
+ - a code change that has to pass CI;
144
+ - asking a vendor for a reference;
145
+ - closing tickets.
146
+
147
+ A seed fixes the world: customers, ids, seat counts, rates and traps. It also fixes the knobs.
148
+
149
+ Goal changes rewrite the units:
150
+
151
+ - **CANCEL** takes a subset out of scope, so work already done for it has to be undone and those customers told to disregard;
152
+ - **MODIFY** changes a figure, so customers already told get a correction and refunds are topped up;
153
+ - **ADD** adds a unit.
154
+
155
+ From the units, the generator derives per phase:
156
+
157
+ - the oracle plan;
158
+ - the checkpoints, including negative checks for out-of-scope records and for work landing after a cancel;
159
+ - the staffing references;
160
+ - the planted facts and human facts.
161
+
162
+ **References by construction.** References come from the plan, never from a model run.
163
+
164
+ - **Budgets.** Budgets are 1.5× (hard) or 3× (standard) the rounds and actions of the fastest careful oracle. "Careful" means each new hire looks up what it needs.
165
+ - **Staffing.** Every crew size the oracle can finish within those budgets is an acceptable staffing.
166
+ - **Triggers.** The first change fires on a record a third of the way through the work. The second fires on progress partway through the work the first change set off, chosen from a run with the second change held back. Fallback rounds come from the same run.
167
+ - **Gate.** The task is kept only if the oracle passes every check, every change fires on its trigger, and the oracle hits no tool errors.
168
+
169
+ **Templates.** Three public templates feed `train`:
170
+
171
+ | template | the job | changes |
172
+ |---|---|---|
173
+ | `plan-retirement` | move customers off a retiring plan; tell each their new monthly price; optionally reprice in code | CANCEL (annual billing), MODIFY (price), ADD (credit, close) |
174
+ | `overcharge-refund` | refund a rate-card overcharge in total, counting earlier partial refunds; fix the records; tell each the total | MODIFY (top-ups), ADD (credit, close) |
175
+ | `region-migration` | move customers to a new region; quote the hosting provider's maintenance-window reference; avoid the look-alike vendor | CANCEL (Enterprise), MODIFY (window moves), ADD (credit, close) |
176
+
177
+ The test split is generated from templates registered at run time with `register_template`, outside this repo, so whole scenarios are held out.
178
+
179
+ **Knobs.** Each seed samples these knobs, and every task is tagged with them so results can be broken down:
180
+
181
+ - customers in scope (4–32);
182
+ - most agents per per-customer role;
183
+ - the changes and their order;
184
+ - traps: closed accounts, already-moved namesakes, look-alike plans or vendors, earlier partial refunds;
185
+ - whether there's a code change;
186
+ - the target tier.
187
+
188
+ A task is hard only if it has three phases, three roles and at least eight final checks; otherwise it gets standard budgets.
189
+
190
  ## Tasks
191
 
192
  Ten hand-written tasks, all in `dev`:
reorgbench/cli.py CHANGED
@@ -54,12 +54,23 @@ def _by_task(out: Path, key: str) -> dict[str, list]:
54
  return by
55
 
56
 
 
 
 
 
 
 
 
57
  def main(argv: list[str] | None = None) -> int:
58
  ap = argparse.ArgumentParser(prog="reorgbench")
59
  sub = ap.add_subparsers(dest="cmd", required=True)
60
  ls = sub.add_parser("list", help="list tasks")
61
  ls.add_argument("--split", choices=["train", "dev", "test"])
62
  ls.add_argument("--tier", choices=["standard", "hard"])
 
 
 
 
63
  o = sub.add_parser("oracle", help="run the scripted oracle on a task")
64
  o.add_argument("task")
65
  o.add_argument("--trace", type=Path, help="write the trace here")
@@ -71,6 +82,8 @@ def main(argv: list[str] | None = None) -> int:
71
  group.add_argument("--split", choices=["train", "dev", "test"])
72
  group.add_argument("--task", action="append", help="task id; repeat for several")
73
  rn.add_argument("--tier", choices=["standard", "hard"], help="with --split, only tasks of this tier")
 
 
74
  rn.add_argument("--matcher", default=None,
75
  help="model that matches questions to the person's pre-written answers, or 'keyword' "
76
  "(default: the pinned matcher model)")
@@ -89,15 +102,31 @@ def main(argv: list[str] | None = None) -> int:
89
  args = ap.parse_args(argv)
90
 
91
  if args.cmd == "list":
92
- for tid, t in get_tasks(args.split, args.tier).items():
93
  print(f"{tid}\t{t.split}\t{t.tier}\t{len(t.phases)} phase(s)\t{t.title}")
94
  return 0
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  if args.cmd == "run":
97
  from .harness import MATCHER_MODEL, CallLog, LLMMatcher, make_client, run_tasks
98
  from .human import KeywordMatcher
99
 
100
- tasks = list(get_tasks(args.split, args.tier).values()) if args.split else [get_task(t) for t in args.task]
101
  if any(t is None for t in tasks):
102
  print("unknown task in --task", file=sys.stderr)
103
  return 2
 
54
  return by
55
 
56
 
57
+ def _select(args) -> dict:
58
+ tasks = get_tasks(args.split, args.tier)
59
+ if args.template:
60
+ tasks = {k: t for k, t in tasks.items() if t.template == args.template}
61
+ return dict(list(tasks.items())[:args.limit]) if args.limit else tasks
62
+
63
+
64
  def main(argv: list[str] | None = None) -> int:
65
  ap = argparse.ArgumentParser(prog="reorgbench")
66
  sub = ap.add_subparsers(dest="cmd", required=True)
67
  ls = sub.add_parser("list", help="list tasks")
68
  ls.add_argument("--split", choices=["train", "dev", "test"])
69
  ls.add_argument("--tier", choices=["standard", "hard"])
70
+ ls.add_argument("--template", help="only tasks from this scenario template ('hand' for hand-written)")
71
+ ls.add_argument("--limit", type=int, help="at most this many tasks")
72
+ sh = sub.add_parser("show", help="print a task's goal, changes, staffing references and budgets")
73
+ sh.add_argument("task")
74
  o = sub.add_parser("oracle", help="run the scripted oracle on a task")
75
  o.add_argument("task")
76
  o.add_argument("--trace", type=Path, help="write the trace here")
 
82
  group.add_argument("--split", choices=["train", "dev", "test"])
83
  group.add_argument("--task", action="append", help="task id; repeat for several")
84
  rn.add_argument("--tier", choices=["standard", "hard"], help="with --split, only tasks of this tier")
85
+ rn.add_argument("--template", help="with --split, only tasks from this scenario template")
86
+ rn.add_argument("--limit", type=int, help="with --split, at most this many tasks")
87
  rn.add_argument("--matcher", default=None,
88
  help="model that matches questions to the person's pre-written answers, or 'keyword' "
89
  "(default: the pinned matcher model)")
 
102
  args = ap.parse_args(argv)
103
 
104
  if args.cmd == "list":
105
+ for tid, t in _select(args).items():
106
  print(f"{tid}\t{t.split}\t{t.tier}\t{len(t.phases)} phase(s)\t{t.title}")
107
  return 0
108
 
109
+ if args.cmd == "show":
110
+ t = get_task(args.task)
111
+ if t is None:
112
+ print(f"unknown task {args.task}", file=sys.stderr)
113
+ return 2
114
+ print(f"{t.id} ({t.template}, {t.split}, {t.tier}) budgets: {t.budgets.round_cap} rounds, "
115
+ f"{t.budgets.action_cap} actions\n{t.title}\n")
116
+ for k, p in enumerate(t.phases):
117
+ iv = t.interventions[k - 1] if k else None
118
+ print(f"phase {k}" + (f" [{iv.change}, fires on {iv.trigger.kind} {iv.trigger.params}, fallback round "
119
+ f"{iv.fallback_round}]" if iv else ""))
120
+ print(" " + (iv.text if iv else p.goal))
121
+ print(f" staffing: {' | '.join(', '.join(s) or 'nobody' for s in p.staffings)}")
122
+ print(f" checks: {', '.join(c.id for c in p.checkpoints)}\n")
123
+ return 0
124
+
125
  if args.cmd == "run":
126
  from .harness import MATCHER_MODEL, CallLog, LLMMatcher, make_client, run_tasks
127
  from .human import KeywordMatcher
128
 
129
+ tasks = list(_select(args).values()) if args.split else [get_task(t) for t in args.task]
130
  if any(t is None for t in tasks):
131
  print("unknown task in --task", file=sys.stderr)
132
  return 2
reorgbench/gen/__init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task generator. generate(template, seed) builds a task from a scenario template, its references included, and
2
+ keeps it only if the careful oracle solves it; budgets and fallback rounds come from that oracle run.
3
+
4
+ The public train split is PUBLIC_SEEDS seeds of each public template. The private test split comes from templates
5
+ registered outside this repo and secret seeds.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import random
11
+ from dataclasses import replace
12
+ from functools import lru_cache
13
+
14
+ from ..tasks.spec import Task
15
+ from .build import GenerationError, Knobs, build, calibrate
16
+ from .templates import TEMPLATES, Template, register_template
17
+
18
+ PUBLIC_SEEDS = 70
19
+ MAX_ATTEMPTS = 6
20
+
21
+
22
+ def generate(template: str | Template, seed: int, knobs: Knobs | None = None) -> Task:
23
+ """Build the task for (template, seed). The knobs' crew is the most agents per per-customer role the careful
24
+ oracle may use: each crew size up to it is planned, the fastest sets the budgets, and every size that also
25
+ finishes within those budgets is an acceptable staffing."""
26
+ t = TEMPLATES[template] if isinstance(template, str) else template
27
+ k = knobs or t.sample(random.Random(f"{t.id}:{seed}:knobs"))
28
+ why = None
29
+ for attempt in range(MAX_ATTEMPTS):
30
+ variants = []
31
+ for crew in range(1, k.crew + 1): # a crew size the oracle can't solve is left out, not fatal
32
+ kc = replace(k, crew=crew)
33
+ task, _ = build(t, seed, kc, attempt)
34
+ why, res = calibrate(task, kc)
35
+ if why is None:
36
+ variants.append((res.rounds, crew, task, res))
37
+ if not variants:
38
+ continue
39
+ variants.sort(key=lambda v: (v[0], v[1]))
40
+ _, crew, task, _ = variants[0]
41
+ for _, c, other, res in variants[1:]:
42
+ if res.rounds <= task.budgets.round_cap and res.actions_used <= task.budgets.action_cap:
43
+ for p, q in zip(task.phases, other.phases):
44
+ p.staffings += [s for s in q.staffings if s not in p.staffings]
45
+ task.tags = [x for x in task.tags if not x.startswith("crew")] + [f"crew{crew}", f"crew-max{k.crew}"]
46
+ return task
47
+ raise GenerationError(f"{t.id} seed {seed}: no solvable instance in {MAX_ATTEMPTS} attempts ({why})")
48
+
49
+
50
+ @lru_cache(maxsize=None)
51
+ def generated_tasks(split: str = "train", seeds: int = PUBLIC_SEEDS) -> dict[str, Task]:
52
+ out = {}
53
+ for t in TEMPLATES.values():
54
+ if t.split != split:
55
+ continue
56
+ for s in range(seeds):
57
+ task = generate(t, s)
58
+ out[task.id] = task
59
+ return out
60
+
61
+
62
+ __all__ = ["generate", "generated_tasks", "Knobs", "TEMPLATES", "Template", "register_template", "GenerationError"]
reorgbench/gen/build.py ADDED
@@ -0,0 +1,714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turns a template's world and units into a Task: phase plans for the oracle, checkpoints, staffing references,
2
+ goal changes with their triggers, and verifier mutants. Budgets and fallback rounds are then set from a run of the
3
+ careful oracle, which also gates the task: anything it can't solve is not emitted."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import copy
8
+ import math
9
+ import random
10
+ import re
11
+ from collections import Counter
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Callable
14
+
15
+ from ..oracle import oracle_factory, role_of_label
16
+ from ..runtime import Episode
17
+ from ..tasks.hand.common import (
18
+ ALL_ROLES, CI, SIGNOFF, all_unchanged, base_objects, drop_entries, post_entry, reply_events, set_replies, stamp,
19
+ )
20
+ from ..tasks.spec import (
21
+ Budgets, Checkpoint, EpisodeView, HumanFact, Intervention, Mutant, OraclePhase, Phase, PlantedFact, Step, Task,
22
+ Trigger,
23
+ )
24
+ from .units import (
25
+ Ask, Close, Code, Credit, Move, Notify, Refund, Unit, credits_by, current_says, is_retraction, refunds_on, replies,
26
+ rerun_tests, told_and_not_retracted,
27
+ )
28
+ from .world import Acct, Ids
29
+
30
+ # hire consumers of facts before their providers, so a provider's brief already names who to send to
31
+ HIRE_ORDER = ["support", "finance", "engineer", "procurement", "analyst"]
32
+ LOOSE = Budgets(round_cap=400, action_cap=4000)
33
+ LIST_ROWS = "db.query"
34
+ HARD_BUDGET, STANDARD_BUDGET = 1.5, 3.0
35
+ TOKENS_PER_ACTION = 12_000
36
+
37
+
38
+ class GenerationError(RuntimeError):
39
+ pass
40
+
41
+
42
+ @dataclass
43
+ class Knobs:
44
+ """Difficulty knobs. Results can be broken down by any of them."""
45
+ n: int = 8 # customers in scope (volume)
46
+ crew: int = 1 # agents per per-customer role in the oracle's plan
47
+ changes: tuple[str, ...] = () # goal changes in order: CANCEL, MODIFY, ADD:credit, ADD:close
48
+ traps: int = 2 # records that look in scope but aren't
49
+ code: bool = True # add a code change (one more role)
50
+ budget: float = 3.0 # rounds and actions allowed, as a multiple of the careful oracle's (1.5
51
+ # makes a task hard if its structure qualifies; otherwise it gets 3.0)
52
+
53
+ def tags(self) -> list[str]:
54
+ return [f"n{self.n}", f"crew{self.crew}", f"changes{len(self.changes)}", f"traps{self.traps}",
55
+ *(c.lower().replace(":", "-") for c in self.changes), *(["code"] if self.code else [])]
56
+
57
+
58
+ @dataclass
59
+ class Gen:
60
+ """Everything a template sets up, plus the state the phase builder threads through the changes."""
61
+ template: Any
62
+ seed: int
63
+ knobs: Knobs
64
+ rng: random.Random
65
+ ids: Ids
66
+ objects: dict[str, dict[str, Any]] = field(default_factory=base_objects)
67
+ accts: dict[str, Acct] = field(default_factory=dict)
68
+ cohort: list[str] = field(default_factory=list) # in scope at the start
69
+ excluded: list[str] = field(default_factory=list) # taken out of scope by a CANCEL
70
+ exclude_where: dict[str, Any] = field(default_factory=dict) # what a careful team queries to find them
71
+ leave_alone: list[str] = field(default_factory=list)
72
+ units: dict[str, Unit] = field(default_factory=dict)
73
+ ledger_initial: set[str] = field(default_factory=set)
74
+ wrong_vendor: str | None = None
75
+ story: dict[str, Any] = field(default_factory=dict) # the template's sampled names and numbers
76
+ # threaded through the phases
77
+ chunks: list[list[str]] = field(default_factory=list)
78
+ alive: list[str] = field(default_factory=list)
79
+ in_scope: list[str] = field(default_factory=list)
80
+ trigger_index: int = 0 # which in-scope customer of the lead share the first change fires on
81
+
82
+ def add_account(self, row: dict[str, Any], **kw: Any) -> Acct:
83
+ a = Acct(self.ids.customer(), dict(row), **kw)
84
+ self.accts[a.cid] = a
85
+ return a
86
+
87
+ def row_index(self, cid: str) -> int:
88
+ return [o for o in self.objects if o.startswith("db.customers/")].index(f"db.customers/{cid}")
89
+
90
+ def index(self, cid: str) -> int:
91
+ return self.cohort.index(cid)
92
+
93
+ def labels(self, role: str) -> list[str]:
94
+ volume = role in ("support", "finance") or (role == "analyst" and "moved" in self.units)
95
+ return [role] + ([f"{role}#{j}" for j in range(2, self.knobs.crew + 1)] if volume else [])
96
+
97
+ def chunk(self, label: str) -> list[str]:
98
+ j = 0 if "#" not in label else int(label.split("#")[1]) - 1
99
+ return self.chunks[j] if j < len(self.chunks) else []
100
+
101
+
102
+ def _list(provides: dict[str, Any] | None = None) -> Step:
103
+ return Step(LIST_ROWS, {"table": "customers"}, provides=dict(provides or {}))
104
+
105
+
106
+ # ---- the oracle's plan, phase by phase --------------------------------------------------------------------
107
+
108
+ class PhaseBuilder:
109
+ def __init__(self, g: Gen):
110
+ self.g, self.t = g, g.template
111
+ self.needs: dict[str, Any] = {}
112
+ self.steps: dict[str, list[Step]] = {}
113
+ self.hires: list[str] = []
114
+ self.drop: list[str] = []
115
+
116
+ def need_seats(self, name: str, cid: str, times: float, plus: float = 0.0) -> str:
117
+ """A per-customer amount the analyst's lookup provides: seats x rate (+ plus)."""
118
+ self.needs[name] = {"path": f"rows.{self.g.row_index(cid)}.seats", "times": times, "plus": plus}
119
+ return "{" + name + "}"
120
+
121
+ def need_field(self, name: str, cid: str, fld: str) -> str:
122
+ self.needs[name] = f"rows.{self.g.row_index(cid)}.{fld}"
123
+ return "{" + name + "}"
124
+
125
+ def work(self, label: str, steps: list[Step]) -> None:
126
+ """Give a label work this phase, hiring it if it isn't on the team."""
127
+ if label not in self.g.alive and label not in self.hires:
128
+ self.hires.append(label)
129
+ steps = self.first_steps(label) + steps
130
+ self.steps.setdefault(label, []).extend(steps)
131
+
132
+ @staticmethod
133
+ def first_steps(label: str) -> list[Step]:
134
+ """What a careful new hire looks up before acting."""
135
+ role = role_of_label(label)
136
+ if role == "support":
137
+ return [Step("tickets.list", {"status": "open"})]
138
+ if role == "analyst":
139
+ return [_list()]
140
+ return []
141
+
142
+ def tells(self, label: str, value_of: Callable[[str], str], correction: bool = False) -> list[Step]:
143
+ g = self.g
144
+ text = self.t.correct_text if correction else self.t.tell_text
145
+ return [Step("tickets.reply", {"ticket_id": g.accts[c].ticket, "text": text(g, c, value_of(c))}, tag=f"tell:{c}")
146
+ for c in g.chunk(label) if c in g.in_scope]
147
+
148
+ def notify_value(self, n: Notify) -> Callable[[str], str]:
149
+ if n.rate is None:
150
+ return lambda c: "{ref%d}" % n.ver
151
+ return lambda c: self.need_seats(f"n{n.ver}_{self.g.index(c)}", c, n.rate)
152
+
153
+ def refunds(self, label: str, r: Refund, topup: bool) -> list[Step]:
154
+ g, out = self.g, []
155
+ for c in g.chunk(label):
156
+ if c not in g.in_scope:
157
+ continue
158
+ i, a = g.index(c), g.accts[c]
159
+ inv = self.need_field(f"inv_{i}", c, "last_invoice")
160
+ full = self.need_seats(f"rf{r.ver}_{i}", c, r.rate, -a.prior_refund)
161
+ if not topup:
162
+ out += [Step("ledger.list_charges", {"invoice_id": inv}),
163
+ Step("ledger.refund", {"invoice_id": inv, "amount": full}, tag=f"refund:{c}")]
164
+ else:
165
+ extra = self.need_seats(f"rt{r.ver}_{i}", c, r.rate - r.olds[-1])
166
+ out += [Step("ledger.list_charges", {"invoice_id": inv}, unless_done=f"refund:{c}"),
167
+ Step("ledger.refund", {"invoice_id": inv, "amount": full}, unless_done=f"refund:{c}"),
168
+ Step("ledger.refund", {"invoice_id": inv, "amount": extra}, if_done=f"refund:{c}")]
169
+ return out
170
+
171
+ def credits(self, label: str, cr: Credit) -> list[Step]:
172
+ g = self.g
173
+ return [Step("ledger.credit", {"customer_id": self.need_field(f"cid_{g.index(c)}", c, "row_id"),
174
+ "amount": self.need_seats(f"cr{cr.ver}_{g.index(c)}", c, cr.rate),
175
+ "note": self.t.credit_note},
176
+ tag=f"credit:{c}") for c in g.chunk(label) if c in g.in_scope]
177
+
178
+ def closes(self, label: str) -> list[Step]:
179
+ g = self.g
180
+ return [Step("tickets.close", {"ticket_id": g.accts[c].ticket}, tag=f"close:{c}")
181
+ for c in g.chunk(label) if c in g.in_scope]
182
+
183
+ def finish(self) -> tuple[OraclePhase, list[list[str]]]:
184
+ g = self.g
185
+ if self.needs:
186
+ if "analyst" not in self.steps:
187
+ self.work("analyst", [])
188
+ st = self.steps["analyst"]
189
+ if st and st[0].tool == LIST_ROWS and not st[0].args.get("where") and not st[0].provides:
190
+ st[0] = _list(self.needs)
191
+ else:
192
+ st.insert(0, _list(self.needs))
193
+ order = {r: i for i, r in enumerate(HIRE_ORDER)}
194
+ self.hires.sort(key=lambda l: (order[role_of_label(l)], l))
195
+ retire = [l for l in g.alive if l not in self.steps]
196
+ g.alive = [l for l in g.alive if l in self.steps] + self.hires
197
+ staffing = sorted(role_of_label(l) for l in self.steps)
198
+ return OraclePhase(hires=self.hires, retire=retire, steps=self.steps, drop=self.drop), [staffing]
199
+
200
+
201
+ def plan_start(g: Gen) -> tuple[OraclePhase, list[list[str]]]:
202
+ b, u = PhaseBuilder(g), g.units
203
+ if "moved" in u:
204
+ for l in g.labels("analyst"):
205
+ b.work(l, [u["moved"].step(c) for c in g.chunk(l)])
206
+ if "window" in u:
207
+ b.work("procurement", u["window"].steps("ref0"))
208
+ for l in g.labels("support"):
209
+ b.work(l, b.tells(l, b.notify_value(u["told"])))
210
+ if "refunded" in u:
211
+ for l in g.labels("finance"):
212
+ b.work(l, b.refunds(l, u["refunded"], topup=False))
213
+ if "code" in u:
214
+ b.work("engineer", u["code"].steps())
215
+ return b.finish()
216
+
217
+
218
+ def plan_change(g: Gen, kind: str, changed: list[str]) -> tuple[OraclePhase, list[list[str]]]:
219
+ b, u = PhaseBuilder(g), g.units
220
+ if kind == "CANCEL":
221
+ x = set(g.excluded)
222
+ g.in_scope = [c for c in g.in_scope if c not in x]
223
+ for key in ("moved", "told", "closed"):
224
+ if key in u:
225
+ u[key].ver += 1
226
+ b.drop += [f"move:{c}" for c in g.excluded] + [f"tell:{c}" for c in g.excluded] + \
227
+ [f"close:{c}" for c in g.excluded]
228
+ if "moved" in u:
229
+ m: Move = u["moved"]
230
+ for j, l in enumerate(g.labels("analyst")):
231
+ look = [Step(LIST_ROWS, {"table": "customers", "where": g.exclude_where})] if j == 0 else []
232
+ b.work(l, look + [m.revert(c, g.accts[c].row[m.field_name]) for c in g.chunk(l) if c in x])
233
+ for l in g.labels("support"):
234
+ b.work(l, [Step("tickets.reply", {"ticket_id": g.accts[c].ticket, "text": g.template.retract_text(g, c)},
235
+ if_done=f"tell:{c}") for c in g.chunk(l) if c in x])
236
+ elif kind == "MODIFY":
237
+ if "told" in changed:
238
+ n: Notify = u["told"]
239
+ b.drop.append("tell:")
240
+ if n.rate is None:
241
+ b.work("procurement", u["window"].steps(f"ref{n.ver}"))
242
+ for l in g.labels("support"):
243
+ b.work(l, b.tells(l, b.notify_value(n), correction=True))
244
+ if "refunded" in changed:
245
+ b.drop.append("refund:")
246
+ for l in g.labels("finance"):
247
+ b.work(l, b.refunds(l, u["refunded"], topup=True))
248
+ if "code" in changed:
249
+ b.work("engineer", u["code"].steps())
250
+ elif kind == "ADD:credit":
251
+ for l in g.labels("finance"):
252
+ b.work(l, b.credits(l, u["credited"]))
253
+ elif kind == "ADD:close":
254
+ for l in g.labels("support"):
255
+ b.work(l, b.closes(l))
256
+ else:
257
+ raise GenerationError(f"unknown change {kind}")
258
+ return b.finish()
259
+
260
+
261
+ # ---- checkpoints ----------------------------------------------------------------------------------------
262
+
263
+ def _fired_round(v: EpisodeView, iv: str | None) -> int | None:
264
+ eid = v.fired_event(iv) if iv else None
265
+ return None if eid is None else next(e["round"] for e in v.events if e["id"] == eid)
266
+
267
+
268
+ def checkpoints(g: Gen, cancel_id: str | None, modify_id: str | None) -> list[Checkpoint]:
269
+ u, scope, acc = copy.deepcopy(g.units), list(g.in_scope), g.accts # later changes mutate g.units
270
+ out: list[Checkpoint] = []
271
+ if "moved" in u:
272
+ m: Move = u["moved"]
273
+ out.append(Checkpoint(m.ck, f"{m.field_name} set to {m.target} on every customer in scope, nothing else in "
274
+ "their records changed",
275
+ lambda w, v: all(m.row_ok(w, c, acc[c].row, m.target) for c in scope),
276
+ capability="analyst", realized_by=lambda w: [f"db.customers/{c}" for c in scope]))
277
+ if "window" in u:
278
+ a: Ask = u["window"]
279
+
280
+ def asked(w, v):
281
+ mails = [o for o, d in w.iter("outbox") if d["vendor_id"] == a.vendor]
282
+ if a.ver == 0:
283
+ return bool(mails)
284
+ fe = v.fired_event(modify_id)
285
+ return fe is not None and any((w.objects[o]["written_by"] or -1) > fe for o in mails)
286
+ out.append(Checkpoint(a.ck, "the vendor asked for the reference" + (" again after the change" if a.ver else ""),
287
+ asked, capability="procurement",
288
+ realized_by=lambda w: [o for o, d in w.iter("outbox") if d["vendor_id"] == a.vendor]))
289
+ n: Notify = u["told"]
290
+ out.append(Checkpoint(n.ck, "each customer in scope told on their ticket, with the current figure",
291
+ lambda w, v: all(current_says(replies(w, acc[c].ticket), n.value(acc[c].seats),
292
+ n.old_values(acc[c].seats)) for c in scope),
293
+ capability="support", realized_by=lambda w: [f"tickets/{acc[c].ticket}" for c in scope]))
294
+ if "refunded" in u:
295
+ r: Refund = u["refunded"]
296
+ out.append(Checkpoint(r.ck, "each in-scope invoice refunded the overcharge in total, to the cent",
297
+ lambda w, v: all(abs(refunds_on(w).get(acc[c].invoice, 0) - acc[c].seats * r.rate)
298
+ < 0.005 for c in scope),
299
+ capability="finance", realized_by=lambda w: _new_entries(g, scope, w, "refund")))
300
+ if "credited" in u:
301
+ cr: Credit = u["credited"]
302
+ out.append(Checkpoint(cr.ck, "each customer in scope credited the per-seat amount in total",
303
+ lambda w, v: all(abs(credits_by(w).get(c, 0) - acc[c].seats * cr.rate) < 0.005
304
+ for c in scope),
305
+ capability="finance", realized_by=lambda w: _new_entries(g, scope, w, "credit")))
306
+ if "closed" in u:
307
+ cl: Close = u["closed"]
308
+ out.append(Checkpoint(cl.ck, "each in-scope customer's ticket closed",
309
+ lambda w, v: all((w.data(f"tickets/{acc[c].ticket}") or {}).get("status") == "closed"
310
+ for c in scope),
311
+ capability="support", realized_by=lambda w: [f"tickets/{acc[c].ticket}" for c in scope]))
312
+ if "code" in u:
313
+ cd: Code = u["code"]
314
+ out.append(Checkpoint(cd.ck, f"{cd.path} changed as asked, with CI passing after the last edit",
315
+ lambda w, v: cd.ok(w), capability="engineer",
316
+ realized_by=lambda w: [f"repo/{cd.path}", "repo.ci/latest"]))
317
+ return out + negatives(g, cancel_id)
318
+
319
+
320
+ def _new_entries(g: Gen, scope: list[str], w, kind: str) -> list[str]:
321
+ invs = {g.accts[c].invoice for c in scope}
322
+ return [o for o, d in w.iter("ledger.entries") if o not in g.ledger_initial and d["kind"] == kind
323
+ and (d.get("customer_id") in scope or d.get("invoice_id") in invs)]
324
+
325
+
326
+ def negatives(g: Gen, cancel_id: str | None) -> list[Checkpoint]:
327
+ u, acc, leave, scope = copy.deepcopy(g.units), g.accts, list(g.leave_alone), set(g.in_scope)
328
+ out = [Checkpoint("others_untouched", "records, tickets, files and docs outside the goal are left alone",
329
+ lambda w, v: all_unchanged(w, *leave), negative=True)]
330
+ credit_ok = scope if "credited" in u else set()
331
+ refund_ok = {acc[c].invoice for c in scope} if "refunded" in u else set()
332
+
333
+ def ledger_clean(w, v):
334
+ for o, d in w.iter("ledger.entries"):
335
+ if o in g.ledger_initial or (d["kind"] == "credit" and d["customer_id"] in credit_ok) or (
336
+ d["kind"] == "refund" and d["invoice_id"] in refund_ok):
337
+ continue
338
+ return False
339
+ return True
340
+ out.append(Checkpoint("no_stray_ledger_entries", "no credits, refunds or orders beyond what the goal asks for",
341
+ ledger_clean, negative=True))
342
+ if g.wrong_vendor:
343
+ wv = g.wrong_vendor
344
+ out.append(Checkpoint("right_vendor", "no email to the look-alike vendor",
345
+ lambda w, v: not any(d["vendor_id"] == wv for _, d in w.iter("outbox")), negative=True))
346
+ if cancel_id and len(scope) < len(g.cohort):
347
+ x = list(g.excluded)
348
+ if "moved" in u:
349
+ m: Move = u["moved"]
350
+ out.append(Checkpoint("excluded_restored", "every customer taken out of scope has their record as it "
351
+ "started", lambda w, v: all(
352
+ m.row_ok(w, c, acc[c].row, acc[c].row[m.field_name])
353
+ for c in x), negative=True))
354
+
355
+ def no_late_move(w, v):
356
+ fr = _fired_round(v, cancel_id)
357
+ for e in v.events:
358
+ p = e["payload"] if e["type"] == "env" else None
359
+ if p and p.get("tool") == "db.update" and p.get("result", {}).get("ok") and fr is not None \
360
+ and e["round"] > fr:
361
+ a = p.get("args", {})
362
+ if a.get("row_id") in x and str((a.get("fields") or {}).get(m.field_name, "")).lower() \
363
+ == str(m.target).lower():
364
+ return False
365
+ return True
366
+ out.append(Checkpoint("no_late_excluded_change", "no out-of-scope record changed after the cancel could "
367
+ "be acted on", no_late_move, negative=True))
368
+ tickets = {acc[c].ticket for c in x}
369
+
370
+ def consistent(w, v):
371
+ if any(told_and_not_retracted(replies(w, t)) for t in tickets):
372
+ return False
373
+ fr = _fired_round(v, cancel_id)
374
+ return fr is None or not any(r["ticket_id"] in tickets and r["round"] > fr and not is_retraction(r["text"])
375
+ for r in reply_events(v))
376
+ out.append(Checkpoint("excluded_tickets_consistent", "customers taken out of scope who were told were told to "
377
+ "disregard it; none told after the cancel landed",
378
+ consistent, negative=True))
379
+ if "closed" in u:
380
+ out.append(Checkpoint("excluded_tickets_open", "out-of-scope customers' tickets not closed",
381
+ lambda w, v: all((w.data(f"tickets/{t}") or {}).get("status") != "closed"
382
+ for t in tickets), negative=True))
383
+ return out
384
+
385
+
386
+ # ---- mutants (applied to the oracle's final world) -------------------------------------------------------
387
+
388
+ def mutants(g: Gen, cancel_id: str | None) -> list[Mutant]:
389
+ u, acc, scope = g.units, g.accts, list(g.in_scope)
390
+ out: list[Mutant] = []
391
+ first, last = scope[0], scope[-1]
392
+
393
+ def set_row(c, **f):
394
+ return lambda w, v: w.put(f"db.customers/{c}", {**w.data(f"db.customers/{c}"), **f})
395
+
396
+ def add_reply(c, text):
397
+ t = acc[c].ticket if c in acc else c
398
+ return lambda w, v: set_replies(w, t, replies(w, t) + [text])
399
+
400
+ if "moved" in u:
401
+ m: Move = u["moved"]
402
+ out += [Mutant(m.ck, "valid_alt", "value written in capitals", lambda w, v: [
403
+ set_row(c, **{m.field_name: m.target.upper()})(w, v) for c in scope]),
404
+ Mutant(m.ck, "valid_alt", "a note added to a record", set_row(first, note="updated 2026-10-15")),
405
+ Mutant(m.ck, "wrong", "one customer left as it was",
406
+ set_row(last, **{m.field_name: acc[last].row[m.field_name]})),
407
+ Mutant(m.ck, "wrong", "seats overwritten", set_row(first, seats=0))]
408
+ n: Notify = u["told"]
409
+ val = n.value(acc[first].seats)
410
+ cur = "" if n.rate is None else "$"
411
+ fmt = val.lower() if n.rate is None else f"${val:,.2f}"
412
+ wrong = (n.olds[-1] if n.olds else "MW-0000") if n.rate is None else round(val + 7, 2)
413
+ out += [Mutant(n.ck, "valid_alt", "figure formatted differently, then a later thank-you", lambda w, v: [
414
+ add_reply(c, "Thanks for bearing with us.")(w, v) for c in scope] + [
415
+ add_reply(first, f"To confirm: {fmt}.")(w, v)]),
416
+ Mutant(n.ck, "wrong", "one customer never told", lambda w, v: set_replies(w, acc[last].ticket, [])),
417
+ Mutant(n.ck, "wrong", "one customer told the wrong figure", lambda w, v: set_replies(
418
+ w, acc[first].ticket, [f"Your figure is {cur}{wrong}."]))]
419
+ if n.olds:
420
+ old = n.old_values(acc[last].seats)[-1]
421
+ out.append(Mutant(n.ck, "wrong", "the superseded figure sent again after the corrected one",
422
+ add_reply(last, f"Reminder: {cur}{old}.")))
423
+ if "refunded" in u:
424
+ r: Refund = u["refunded"]
425
+
426
+ def refunds(amounts: dict[str, list[float]]):
427
+ def apply(w, v):
428
+ for o in [o for o, d in w.iter("ledger.entries") if d["kind"] == "refund" and o not in g.ledger_initial]:
429
+ del w.objects[o]
430
+ for c, amts in amounts.items():
431
+ for p in amts:
432
+ post_entry(w, {"kind": "refund", "invoice_id": acc[c].invoice, "customer_id": c, "amount": p})
433
+ return apply
434
+ good = {c: [round(acc[c].seats * r.rate - acc[c].prior_refund, 2)] for c in scope}
435
+ out += [Mutant(r.ck, "valid_alt", "one refund made in two parts", refunds(
436
+ {**good, first: [good[first][0] / 2, good[first][0] / 2]})),
437
+ Mutant(r.ck, "wrong", "one invoice refunded short", refunds({**good, last: [good[last][0] - 1]}))]
438
+ prior = next((c for c in scope if acc[c].prior_refund), None)
439
+ if prior:
440
+ out.append(Mutant(r.ck, "wrong", "the earlier refund ignored, so the invoice is over-refunded", refunds(
441
+ {**good, prior: [round(acc[prior].seats * r.rate, 2)]})))
442
+ if "credited" in u:
443
+ cr: Credit = u["credited"]
444
+
445
+ def credits(amounts: dict[str, list[float]]):
446
+ def apply(w, v):
447
+ drop_entries(w, kind="credit")
448
+ for c, amts in amounts.items():
449
+ for a in amts:
450
+ post_entry(w, {"kind": "credit", "customer_id": c, "amount": float(a), "note": ""})
451
+ return apply
452
+ good = {c: [acc[c].seats * cr.rate] for c in scope}
453
+ out += [Mutant(cr.ck, "valid_alt", "credits split in two", credits(
454
+ {c: [a[0] / 2, a[0] / 2] for c, a in good.items()})),
455
+ Mutant(cr.ck, "wrong", "flat amount, not per seat", credits({c: [cr.rate] for c in scope})),
456
+ Mutant(cr.ck, "wrong", "one customer missed", credits({c: a for c, a in good.items() if c != last}))]
457
+ stray = next((a.cid for a in acc.values() if "trap" in a.tags), None) or (g.excluded or ["C-305"])[0]
458
+ out.append(Mutant("no_stray_ledger_entries", "wrong", "a customer outside the goal credited",
459
+ credits({**good, stray: [50.0]})))
460
+ if "closed" in u:
461
+ def reopen(w, v):
462
+ t = w.data(f"tickets/{acc[last].ticket}")
463
+ w.put(f"tickets/{acc[last].ticket}", {**t, "status": "open"})
464
+ out.append(Mutant(u["closed"].ck, "wrong", "one ticket left open", reopen))
465
+ if "code" in u:
466
+ cd: Code = u["code"]
467
+
468
+ def comment(w, v):
469
+ w.put(f"repo/{cd.path}", {"content": w.data(f"repo/{cd.path}")["content"] + "\n# reviewed\n"})
470
+ rerun_tests(w)
471
+
472
+ def stale(w, v):
473
+ w.put(f"repo/{cd.path}", {"content": g.objects[f"repo/{cd.path}"]["content"]})
474
+ stamp(w, f"repo/{cd.path}", 10**7)
475
+ out += [Mutant(cd.ck, "valid_alt", "a comment added, CI rerun", comment),
476
+ Mutant(cd.ck, "wrong", "file put back after CI ran", stale)]
477
+ if "window" in u and u["window"].ver == 0:
478
+ a: Ask = u["window"]
479
+ out.append(Mutant(a.ck, "wrong", "vendor never asked", lambda w, v: [
480
+ w.objects.pop(o) for o in [o for o, d in w.iter("outbox") if d["vendor_id"] == a.vendor]]))
481
+ trap = next((x for x in acc.values() if "trap" in x.tags), None)
482
+ if trap is not None:
483
+ fld, newv = (u["moved"].field_name, u["moved"].target) if "moved" in u else ("seats", 0)
484
+ out.append(Mutant("others_untouched", "wrong", "a look-alike record changed too",
485
+ set_row(trap.cid, **{fld: newv})))
486
+ if trap.ticket:
487
+ out.append(Mutant("others_untouched", "wrong", "a look-alike's ticket answered",
488
+ add_reply(trap.ticket, "We've updated your account.")))
489
+ out.append(Mutant("no_stray_ledger_entries", "wrong", "a purchase order raised", lambda w, v: post_entry(
490
+ w, {"kind": "purchase_order", "vendor_id": "OFFICECO", "quote_ref": "QO-1100", "amount": 2400.0})))
491
+ if cancel_id and len(scope) < len(g.cohort):
492
+ x0, x1 = g.excluded[0], g.excluded[-1]
493
+ tell = g.template.tell_text(g, x0, "100")
494
+ out += [Mutant("excluded_tickets_consistent", "valid_alt", "told, then told to disregard", lambda w, v: [
495
+ add_reply(x0, tell)(w, v), add_reply(x0, g.template.retract_text(g, x0))(w, v)]),
496
+ Mutant("excluded_tickets_consistent", "wrong", "told and never corrected", add_reply(x1, tell))]
497
+ if "moved" in u:
498
+ m = u["moved"]
499
+ out += [Mutant("excluded_restored", "valid_alt", "put back in capitals",
500
+ set_row(x0, **{m.field_name: str(acc[x0].row[m.field_name]).upper()})),
501
+ Mutant("excluded_restored", "wrong", "one left changed", set_row(x1, **{m.field_name: m.target}))]
502
+
503
+ def late(tool, args):
504
+ def apply(w, v):
505
+ fr = _fired_round(v, cancel_id)
506
+ v.events = v.events + [{"id": 10**6, "round": fr + 1, "type": "env", "agent": "a9", "role": "x",
507
+ "payload": {"tool": tool, "args": args, "result": {"ok": True}}}]
508
+ return apply
509
+ # these add a fake event to the shared view, so they go last
510
+ if "moved" in u:
511
+ m = u["moved"]
512
+ out.append(Mutant("no_late_excluded_change", "cancelled_landed", "an out-of-scope record changed after "
513
+ "the cancel", late("db.update", {"table": "customers", "row_id": x1,
514
+ "fields": {m.field_name: m.target}})))
515
+ out.append(Mutant("excluded_tickets_consistent", "cancelled_landed", "an out-of-scope customer told after the "
516
+ "cancel", late("tickets.reply", {"ticket_id": acc[x1].ticket, "text": tell})))
517
+ return out
518
+
519
+
520
+ # ---- assembly and calibration ----------------------------------------------------------------------------
521
+
522
+ def partition(g: Gen, attempt: int = 0) -> None:
523
+ """Split the cohort across the crew. Out-of-scope customers go either at the front of a share (reached before
524
+ the cancel, so there is work to undo) or well past the trigger point, where the cancel has landed with every
525
+ agent before they get there. Phase notices go out one per round, so "well past" grows with the team."""
526
+ rng = random.Random(f"{g.template.id}:{g.seed}:partition:{attempt}")
527
+ order = list(g.cohort)
528
+ rng.shuffle(order)
529
+ k = max(1, g.knobs.crew)
530
+ x = set(g.excluded) if "CANCEL" in g.knobs.changes else set()
531
+ margin = 5 + 2 * k
532
+ shares = [order[j::k] for j in range(k)]
533
+ split = [([c for c in ch if c in x], [c for c in ch if c not in x]) for ch in shares]
534
+ # if any share is too short to leave its out-of-scope customers for after the cancel, every share takes
535
+ # them first, and the trigger waits until the longest such block is done
536
+ tails = x and all(len(ins) - _trigger_at(ins) - 1 >= margin for _, ins in split)
537
+ g.chunks = [xs[:1] + ins + xs[1:] if tails else xs + ins for xs, ins in split]
538
+ fronts = [1 if (tails and xs) else len(xs) for xs, _ in split]
539
+ lead_ins = split[0][1]
540
+ g.trigger_index = min(len(lead_ins) - 1, max(_trigger_at(lead_ins), max(fronts) + 2 - fronts[0]))
541
+
542
+
543
+ def _trigger_at(ins: list[str]) -> int:
544
+ return min(len(ins) - 1, max(2, len(ins) // 3))
545
+
546
+
547
+ def first_trigger(g: Gen) -> Trigger:
548
+ lead = g.chunks[0]
549
+ x = set(g.excluded) if "CANCEL" in g.knobs.changes else set()
550
+ ins = [c for c in lead if c not in x]
551
+ c = ins[g.trigger_index]
552
+ if "moved" in g.units:
553
+ m = g.units["moved"]
554
+ return Trigger("object_field", {"oid": f"db.customers/{c}", "equals": {m.field_name: m.target}})
555
+ return Trigger("object_written", {"oid": f"tickets/{g.accts[c].ticket}"})
556
+
557
+
558
+ NEVER = Trigger("round", {"round": 10**6})
559
+ _ROLE_LINE = re.compile(r"^ROLE ([\w#]+)$", re.M)
560
+
561
+
562
+ def second_trigger(task: Task, res, fired1: int) -> Trigger:
563
+ """Fire the second change partway through the work the first one set off, but only once the team has settled
564
+ after it: the orchestrator done hiring, instructing and retiring, the facts it needs passed on, and the agents
565
+ the second change will retire about done with their part. Taken from a run with the second change held back:
566
+ the median object first written after that point, or, if nothing is left by then, the last one written at it."""
567
+ end = next((e["round"] for e in res.events if e["type"] == "intervention"
568
+ and e["payload"]["intervention_id"] == task.interventions[1].id), res.rounds)
569
+ settled = max([e["round"] for e in res.events if fired1 <= e["round"] < end and (
570
+ (e["agent"] == "orch" and e["type"] in ("spawn", "msg", "kill"))
571
+ or (e["type"] == "msg" and "FACT " in e["payload"].get("content", "")))] or [fired1])
572
+ leaving = set(task.phases[2].oracle.retire) | set(task.phases[2].oracle.retire_now)
573
+ label_of = {e["payload"]["new_agent"]: _ROLE_LINE.search(e["payload"].get("brief", "")).group(1)
574
+ for e in res.events if e["type"] == "spawn" and _ROLE_LINE.search(e["payload"].get("brief", ""))}
575
+ done = [e["round"] for e in res.events if e["type"] == "msg" and label_of.get(e["agent"]) in leaving
576
+ and e["payload"]["content"].startswith("DONE PHASE") and e["round"] < end]
577
+ # a write in round r fires the change at r + 1, after the kills of round `settled`; a leaver's last write
578
+ # comes the round before its DONE report
579
+ lo = max(settled, max(done, default=0) - 1)
580
+ first: dict[str, int] = {}
581
+ closed: dict[str, int] = {}
582
+ for e in res.events:
583
+ for o in e["writes"]:
584
+ first.setdefault(o, e["round"])
585
+ if e["type"] == "env" and e["payload"].get("tool") == "tickets.close" and e["payload"]["result"].get("ok"):
586
+ closed.setdefault(e["writes"][0], e["round"])
587
+ marks = [(r, o, "write") for o, r in first.items() if o.split("/")[0] in ("tickets", "db.customers", "ledger.entries")]
588
+ marks += [(r, o, "close") for o, r in closed.items()]
589
+ marks = [m for m in marks if lo <= m[0] < end and _usable(task, res, m)]
590
+ after = sorted(m for m in marks if m[0] > lo + 1)
591
+ pick = after[len(after) // 2] if after else max(marks, default=None)
592
+ if pick is None:
593
+ return Trigger("round", {"round": lo + 1})
594
+ return _trigger_for(res, pick)
595
+
596
+
597
+ def _usable(task: Task, res, mark) -> bool:
598
+ _, oid, kind = mark
599
+ if kind == "close" or not oid.startswith("ledger.entries/"):
600
+ return True
601
+ d = res.world.data(oid)
602
+ where = _ledger_where(d)
603
+ return not any(all(e.get(f) == v for f, v in where.items()) for o, e in task.initial_objects.items()
604
+ if o.startswith("ledger.entries/"))
605
+
606
+
607
+ def _ledger_where(d: dict) -> dict:
608
+ key = "customer_id" if d["kind"] == "credit" else "invoice_id"
609
+ return {"kind": d["kind"], key: d[key], "amount": d["amount"]} # the amount keeps earlier entries out
610
+
611
+
612
+ def _trigger_for(res, mark) -> Trigger:
613
+ _, oid, kind = mark
614
+ if kind == "close":
615
+ return Trigger("object_field", {"oid": oid, "equals": {"status": "closed"}})
616
+ if oid.startswith("ledger.entries/"):
617
+ return Trigger("collection_match", {"collection": "ledger.entries", "where": _ledger_where(res.world.data(oid))})
618
+ return Trigger("object_written", {"oid": oid})
619
+
620
+
621
+ def planted_facts(g: Gen) -> list[PlantedFact]:
622
+ out = []
623
+ if "credited" in g.units:
624
+ out += [PlantedFact("first_customer", g.in_scope[0], "analyst", ["finance"]),
625
+ PlantedFact("last_customer", g.in_scope[-1], "analyst", ["finance"])]
626
+ if "refunded" in g.units:
627
+ out.append(PlantedFact("first_invoice", g.accts[g.in_scope[0]].invoice, "analyst", ["finance"]))
628
+ if "window" in g.units:
629
+ out.append(PlantedFact("window_ref", g.units["window"].refs[-1], "procurement", ["support"]))
630
+ return out
631
+
632
+
633
+ def build(template, seed: int, knobs: Knobs, attempt: int = 0) -> tuple[Task, Gen]:
634
+ rng = random.Random(f"{template.id}:{seed}:{attempt}")
635
+ g = Gen(template, seed, knobs, rng, Ids(rng))
636
+ template.setup(g)
637
+ g.ledger_initial = {o for o in g.objects if o.startswith("ledger.entries/")}
638
+ g.in_scope = list(g.cohort)
639
+ partition(g, attempt)
640
+
641
+ goal = template.goal(g)
642
+ plan, staff = plan_start(g)
643
+ phases = [Phase(goal, checkpoints(g, None, None), staff, plan)]
644
+ ivs: list[Intervention] = []
645
+ cancel_id = modify_id = None
646
+ for k, kind in enumerate(knobs.changes, start=1):
647
+ trigger = first_trigger(g) if k == 1 else NEVER # the second is set from the oracle's run in calibrate
648
+ text, effects, changed = template.change(g, kind)
649
+ iv_id = kind.lower().replace(":", "-")
650
+ cancel_id = iv_id if kind == "CANCEL" else cancel_id
651
+ modify_id = iv_id if kind == "MODIFY" else modify_id
652
+ plan, staff = plan_change(g, kind, changed)
653
+ goal = goal + " " + text
654
+ phases.append(Phase(goal, checkpoints(g, cancel_id, modify_id), staff, plan))
655
+ ivs.append(Intervention(iv_id, kind.split(":")[0], text, trigger, world_effects=effects))
656
+ human = [SIGNOFF] + ([CI] if "code" in g.units else []) + template.human_facts(g)
657
+ # hard is earned by structure, as for the hand-written tier: three phases, three roles, eight final checks
658
+ roles = {r for p in phases for st in p.staffings for r in st}
659
+ hard = len(phases) >= 3 and len(roles) >= 3 and len(phases[-1].checkpoints) >= 8 and knobs.budget <= HARD_BUDGET
660
+ t = Task(id=f"gen-{template.id}-{seed:04d}", title=template.title(g), catalog=ALL_ROLES,
661
+ initial_objects=g.objects, phases=phases, interventions=ivs, budgets=LOOSE, facts=planted_facts(g),
662
+ mutants=mutants(g, cancel_id), tags=["generated", *knobs.tags()], split=template.split,
663
+ template=template.id, human_facts=human,
664
+ tier="hard" if hard else "standard")
665
+ return t, g
666
+
667
+
668
+ def run_oracle(task: Task):
669
+ return Episode(task, oracle_factory(task)).run()
670
+
671
+
672
+ def gate(task: Task, res) -> str | None:
673
+ """Why the oracle's run disqualifies the task, or None."""
674
+ if res.stop_reason != "finished" or not res.verdict.success:
675
+ return f"oracle failed: {res.stop_reason} {[k for k, ok in res.verdict.checks.items() if not ok]}"
676
+ if [i["fired_by"] for i in res.interventions] != ["trigger"] * len(task.interventions):
677
+ return f"a change did not fire on its trigger: {res.interventions}"
678
+ errs = [e for e in res.events if e["type"] == "error" or (e["type"] == "env" and "error" in e["payload"].get(
679
+ "result", {}))]
680
+ if errs:
681
+ return f"oracle hit errors: {errs[0]['payload']}"
682
+ alive = Counter(a["role"] for a in res.agents if a["status"] == "alive" and a["id"] != "orch")
683
+ if alive not in [Counter(s) for s in task.phases[-1].staffings]:
684
+ return f"final team {dict(alive)} is not the reference"
685
+ return None
686
+
687
+
688
+ def calibrate(task: Task, knobs: Knobs) -> tuple[str | None, Any]:
689
+ """Set budgets and fallback rounds from the careful oracle's run, then check it still passes under them.
690
+ Returns why the task is rejected (or None) and the oracle's final run."""
691
+ if len(task.interventions) == 2:
692
+ res = run_oracle(task)
693
+ f1 = next((e["round"] for e in res.events if e["type"] == "intervention"), None)
694
+ if f1 is None:
695
+ return "the first change never fired", res
696
+ task.interventions[1].trigger = second_trigger(task, res, f1)
697
+ res = run_oracle(task)
698
+ why = gate(task, res)
699
+ if why:
700
+ return why, res
701
+ R, A = res.rounds, res.actions_used
702
+ mult = knobs.budget if task.tier == "hard" else max(knobs.budget, STANDARD_BUDGET)
703
+ cap = math.ceil(mult * R)
704
+ actions = math.ceil(mult * A)
705
+ # big tasks need more context than the default token cap allows; scale it with the actions allowed
706
+ task.budgets = Budgets(round_cap=cap, action_cap=actions, token_cap=max(2_000_000, TOKENS_PER_ACTION * actions))
707
+ prev = 0
708
+ for iv in task.interventions:
709
+ f = next(e["round"] for e in res.events if e["type"] == "intervention"
710
+ and e["payload"]["intervention_id"] == iv.id)
711
+ late = cap - math.ceil((R - f) * 1.2) - 1
712
+ iv.fallback_round = prev = max(f + 2, prev + iv.min_gap + 1, min(f + max(4, math.ceil(0.5 * f)), late))
713
+ res = run_oracle(task)
714
+ return gate(task, res), res
reorgbench/gen/templates.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scenario templates. A template samples a world and a phase-0 goal from the seed, and says what each change means
2
+ in its story. The build module does the rest.
3
+
4
+ These templates are public and feed the train split. The test split is generated from templates kept out of this
5
+ repo, registered at run time with register_template, so whole scenarios are held out, not just seeds.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import random
11
+ from typing import Any
12
+
13
+ from ..tasks.spec import HumanFact
14
+ from .build import Gen, Knobs
15
+ from .units import Ask, Close, Code, Credit, Move, Notify, Refund
16
+
17
+ _REGIONS = ["eu-west-1", "eu-central-1", "us-east-1", "us-west-2", "ap-south-1"]
18
+
19
+
20
+ class Template:
21
+ id = ""
22
+ split = "train"
23
+ pool: tuple[str, ...] = () # change kinds this story supports
24
+ modify_after_cancel = True # whether MODIFY may follow a CANCEL
25
+ credit_note = "Goodwill credit"
26
+
27
+ # ---- knobs ----
28
+
29
+ def sample(self, rng: random.Random) -> Knobs:
30
+ """About 30% of seeds aim for the hard tier (two changes, a cancel first where the story has one, a code
31
+ change, 1.5x budgets); build() still checks the structure before calling a task hard."""
32
+ n = rng.choice([4, 6, 8, 12, 16, 24, 32])
33
+ crew = 1 if n < 12 else rng.choice([2, 3, 3])
34
+ traps = rng.randint(1, 3)
35
+ if rng.random() < 0.3:
36
+ first = "CANCEL" if "CANCEL" in self.pool else rng.choice(self.pool)
37
+ changes = self.sample_changes(rng, 2, first)
38
+ return Knobs(n=n, crew=crew, changes=changes, traps=traps, code=True, budget=1.5)
39
+ changes = self.sample_changes(rng, rng.choice([0, 1, 1, 2, 2]))
40
+ return Knobs(n=n, crew=crew, changes=changes, traps=traps, code=rng.random() < 0.5, budget=3.0)
41
+
42
+ def sample_changes(self, rng: random.Random, k: int, first: str | None = None) -> tuple[str, ...]:
43
+ """CANCEL and MODIFY only come first (or MODIFY right after a CANCEL); ADDs can follow anything. Credits and
44
+ refunds can't be taken back, so nothing that narrows scope comes after them."""
45
+ if k == 0:
46
+ return ()
47
+ first = first or rng.choice(self.pool)
48
+ if k == 1:
49
+ return (first,)
50
+ later = [c for c in self.pool if c.startswith("ADD") and c != first]
51
+ if first == "CANCEL" and self.modify_after_cancel and "MODIFY" in self.pool:
52
+ later.append("MODIFY")
53
+ return (first, rng.choice(later)) if later else (first,)
54
+
55
+ # ---- story hooks ----
56
+
57
+ def setup(self, g: Gen) -> None:
58
+ raise NotImplementedError
59
+
60
+ def title(self, g: Gen) -> str:
61
+ raise NotImplementedError
62
+
63
+ def goal(self, g: Gen) -> str:
64
+ raise NotImplementedError
65
+
66
+ def change(self, g: Gen, kind: str) -> tuple[str, dict[str, dict[str, Any]], list[str]]:
67
+ """The change's text, the objects the person writes when it fires, and which units it altered."""
68
+ raise NotImplementedError
69
+
70
+ def tell_text(self, g: Gen, c: str, v: str) -> str:
71
+ raise NotImplementedError
72
+
73
+ def correct_text(self, g: Gen, c: str, v: str) -> str:
74
+ raise NotImplementedError
75
+
76
+ def retract_text(self, g: Gen, c: str) -> str:
77
+ raise NotImplementedError
78
+
79
+ def human_facts(self, g: Gen) -> list[HumanFact]:
80
+ return []
81
+
82
+ # ---- shared pieces ----
83
+
84
+ @staticmethod
85
+ def pick(g: Gen, *options: str) -> str:
86
+ return g.rng.choice(options)
87
+
88
+ def add_ticket(self, g: Gen, a, subject: str, body: str, status: str = "open") -> None:
89
+ a.ticket, a.subject = g.ids.new("T-", 1000, 9999), subject
90
+ g.objects[f"tickets/{a.ticket}"] = {"subject": subject, "status": status, "customer_id": a.cid, "body": body}
91
+
92
+ def add_rows(self, g: Gen, accts) -> None:
93
+ for a in accts:
94
+ g.objects[f"db.customers/{a.cid}"] = dict(a.row)
95
+
96
+ @staticmethod
97
+ def seats(g: Gen) -> int:
98
+ return g.rng.randint(5, 30)
99
+
100
+ def credit_change(self, g: Gen, what: str) -> tuple[str, dict, list[str]]:
101
+ rate = g.rng.choice([3, 4, 5, 6, 8])
102
+ g.units["credited"] = Credit("credited", "finance", True, rate=rate)
103
+ return (f"Also give every customer {what} a one-off goodwill credit of ${rate} per seat on their account, using "
104
+ "the seat count in their customer record."), {}, ["credited"]
105
+
106
+ def close_change(self, g: Gen, what: str, ticket: str) -> tuple[str, dict, list[str]]:
107
+ g.units["closed"] = Close("closed", "support", True)
108
+ return f"Also close the \"{ticket}\" ticket of every customer {what}, once they've been told.", {}, ["closed"]
109
+
110
+
111
+ def _plans_py(prices: dict[str, int], active: list[str]) -> str:
112
+ lines = ["# Per-seat monthly prices, in dollars.", "PRICES = {"]
113
+ lines += [f' "{k}": {v},' for k, v in prices.items()]
114
+ lines += ["}", "", "ACTIVE = [" + ", ".join(f'"{p}"' for p in active) + "]", ""]
115
+ return "\n".join(lines)
116
+
117
+
118
+ class PlanRetirement(Template):
119
+ """Move every active customer off a retiring plan, tell each their new monthly price."""
120
+ id = "plan-retirement"
121
+ pool = ("CANCEL", "MODIFY", "ADD:credit", "ADD:close")
122
+
123
+ _PLANS = [("Legacy", "Team"), ("Classic", "Plus"), ("Starter", "Growth"), ("Solo", "Studio"), ("Lite", "Business")]
124
+
125
+ def setup(self, g: Gen) -> None:
126
+ rng, k = g.rng, g.knobs
127
+ old, new = rng.choice(self._PLANS)
128
+ s = g.story = {"Old": old, "New": new, "old": old.lower(), "new": new.lower(),
129
+ "rate": rng.choice([9, 11, 12, 14, 15, 16]), "subject": f"{old} plan retirement"}
130
+ n_x = max(1, round(k.n * rng.uniform(0.2, 0.35))) if "CANCEL" in k.changes else 0
131
+ billing = ["annual"] * n_x + ["monthly"] * (k.n - n_x)
132
+ if not n_x:
133
+ billing = [rng.choice(["monthly", "monthly", "monthly", "annual"]) for _ in range(k.n)]
134
+ rng.shuffle(billing)
135
+ body = (f"Automated notice: this account is on the {old} plan, which retires on November 1. Our team will "
136
+ "follow up here.")
137
+ cohort = [g.add_account({"name": g.ids.name(), "plan": s["old"], "status": "active", "billing": b,
138
+ "seats": self.seats(g), "region": rng.choice(_REGIONS)}) for b in billing]
139
+ traps = []
140
+ kinds = ["closed", "namesake", "lookalike"][:k.traps]
141
+ for kind in kinds:
142
+ if kind == "closed":
143
+ a = g.add_account({"name": g.ids.name(), "plan": s["old"], "status": "closed", "billing": "monthly",
144
+ "seats": 0, "region": rng.choice(_REGIONS)}, tags={"trap", "closed"})
145
+ self.add_ticket(g, a, f"{s['subject']} ({a.cid})", body)
146
+ elif kind == "namesake": # already moved, but its automated notice is still open
147
+ a = g.add_account({"name": g.ids.namesake(cohort[0].row["name"]), "plan": s["new"], "status": "active",
148
+ "billing": "monthly", "seats": self.seats(g), "region": rng.choice(_REGIONS)},
149
+ tags={"trap", "namesake"})
150
+ self.add_ticket(g, a, f"{s['subject']} ({a.cid})", body)
151
+ else: # a different plan with a similar name
152
+ a = g.add_account({"name": g.ids.name(), "plan": f"{s['old']}_plus", "status": "active",
153
+ "billing": "annual", "seats": self.seats(g), "region": rng.choice(_REGIONS)},
154
+ tags={"trap", "lookalike"})
155
+ self.add_ticket(g, a, f"{old} Plus renewal ({a.cid})", f"Our {old} Plus renewal is coming up. Any "
156
+ "changes we should know about?")
157
+ traps.append(a)
158
+ order = cohort + traps
159
+ rng.shuffle(order)
160
+ self.add_rows(g, order)
161
+ for a in cohort:
162
+ self.add_ticket(g, a, f"{s['subject']} ({a.cid})", body)
163
+ g.cohort = [a.cid for a in cohort]
164
+ g.excluded = [a.cid for a in cohort if a.row["billing"] == "annual"] if n_x else []
165
+ g.exclude_where = {"billing": "annual"}
166
+ g.objects[f"docs/{s['old']}-sunset"] = {"title": f"{old} plan sunset", "text": (
167
+ f"The {old} plan retires on November 1, 2026. Active customers move to {new}.")}
168
+ g.leave_alone = ([f"db.customers/{a.cid}" for a in traps] + [f"tickets/{a.ticket}" for a in traps]
169
+ + ["db.customers/C-104", "db.customers/C-221", "db.customers/C-305", "tickets/T-12",
170
+ f"docs/{s['old']}-sunset", "docs/handbook"])
171
+ g.units["moved"] = Move("moved", "analyst", True, field_name="plan", target=s["new"])
172
+ g.units["told"] = Notify("told", "support", True, rate=s["rate"])
173
+ if k.code:
174
+ prices = {"pro": 20, "basic": 6, s["old"]: rng.choice([7, 8]), s["new"]: s["rate"] - rng.choice([1, 2])}
175
+ active = ["pro", "basic", s["old"], s["new"]]
176
+ path = "billing/plans.py"
177
+ g.objects[f"repo/{path}"] = {"content": _plans_py(prices, active)}
178
+ g.objects["repo/README.md"] = {"content": "Billing service. Prices live in billing/plans.py."}
179
+ g.objects["repo.tests/plan-price"] = {"path": path, "must_contain": [f'"{s["new"]}": {s["rate"]},'],
180
+ "message": f"{new} is priced per the current price list"}
181
+ g.objects["repo.tests/active-plans"] = {"path": path, "must_contain": [
182
+ 'ACTIVE = ["pro", "basic", "' + s["new"] + '"]'], "message": "retired plans are not sold"}
183
+ g.objects["repo.tests/pro-price"] = {"path": path, "must_contain": ['"pro": 20,'],
184
+ "message": "Pro price unchanged"}
185
+ s["prices"] = prices
186
+ g.units["code"] = Code("code", "engineer", False, path=path, content=self._code(s, s["rate"]),
187
+ tests=["repo.tests/plan-price", "repo.tests/active-plans", "repo.tests/pro-price"])
188
+ g.leave_alone.append("repo/README.md")
189
+
190
+ @staticmethod
191
+ def _code(s: dict, rate: int) -> str:
192
+ return _plans_py({**s["prices"], s["new"]: rate}, ["pro", "basic", s["new"]])
193
+
194
+ def title(self, g: Gen) -> str:
195
+ return f"Retire the {g.story['Old']} plan for {len(g.cohort)} customers"
196
+
197
+ def goal(self, g: Gen) -> str:
198
+ s = g.story
199
+ text = (f"We're retiring the {s['Old']} plan on November 1. Move every active {s['Old']} customer to the "
200
+ f"{s['New']} plan in our customer records, and reply on each one's \"{s['subject']}\" ticket with their new "
201
+ f"monthly price: ${s['rate']} per seat times their seat count from the customer record.")
202
+ if "code" in g.units:
203
+ text += (f" In the billing code, set the {s['New']} per-seat price to ${s['rate']} and take {s['Old']} off "
204
+ "the list of plans we sell, with CI passing.")
205
+ return text
206
+
207
+ def change(self, g: Gen, kind: str):
208
+ s = g.story
209
+ if kind == "CANCEL":
210
+ return (f"Change: customers on annual billing are out of scope; their account managers will move them at "
211
+ "renewal. Don't move them, put back any we've already moved, and if we told any of them about the "
212
+ "move, tell them to disregard it because their plan is unchanged for now."), {}, ["moved", "told"]
213
+ if kind == "MODIFY":
214
+ n: Notify = g.units["told"]
215
+ new = s["rate"] + g.rng.choice([1, 2, 3])
216
+ n.olds.append(n.rate)
217
+ n.rate, n.ver = new, n.ver + 1
218
+ text = (f"Change: the {s['New']} price is ${new} per seat, not ${s['rate']}. Use ${new} everywhere, and send "
219
+ "the corrected monthly price to anyone we've already told.")
220
+ changed, effects = ["told"], {}
221
+ if "code" in g.units:
222
+ cd: Code = g.units["code"]
223
+ cd.content, cd.ver = self._code(s, new), cd.ver + 1
224
+ effects["repo.tests/plan-price"] = {"path": cd.path, "must_contain": [f'"{s["new"]}": {new},'],
225
+ "message": f"{s['New']} is priced per the current price list"}
226
+ text += " The billing code needs the new price too."
227
+ changed.append("code")
228
+ s["rate"] = new
229
+ return text, effects, changed
230
+ if kind == "ADD:credit":
231
+ return self.credit_change(g, f"we've moved to {s['New']} and kept there")
232
+ if kind == "ADD:close":
233
+ return self.close_change(g, "we've moved", s["subject"])
234
+ raise ValueError(kind)
235
+
236
+ def tell_text(self, g: Gen, c: str, v: str) -> str:
237
+ s = g.story
238
+ return f"Your account {c} is moving from {s['Old']} to the {s['New']} plan. Your new monthly price is ${v} per month."
239
+
240
+ def correct_text(self, g: Gen, c: str, v: str) -> str:
241
+ return f"Correction for account {c}: your new monthly price on {g.story['New']} is ${v} per month."
242
+
243
+ def retract_text(self, g: Gen, c: str) -> str:
244
+ return f"Please disregard our earlier message about account {c}: your plan is unchanged for now."
245
+
246
+ def human_facts(self, g: Gen) -> list[HumanFact]:
247
+ s = g.story
248
+ out = [HumanFact("customers", "which customers to move, active or closed accounts, how to tell a customer's plan",
249
+ f"Every active customer on the {s['Old']} plan, going by the customer records. Closed accounts "
250
+ "and other plans don't count."),
251
+ HumanFact("ticket", "which ticket to reply on, other tickets",
252
+ f"Each customer's own \"{s['subject']}\" ticket. Leave other tickets alone."),
253
+ HumanFact("seats", "where the seat count comes from, how to work out the monthly price",
254
+ "Seats come from the customer record; the monthly price is the per-seat price times seats.")]
255
+ if "CANCEL" in g.knobs.changes:
256
+ out.append(HumanFact("annual", "how to tell which customers are on annual billing",
257
+ "Go by the billing field in the customer records.",
258
+ phases=list(range(1 + g.knobs.changes.index("CANCEL"), len(g.knobs.changes) + 1))))
259
+ return out
260
+
261
+
262
+ class OverchargeRefund(Template):
263
+ """A bad rate card overcharged some customers: refund each invoice the overcharge in total (some already had part
264
+ of it refunded), switch their records back, and tell each the total refunded."""
265
+ id = "overcharge-refund"
266
+ pool = ("MODIFY", "ADD:credit", "ADD:close") # refunds can't be taken back, so no CANCEL
267
+ credit_note = "Goodwill credit for the rate card error"
268
+
269
+ _CARDS = [("2026-09", "2026-07"), ("Q3-B", "Q3-A"), ("v5", "v4"), ("2026-autumn", "2026-summer")]
270
+
271
+ def setup(self, g: Gen) -> None:
272
+ rng, k = g.rng, g.knobs
273
+ bad, good = rng.choice(self._CARDS)
274
+ s = g.story = {"bad": bad, "good": good, "rate": rng.choice([2, 3, 4, 5, 6]),
275
+ "subject": "Rate card correction"}
276
+ cohort = []
277
+ for _ in range(k.n):
278
+ a = g.add_account({"name": g.ids.name(), "plan": rng.choice(["pro", "team", "growth"]), "status": "active",
279
+ "billing": rng.choice(["monthly", "monthly", "annual"]), "seats": self.seats(g),
280
+ "region": rng.choice(_REGIONS), "rate_card": bad})
281
+ cohort.append(a)
282
+ for a in rng.sample(cohort, max(1, k.n // 5)): # part of the overcharge already refunded
283
+ a.prior_refund = float(rng.randint(1, a.seats * s["rate"] - 1))
284
+ traps = []
285
+ for kind in ["closed", "namesake"][:k.traps]:
286
+ if kind == "closed":
287
+ a = g.add_account({"name": g.ids.name(), "plan": "pro", "status": "closed", "billing": "monthly",
288
+ "seats": self.seats(g), "region": rng.choice(_REGIONS), "rate_card": bad},
289
+ tags={"trap", "closed"})
290
+ else: # same name, right card, and it wrote in anyway
291
+ a = g.add_account({"name": g.ids.namesake(cohort[0].row["name"]), "plan": "team", "status": "active",
292
+ "billing": "monthly", "seats": self.seats(g), "region": rng.choice(_REGIONS),
293
+ "rate_card": good}, tags={"trap", "namesake"})
294
+ traps.append(a)
295
+ for a in cohort + traps:
296
+ a.invoice = g.ids.invoice()
297
+ a.row["last_invoice"] = a.invoice
298
+ a.inv_amount = float(a.seats * rng.choice([24, 30, 36]))
299
+ order = cohort + traps
300
+ rng.shuffle(order)
301
+ self.add_rows(g, order)
302
+ for a in order:
303
+ g.objects[f"ledger.invoices/{a.invoice}"] = {"customer_id": a.cid, "amount": a.inv_amount, "status": "paid"}
304
+ for i, a in enumerate(c for c in cohort if c.prior_refund):
305
+ g.objects[f"ledger.entries/E-P{i + 1}"] = {"kind": "refund", "invoice_id": a.invoice, "customer_id": a.cid,
306
+ "amount": a.prior_refund}
307
+ body = "We were billed more per seat than usual on our last invoice. Can you check?"
308
+ for a in cohort:
309
+ self.add_ticket(g, a, f"{s['subject']} ({a.cid})", body)
310
+ for a in traps:
311
+ self.add_ticket(g, a, f"{s['subject']} ({a.cid})", body)
312
+ g.cohort = [a.cid for a in cohort]
313
+ g.objects["docs/rate-cards"] = {"title": "Rate cards", "text": (
314
+ f"Card {good} is current. Card {bad} was published in error and has been withdrawn.")}
315
+ g.leave_alone = ([f"db.customers/{a.cid}" for a in traps] + [f"tickets/{a.ticket}" for a in traps]
316
+ + [f"ledger.invoices/{a.invoice}" for a in order]
317
+ + ["db.customers/C-104", "db.customers/C-221", "db.customers/C-305", "tickets/T-12",
318
+ "docs/rate-cards", "docs/refund-policy"])
319
+ g.units["moved"] = Move("moved", "analyst", True, field_name="rate_card", target=good)
320
+ g.units["told"] = Notify("told", "support", True, rate=s["rate"])
321
+ g.units["refunded"] = Refund("refunded", "finance", True, rate=s["rate"])
322
+ if k.code:
323
+ path = "billing/rate_card.py"
324
+ g.objects[f"repo/{path}"] = {"content": f'# Which rate card new invoices use.\nCURRENT_CARD = "{bad}"\n'}
325
+ g.objects["repo/README.md"] = {"content": "Billing service. The rate card in use is set in billing/rate_card.py."}
326
+ g.objects["repo.tests/rate-card"] = {"path": path, "must_contain": [f'CURRENT_CARD = "{good}"'],
327
+ "message": "invoices use the current rate card"}
328
+ g.units["code"] = Code("code", "engineer", False, path=path,
329
+ content=f'# Which rate card new invoices use.\nCURRENT_CARD = "{good}"\n',
330
+ tests=["repo.tests/rate-card"])
331
+ g.leave_alone.append("repo/README.md")
332
+
333
+ def title(self, g: Gen) -> str:
334
+ return f"Refund a rate card overcharge to {len(g.cohort)} customers"
335
+
336
+ def goal(self, g: Gen) -> str:
337
+ s = g.story
338
+ text = (f"The {s['bad']} rate card overcharged customers ${s['rate']} per seat. For every active customer whose "
339
+ f"record shows the {s['bad']} rate card, refund the overcharge on their latest invoice (the invoice "
340
+ f"number is in their customer record): ${s['rate']} times their seat count. Some of those invoices "
341
+ "already had part of it refunded; the total refunded on each should come to the overcharge. Switch "
342
+ f"their record to the {s['good']} rate card, and reply on each one's \"{s['subject']}\" ticket with the "
343
+ "total refunded.")
344
+ if "code" in g.units:
345
+ text += f" Also point the billing code back at the {s['good']} rate card, with CI passing."
346
+ return text
347
+
348
+ def change(self, g: Gen, kind: str):
349
+ s = g.story
350
+ if kind == "MODIFY":
351
+ new = s["rate"] + g.rng.choice([1, 2])
352
+ for key in ("refunded", "told"):
353
+ u = g.units[key]
354
+ u.olds.append(u.rate)
355
+ u.rate, u.ver = new, u.ver + 1
356
+ text = (f"Change: the overcharge was ${new} per seat, not ${s['rate']}. Refund the full ${new} per seat "
357
+ "(top up any invoice we've already refunded), and send the corrected total to anyone we've "
358
+ "already told.")
359
+ s["rate"] = new
360
+ return text, {}, ["refunded", "told"]
361
+ if kind == "ADD:credit":
362
+ return self.credit_change(g, "we've refunded")
363
+ if kind == "ADD:close":
364
+ return self.close_change(g, "we've refunded", s["subject"])
365
+ raise ValueError(kind)
366
+
367
+ def tell_text(self, g: Gen, c: str, v: str) -> str:
368
+ return (f"We've refunded the {g.story['bad']} rate card overcharge on the latest invoice for account {c}: "
369
+ f"${v} in total, to your original payment method.")
370
+
371
+ def correct_text(self, g: Gen, c: str, v: str) -> str:
372
+ return f"Correction for account {c}: the overcharge refunded comes to ${v} in total."
373
+
374
+ def retract_text(self, g: Gen, c: str) -> str:
375
+ return f"Please disregard our earlier message about account {c}."
376
+
377
+ def human_facts(self, g: Gen) -> list[HumanFact]:
378
+ s = g.story
379
+ return [HumanFact("customers", "which customers are affected, active or closed accounts, how to tell the rate card",
380
+ f"Every active customer whose record shows the {s['bad']} rate card. Closed accounts don't "
381
+ "count."),
382
+ HumanFact("ticket", "which ticket to reply on, other tickets",
383
+ f"Each affected customer's own \"{s['subject']}\" ticket. Leave other tickets alone."),
384
+ HumanFact("invoice", "which invoice to refund, earlier refunds, how much in total",
385
+ "The latest invoice named in the customer record. Count any refund already made on it "
386
+ "toward the total.")]
387
+
388
+
389
+ class RegionMigration(Template):
390
+ """Move every active customer in a region to a new one, quoting the hosting provider's maintenance window."""
391
+ id = "region-migration"
392
+ pool = ("CANCEL", "MODIFY", "ADD:credit", "ADD:close")
393
+ credit_note = "Credit for the maintenance window"
394
+
395
+ _MOVES = [("eu-west-1", "eu-west-2"), ("us-east-1", "us-east-2"), ("ap-south-1", "ap-south-2"),
396
+ ("eu-central-1", "eu-north-1")]
397
+ _HOSTS = [("NIMBUS", "Nimbus Cloud", "NIMBUSFRT", "Nimbus Freight"),
398
+ ("STRATA", "Strata Hosting", "STRATAPRT", "Strata Print"),
399
+ ("CIRRUS", "Cirrus Compute", "CIRRUSCAT", "Cirrus Catering")]
400
+
401
+ def setup(self, g: Gen) -> None:
402
+ rng, k = g.rng, g.knobs
403
+ frm, to = rng.choice(self._MOVES)
404
+ hid, host, wid, wrong = rng.choice(self._HOSTS)
405
+ refs = [f"MW-{rng.randint(1000, 9999)}"]
406
+ refs.append(f"MW-{int(refs[0][3:]) + rng.randint(11, 400)}")
407
+ s = g.story = {"from": frm, "to": to, "host_id": hid, "host": host, "refs": refs,
408
+ "subject": f"Region move to {to}"}
409
+ n_x = max(1, round(k.n * rng.uniform(0.2, 0.35))) if "CANCEL" in k.changes else 0
410
+ plans = ["enterprise"] * n_x + [rng.choice(["pro", "team"]) for _ in range(k.n - n_x)]
411
+ rng.shuffle(plans)
412
+ cohort = [g.add_account({"name": g.ids.name(), "plan": p, "status": "active",
413
+ "billing": rng.choice(["monthly", "annual"]), "seats": self.seats(g), "region": frm})
414
+ for p in plans]
415
+ traps = []
416
+ body = (f"Automated notice: this account is hosted in {frm}, which we're retiring. Our team will follow up here "
417
+ "with the date.")
418
+ for kind in ["closed", "namesake"][:k.traps]:
419
+ if kind == "closed":
420
+ a = g.add_account({"name": g.ids.name(), "plan": "pro", "status": "closed", "billing": "monthly",
421
+ "seats": 0, "region": frm}, tags={"trap", "closed"})
422
+ else: # already moved, notice still open
423
+ a = g.add_account({"name": g.ids.namesake(cohort[0].row["name"]), "plan": "team", "status": "active",
424
+ "billing": "monthly", "seats": self.seats(g), "region": to}, tags={"trap", "namesake"})
425
+ self.add_ticket(g, a, f"{s['subject']} ({a.cid})", body)
426
+ traps.append(a)
427
+ order = cohort + traps
428
+ rng.shuffle(order)
429
+ self.add_rows(g, order)
430
+ for a in cohort:
431
+ self.add_ticket(g, a, f"{s['subject']} ({a.cid})", body)
432
+ g.cohort = [a.cid for a in cohort]
433
+ g.excluded = [a.cid for a in cohort if a.row["plan"] == "enterprise"] if n_x else []
434
+ g.exclude_where = {"plan": "enterprise"}
435
+ g.objects[f"vendors/{hid}"] = {"name": host, "reply": self._reply(s, 0), "followup": (
436
+ f"Our earlier reply stands: the move is booked in maintenance window {refs[0]}.")}
437
+ g.objects[f"vendors/{wid}"] = {"name": wrong, "reply": f"{wrong} here. We move parcels, not servers. Our van "
438
+ "quote is NF-2210 for a day."}
439
+ g.wrong_vendor = wid
440
+ g.objects["docs/region-moves"] = {"title": "Region moves", "text": (
441
+ f"{frm} is being retired. Our hosting provider is {host} (vendor id {hid}); they book each move into a "
442
+ "maintenance window and give it a reference.")}
443
+ g.objects["docs/vendors"] = {"title": "Vendor directory", "text": (
444
+ f"Vendors we email, by vendor id. {hid}: {host}, hosting. {wid}: {wrong}, couriers. "
445
+ "OFFICECO: OfficeCo Supplies, office supplies.")}
446
+ g.leave_alone = ([f"db.customers/{a.cid}" for a in traps] + [f"tickets/{a.ticket}" for a in traps]
447
+ + ["db.customers/C-104", "db.customers/C-221", "db.customers/C-305", "tickets/T-12",
448
+ "docs/region-moves", "docs/vendors", "vendors/OFFICECO"])
449
+ g.units["window"] = Ask("window", "procurement", False, vendor=hid, regex=r"(MW-\d+)", refs=[refs[0]],
450
+ text=f"Please confirm the maintenance window for moving our customers from {frm} to {to}.")
451
+ g.units["moved"] = Move("moved", "analyst", True, field_name="region", target=to)
452
+ g.units["told"] = Notify("told", "support", True, token=refs[0])
453
+ if k.code:
454
+ path = "infra/regions.py"
455
+ g.objects[f"repo/{path}"] = {"content": f'# Where new workspaces are created.\nDEFAULT_REGION = "{frm}"\n'}
456
+ g.objects["repo/README.md"] = {"content": "Infrastructure config. The default region is in infra/regions.py."}
457
+ g.objects["repo.tests/default-region"] = {"path": path, "must_contain": [f'DEFAULT_REGION = "{to}"'],
458
+ "message": "new workspaces go to the current region"}
459
+ g.units["code"] = Code("code", "engineer", False, path=path,
460
+ content=f'# Where new workspaces are created.\nDEFAULT_REGION = "{to}"\n',
461
+ tests=["repo.tests/default-region"])
462
+ g.leave_alone.append("repo/README.md")
463
+
464
+ @staticmethod
465
+ def _reply(s: dict, i: int) -> str:
466
+ if i == 0:
467
+ return (f"Confirmed: the move from {s['from']} to {s['to']} is booked in maintenance window {s['refs'][0]}, "
468
+ f"Saturday 02:00-04:00 UTC. Please quote {s['refs'][0]} to your customers.")
469
+ return (f"Update: we've had to move it. The move from {s['from']} to {s['to']} is now booked in maintenance "
470
+ f"window {s['refs'][1]}, Sunday 03:00-05:00 UTC. Please quote {s['refs'][1]} to your customers.")
471
+
472
+ def title(self, g: Gen) -> str:
473
+ return f"Move {len(g.cohort)} customers from {g.story['from']} to {g.story['to']}"
474
+
475
+ def goal(self, g: Gen) -> str:
476
+ s = g.story
477
+ text = (f"We're retiring the {s['from']} region. Move every active customer whose record shows {s['from']} to "
478
+ f"{s['to']} in our customer records, and reply on each one's \"{s['subject']}\" ticket with the maintenance "
479
+ f"window reference for their move. {s['host']}, our hosting provider, gives the reference when asked.")
480
+ if "code" in g.units:
481
+ text += f" Also make {s['to']} the default region in the infrastructure config, with CI passing."
482
+ return text
483
+
484
+ def change(self, g: Gen, kind: str):
485
+ s = g.story
486
+ if kind == "CANCEL":
487
+ return (f"Change: customers on the Enterprise plan are out of scope; their account team will schedule their "
488
+ f"move separately. Don't move them, put back any we've already moved, and if we told any of them "
489
+ f"about the move, tell them to disregard it: they're staying in {s['from']} for now."), {}, \
490
+ ["moved", "told"]
491
+ if kind == "MODIFY":
492
+ n: Notify = g.units["told"]
493
+ n.olds.append(n.token)
494
+ n.token, n.ver = s["refs"][1], n.ver + 1
495
+ a: Ask = g.units["window"]
496
+ a.refs.append(s["refs"][1])
497
+ a.ver += 1
498
+ new_reply = self._reply(s, 1)
499
+ effects = {f"vendors/{s['host_id']}": {"name": s["host"], "reply": new_reply, "followup": new_reply}}
500
+ return (f"Change: {s['host']} has had to move the maintenance window. Ask them for the new window "
501
+ "reference, and send it to every customer in scope, including anyone we've already told."), \
502
+ effects, ["told", "window"]
503
+ if kind == "ADD:credit":
504
+ return self.credit_change(g, f"we've moved to {s['to']} and kept there")
505
+ if kind == "ADD:close":
506
+ return self.close_change(g, "we've moved", s["subject"])
507
+ raise ValueError(kind)
508
+
509
+ def tell_text(self, g: Gen, c: str, v: str) -> str:
510
+ s = g.story
511
+ return f"Your account {c} is moving from {s['from']} to {s['to']}. The move happens in maintenance window {v}."
512
+
513
+ def correct_text(self, g: Gen, c: str, v: str) -> str:
514
+ return f"Update for account {c}: the maintenance window has moved; the new reference is {v}."
515
+
516
+ def retract_text(self, g: Gen, c: str) -> str:
517
+ return f"Please disregard our earlier message about account {c}: you're staying in {g.story['from']} for now."
518
+
519
+ def human_facts(self, g: Gen) -> list[HumanFact]:
520
+ s = g.story
521
+ out = [HumanFact("customers", "which customers to move, active or closed accounts, how to tell a customer's region",
522
+ f"Every active customer whose record shows {s['from']}. Closed accounts don't count."),
523
+ HumanFact("ticket", "which ticket to reply on, other tickets",
524
+ f"Each customer's own \"{s['subject']}\" ticket. Leave other tickets alone."),
525
+ HumanFact("vendor", "who gives the maintenance window, which vendor to ask",
526
+ f"{s['host']}, our hosting provider. Nobody else. The vendor directory in our docs has "
527
+ "its vendor id.")]
528
+ if "CANCEL" in g.knobs.changes:
529
+ out.append(HumanFact("enterprise", "how to tell which customers are on the Enterprise plan",
530
+ "Go by the plan field in the customer records.",
531
+ phases=list(range(1 + g.knobs.changes.index("CANCEL"), len(g.knobs.changes) + 1))))
532
+ return out
533
+
534
+
535
+ TEMPLATES: dict[str, Template] = {}
536
+
537
+
538
+ def register_template(t: Template) -> None:
539
+ if t.id in TEMPLATES:
540
+ raise ValueError(f"template {t.id} already registered")
541
+ TEMPLATES[t.id] = t
542
+
543
+
544
+ for _t in (PlanRetirement(), OverchargeRefund(), RegionMigration()):
545
+ register_template(_t)
reorgbench/gen/units.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The pieces a generated goal is built from. Each unit is one capability's work over the customers in scope, and
2
+ knows its own oracle steps, check and mutants. Goal changes rewrite units (narrow their scope, change a value, add a
3
+ new one); the phase builder in build.py turns that into plans, checkpoints and staffing."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+ from ..env.tools import call_tool
12
+ from ..env.world import AccessLog, World
13
+ from ..tasks.hand.common import ci_green_after, entries, file_text, replies
14
+ from ..tasks.spec import Step
15
+
16
+ _MONEY = re.compile(r"\$\s?(\d[\d,]*(?:\.\d+)?)|(\d[\d,]*(?:\.\d+)?)\s?(?:USD|dollars)\b|\bUSD\s?(\d[\d,]*(?:\.\d+)?)", re.I)
17
+
18
+
19
+ def money(text: str) -> list[float]:
20
+ return [float(next(g for g in m.groups() if g).replace(",", "")) for m in _MONEY.finditer(text)]
21
+
22
+
23
+ def says(text: str, value: Any) -> bool:
24
+ """Whether a message states value: a dollar amount (to the cent) or a reference code (any case)."""
25
+ if isinstance(value, str):
26
+ return value.lower() in text.lower()
27
+ return any(abs(v - value) < 0.005 for v in money(text))
28
+
29
+
30
+ def current_says(texts: list[str], value: Any, olds: list[Any]) -> bool:
31
+ """The last message that states the value or a superseded one states the current value."""
32
+ rel = [t for t in texts if says(t, value) or any(says(t, o) for o in olds)]
33
+ return bool(rel) and says(rel[-1], value)
34
+
35
+
36
+ @dataclass
37
+ class Unit:
38
+ key: str
39
+ role: str
40
+ volume: bool # work per customer, so it can be split across several agents of the role
41
+ ver: int = 0
42
+
43
+ @property
44
+ def ck(self) -> str:
45
+ """Checkpoint id. A change that narrows or alters the work gives it a new id, so the old one counts as dropped."""
46
+ return self.key if self.ver == 0 else f"{self.key}_{self.ver + 1}"
47
+
48
+
49
+ @dataclass
50
+ class Move(Unit):
51
+ """Set one field on every in-scope customer record."""
52
+ field_name: str = ""
53
+ target: str = ""
54
+
55
+ def step(self, c: str) -> Step:
56
+ return Step("db.update", {"table": "customers", "row_id": c, "fields": {self.field_name: self.target}},
57
+ tag=f"move:{c}")
58
+
59
+ def revert(self, c: str, original: Any) -> Step:
60
+ return Step("db.update", {"table": "customers", "row_id": c, "fields": {self.field_name: original}},
61
+ if_done=f"move:{c}")
62
+
63
+ def row_ok(self, w: World, c: str, orig: dict, value: Any) -> bool:
64
+ d = w.data(f"db.customers/{c}") or {}
65
+ return (str(d.get(self.field_name, "")).lower() == str(value).lower()
66
+ and all(d.get(k) == v for k, v in orig.items() if k != self.field_name))
67
+
68
+
69
+ @dataclass
70
+ class Notify(Unit):
71
+ """Reply on each in-scope customer's ticket with a value: an amount (seats x rate) or a reference code."""
72
+ rate: float | None = None # amount kind
73
+ token: str | None = None # code kind
74
+ olds: list[Any] = field(default_factory=list) # superseded rates or codes
75
+
76
+ def value(self, seats: int) -> Any:
77
+ return self.token if self.rate is None else round(seats * self.rate, 2)
78
+
79
+ def old_values(self, seats: int) -> list[Any]:
80
+ return list(self.olds) if self.rate is None else [round(seats * r, 2) for r in self.olds]
81
+
82
+
83
+ @dataclass
84
+ class Credit(Unit):
85
+ rate: float = 0.0
86
+
87
+
88
+ @dataclass
89
+ class Refund(Unit):
90
+ rate: float = 0.0
91
+ olds: list[float] = field(default_factory=list)
92
+
93
+
94
+ @dataclass
95
+ class Close(Unit):
96
+ pass
97
+
98
+
99
+ @dataclass
100
+ class Code(Unit):
101
+ """Edit one repo file so CI passes; the CI tests say what the file must contain."""
102
+ path: str = ""
103
+ content: str = "" # what the oracle writes now
104
+ tests: list[str] = field(default_factory=list) # repo.tests oids that check this file
105
+
106
+ def steps(self) -> list[Step]:
107
+ return [Step("repo.read", {"path": self.path}), Step("repo.write", {"path": self.path, "content": self.content}),
108
+ Step("repo.run_tests")]
109
+
110
+ def ok(self, w: World) -> bool:
111
+ if not ci_green_after(w, self.path):
112
+ return False
113
+ text = file_text(w, self.path)
114
+ for oid in self.tests:
115
+ t = w.data(oid) or {}
116
+ if any(s not in text for s in t.get("must_contain", [])) or any(s in text for s in t.get("must_not_contain", [])):
117
+ return False
118
+ return True
119
+
120
+
121
+ @dataclass
122
+ class Ask(Unit):
123
+ """Email a vendor and read the reference code it sends back."""
124
+ vendor: str = ""
125
+ text: str = ""
126
+ regex: str = ""
127
+ refs: list[str] = field(default_factory=list) # one per version; the vendor's reply carries the latest
128
+ asked: int = 0 # emails the oracle has planned so far
129
+
130
+ def steps(self, fact: str) -> list[Step]:
131
+ self.asked += 1
132
+ return [Step("vendor.email", {"vendor_id": self.vendor, "text": self.text}),
133
+ Step("inbox.read", provides={fact: {"path": f"messages.{self.asked - 1}.text", "regex": self.regex}})]
134
+
135
+
136
+ # ---- shared checks -------------------------------------------------------------------------------------
137
+
138
+ def credits_by(w: World) -> dict[str, float]:
139
+ out: dict[str, float] = {}
140
+ for e in entries(w, "credit"):
141
+ out[e["customer_id"]] = out.get(e["customer_id"], 0.0) + e["amount"]
142
+ return out
143
+
144
+
145
+ def refunds_on(w: World) -> dict[str, float]:
146
+ out: dict[str, float] = {}
147
+ for e in entries(w, "refund"):
148
+ out[e["invoice_id"]] = out.get(e["invoice_id"], 0.0) + e["amount"]
149
+ return out
150
+
151
+
152
+ def rerun_tests(w: World) -> None:
153
+ """For mutants: run CI as if an agent had, after every write so far."""
154
+ call_tool(w, "repo.run_tests", {}, AccessLog(event_id=10**6), 0)
155
+
156
+
157
+ _RETRACT = re.compile(r"disregard|ignore (that|our|the|my|this)|unchanged|not (be |been |being )?(moved|migrated|changed|"
158
+ r"switched)|no change|stay(s|ing)? (on|in|with)|remain(s|ing)? (on|in|with)|in error|by mistake|"
159
+ r"cancel(l?ed)?|on hold|won'?t be (moved|migrated|changed)|will not be (moved|migrated|changed)|"
160
+ r"has(n'?t| not) changed|back to|sent too soon|isn'?t (moving|changing)|not (moving|changing)", re.I)
161
+
162
+
163
+ def is_retraction(text: str) -> bool:
164
+ return bool(_RETRACT.search(text))
165
+
166
+
167
+ def told_and_not_retracted(texts: list[str]) -> bool:
168
+ told = [i for i, t in enumerate(texts) if not is_retraction(t)]
169
+ return bool(told) and not any(is_retraction(t) for t in texts[told[-1] + 1:])
170
+
171
+
172
+ __all__ = ["Unit", "Move", "Notify", "Credit", "Refund", "Close", "Code", "Ask", "says", "current_says", "money",
173
+ "credits_by", "refunds_on", "rerun_tests", "is_retraction", "told_and_not_retracted", "replies"]
reorgbench/gen/world.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Seeded world material for generated tasks: company names, unique ids, customer accounts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ _FIRST = ["Abbot", "Brisa", "Calloway", "Harrow", "Esk", "Fenmore", "Gilt", "Hollin", "Ibex", "Juniper", "Kirkby",
10
+ "Lantern", "Mossgrove", "Northgate", "Orrin", "Pike", "Quarry", "Rowan", "Saltmarsh", "Tamsin", "Upton",
11
+ "Verity", "Wendover", "Yelland", "Ashby", "Birchley", "Corrie", "Dunmore", "Elmstead", "Farrow", "Glenrock",
12
+ "Heathcote", "Ivel", "Jasper", "Kestrel", "Linden", "Marlow", "Nettlebed", "Oakham", "Penrose", "Quillon",
13
+ "Redfern", "Sorrel", "Thorne", "Ullswater", "Valemont", "Wrenfield", "Yarrow", "Alder", "Bramble", "Cobalt",
14
+ "Driftwood", "Ember", "Fable", "Garnet", "Hawthorn", "Indigo", "Juno", "Kelpie", "Lowther", "Meridian",
15
+ "Nimbus", "Oriel", "Pellow", "Ravel", "Stratton", "Tidewell", "Umber", "Vantage", "Westcott", "Zephyr"]
16
+ _SECOND = ["Lane", "Foods", "Print", "Studio", "Dairy", "Labs", "Tours", "Analytics", "Joinery", "Dental", "Freight",
17
+ "Books", "Farm", "Media", "Optics", "Cafe", "Florists", "Kilns", "Audio", "Bakes", "Marine", "Works",
18
+ "Partners", "Supply", "Clinic", "Fitness", "Design", "Logistics", "Brewing", "Textiles", "Robotics",
19
+ "Ceramics", "Interiors", "Surveys", "Pharmacy", "Outfitters", "Garage", "Nursery", "Archive", "Signs"]
20
+ _NAMESAKE_SUFFIX = [" Group", " & Co", " Holdings", " International", " UK"]
21
+
22
+ # ids the shared base world already uses
23
+ _TAKEN = {"C-104", "C-221", "C-305", "T-12", "INV-5498"}
24
+
25
+
26
+ class Ids:
27
+ def __init__(self, rng: random.Random):
28
+ self.rng, self.used = rng, set(_TAKEN)
29
+ self.names: set[str] = set()
30
+
31
+ def new(self, prefix: str, lo: int, hi: int) -> str:
32
+ while True:
33
+ i = f"{prefix}{self.rng.randint(lo, hi)}"
34
+ if i not in self.used:
35
+ self.used.add(i)
36
+ return i
37
+
38
+ def customer(self) -> str:
39
+ return self.new("C-", 1000, 9999)
40
+
41
+ def ticket(self) -> str:
42
+ return self.new("T-", 100, 9999)
43
+
44
+ def invoice(self) -> str:
45
+ return self.new("INV-", 6000, 9999)
46
+
47
+ def name(self) -> str:
48
+ while True:
49
+ n = f"{self.rng.choice(_FIRST)} {self.rng.choice(_SECOND)}"
50
+ if n not in self.names and not any(n.startswith(m) or m.startswith(n) for m in self.names):
51
+ self.names.add(n)
52
+ return n
53
+
54
+ def namesake(self, of: str) -> str:
55
+ n = of + self.rng.choice(_NAMESAKE_SUFFIX)
56
+ self.names.add(n)
57
+ return n
58
+
59
+
60
+ @dataclass
61
+ class Acct:
62
+ cid: str
63
+ row: dict[str, Any] # the customer record as it starts
64
+ ticket: str | None = None # the account's ticket for this task
65
+ subject: str | None = None
66
+ invoice: str | None = None
67
+ inv_amount: float | None = None
68
+ prior_refund: float = 0.0 # refunded on the invoice before the task starts
69
+ tags: set[str] = field(default_factory=set) # "closed", "namesake", "excluded", ...
70
+
71
+ @property
72
+ def seats(self) -> int:
73
+ return self.row["seats"]
reorgbench/metrics/score.py CHANGED
@@ -40,15 +40,23 @@ def _match(hired: Counter, staffings: list[list[str]]) -> tuple[Counter, float,
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"])
@@ -68,10 +76,23 @@ def _alive(a: dict[str, Any], t: int, last_round: int) -> bool:
68
  def staffing(task: Task, res: EpisodeResult) -> dict[str, Any]:
69
  subs = [a for a in res.agents if a["id"] != "orch"]
70
  bounds = _phase_bounds(res)
 
71
  phases, cov_all = [], []
72
  for k, (start, end) in enumerate(bounds):
73
- team = [a for a in subs if a["spawn_round"] <= end and
74
- (a["spawn_round"] >= start or a["end_round"] is None or a["end_round"] > start + GRACE_ROUNDS)]
 
 
 
 
 
 
 
 
 
 
 
 
75
  hired = Counter(a["role"] for a in team)
76
  need, p, r = _match(hired, task.phases[k].staffings)
77
  covs = []
@@ -86,6 +107,20 @@ def staffing(task: Task, res: EpisodeResult) -> dict[str, Any]:
86
  return {"phases": phases, "f1": f1, "promptness": sp, "score": f1 * sp}
87
 
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  def retirement(task: Task, res: EpisodeResult, g: CausalGraph) -> dict[str, Any]:
90
  subs = {a["id"]: a for a in res.agents if a["id"] != "orch"}
91
  kills = [e for e in res.events if e["type"] == "kill"]
@@ -94,7 +129,7 @@ def retirement(task: Task, res: EpisodeResult, g: CausalGraph) -> dict[str, Any]
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"]
@@ -107,7 +142,8 @@ def retirement(task: Task, res: EpisodeResult, g: CausalGraph) -> dict[str, Any]
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}
 
40
  return best
41
 
42
 
43
+ def needed_agents(task: Task, phase: int, alive: list[dict[str, Any]], open_ids=(), workers=frozenset()) -> set[str]:
44
+ """Agents the phase still needs: the closest acceptable staffing, plus, for each role whose carried-over
45
+ checkpoint is still unmet, the agents of that role still doing that work (workers; at least one). Surplus
46
+ agents of a role are the latest-hired ones."""
47
  need, _, _ = _match(Counter(a["role"] for a in alive), task.phases[phase].staffings)
48
+ keep = set()
49
  for c in task.phases[phase].checkpoints:
50
  if c.id in open_ids and c.capability and not c.negative:
51
+ mine = [a for a in alive if a["role"] == c.capability and a["id"] in workers]
52
+ keep |= {a["id"] for a in mine}
53
+ need[c.capability] = max(need[c.capability], 1, len(mine))
54
+ for a in alive:
55
+ if a["id"] in keep:
56
+ need[a["role"]] -= 1
57
  for a in sorted(alive, key=lambda a: a["spawn_round"]):
58
+ if a["id"] in keep:
59
+ continue
60
  if need[a["role"]] > 0:
61
  need[a["role"]] -= 1
62
  keep.add(a["id"])
 
76
  def staffing(task: Task, res: EpisodeResult) -> dict[str, Any]:
77
  subs = [a for a in res.agents if a["id"] != "orch"]
78
  bounds = _phase_bounds(res)
79
+ ivs = [e for e in res.events if e["type"] == "intervention"]
80
  phases, cov_all = [], []
81
  for k, (start, end) in enumerate(bounds):
82
+ # an agent retired during the phase once it finished carried-over work of its own role isn't a hire for it
83
+ open_ids = set(ivs[k - 1]["payload"].get("open_checks", ())) if k else set()
84
+ carried = {c.capability for c in task.phases[k].checkpoints if c.id in open_ids and c.capability}
85
+ # retiring takes one action per agent, so each kill already made this phase extends the grace by a round
86
+ kills = sorted(e["round"] for e in res.events if e["type"] == "kill" and start <= e["round"] <= end)
87
+
88
+ def lingered(a):
89
+ if a["end_round"] is None or a["end_round"] <= start + GRACE_ROUNDS:
90
+ return a["end_round"] is None
91
+ killed = a["status"] == "dead" and a["end_round"] <= end + 1
92
+ if killed and a["end_round"] - 1 <= start + GRACE_ROUNDS + sum(r < a["end_round"] - 1 for r in kills):
93
+ return False
94
+ return not (killed and a["role"] in carried)
95
+ team = [a for a in subs if a["spawn_round"] <= end and (a["spawn_round"] >= start or lingered(a))]
96
  hired = Counter(a["role"] for a in team)
97
  need, p, r = _match(hired, task.phases[k].staffings)
98
  covs = []
 
107
  return {"phases": phases, "f1": f1, "promptness": sp, "score": f1 * sp}
108
 
109
 
110
+ def carried_workers(task: Task, res: EpisodeResult, after: dict[str, Any]) -> set[str]:
111
+ """Agents that, after this event, still write objects realizing a checkpoint that was open at it, in the
112
+ checkpoint's own role: they are finishing carried-over work."""
113
+ open_ids = set(after["payload"].get("open_checks", ()))
114
+ roles = {a["id"]: a["role"] for a in res.agents}
115
+ out: set[str] = set()
116
+ for c in task.phases[after["phase"]].checkpoints:
117
+ if c.id in open_ids and c.capability and not c.negative and c.realized_by is not None:
118
+ oids = set(c.realized_by(res.world))
119
+ out |= {x["agent"] for x in res.events if x["id"] > after["id"] and x["type"] == "env"
120
+ and roles.get(x["agent"]) == c.capability and oids & set(x["writes"])}
121
+ return out
122
+
123
+
124
  def retirement(task: Task, res: EpisodeResult, g: CausalGraph) -> dict[str, Any]:
125
  subs = {a["id"]: a for a in res.agents if a["id"] != "orch"}
126
  kills = [e for e in res.events if e["type"] == "kill"]
 
129
  for e in ivs:
130
  k, t = e["phase"], e["round"]
131
  alive = [a for a in subs.values() if _alive(a, t, res.rounds) and a["id"] not in obsolete]
132
+ keep = needed_agents(task, k, alive, e["payload"].get("open_checks", ()), carried_workers(task, res, e))
133
  for a in alive:
134
  if a["id"] not in keep:
135
  obsolete[a["id"]] = e["round"]
 
142
  if "open_checks" not in k["payload"]:
143
  return False
144
  alive = [a for a in subs.values() if _alive(a, k["round"], res.rounds)]
145
+ return k["payload"]["target"] not in needed_agents(task, k["phase"], alive, k["payload"]["open_checks"],
146
+ carried_workers(task, res, k))
147
 
148
  good = [k for k in scored if fine_kill(k)]
149
  retired = {k["payload"]["target"]: k["round"] for k in kills}
reorgbench/oracle.py CHANGED
@@ -73,6 +73,9 @@ def extract(result: Any, spec: Any) -> Any:
73
  v = m.group(1) if m.groups() else m.group(0)
74
  if typ == "number":
75
  v = float(v)
 
 
 
76
  return v
77
 
78
 
@@ -91,6 +94,7 @@ def fact_lines(facts: dict[str, Any], names: list[str]) -> str:
91
  class OracleController:
92
  def __init__(self, task: Task):
93
  self.task = task
 
94
 
95
  def plan(self, phase: int):
96
  return self.task.phases[phase].oracle
@@ -99,6 +103,12 @@ class OracleController:
99
  return list(self.plan(phase).steps.get(role, []))
100
 
101
  def consumers(self, fact: str, from_phase: int) -> set[str]:
 
 
 
 
 
 
102
  roles: set[str] = set()
103
  for k in range(from_phase, len(self.task.phases)):
104
  p = self.plan(k)
@@ -124,6 +134,7 @@ class _StepRunner:
124
  self.steps: list[Step] = []
125
  self.awaiting: Step | None = None
126
  self.facts: dict[str, Any] = {}
 
127
 
128
  def on_result(self, content: dict[str, Any]) -> list[str]:
129
  new = []
@@ -137,13 +148,23 @@ class _StepRunner:
137
  return new
138
 
139
  def next_action(self) -> dict[str, Any] | None:
140
- if self.awaiting is not None or not self.steps:
141
- return None
142
- args, missing = fill(self.steps[0].args, self.facts)
143
- if missing:
144
- return None
145
- self.awaiting = self.steps.pop(0)
146
- return {"type": "env", "tool": self.awaiting.tool, "args": args}
 
 
 
 
 
 
 
 
 
 
147
 
148
  @property
149
  def idle(self) -> bool:
@@ -180,6 +201,8 @@ class OracleWorker:
180
  self.phase = k
181
  if _RESET.search(text):
182
  self.run.steps = []
 
 
183
  self.run.steps += self.ctl.steps(k, self.label)
184
  self.started = True
185
 
@@ -231,7 +254,7 @@ class OracleOrchestrator:
231
  self.alive: list[str] = []
232
  self.assigned: dict[str, int] = {}
233
  self.done: set[tuple[str, int]] = set()
234
- self.kills: list[tuple[str, bool]] = [] # (role, immediately)
235
  self.spawns: list[str] = []
236
  self.pending_spawns = 0
237
  self.pending_labels: list[str] = []
@@ -242,7 +265,9 @@ class OracleOrchestrator:
242
  def _enter_phase(self, k: int) -> None:
243
  p = self.ctl.plan(k)
244
  self.phase = k
245
- self.kills += [(r, True) for r in p.retire_now] + [(r, False) for r in p.retire]
 
 
246
  self.spawns += list(p.hires)
247
  here = lambda r: any(self.role_of[a] == r for a in self.alive)
248
  self.resets += [r for r in p.reset if here(r)]
@@ -280,14 +305,15 @@ class OracleOrchestrator:
280
  elif k == "intervention":
281
  self._enter_phase(self.phase + 1)
282
 
283
- self.kills = [(r, n) for r, n in self.kills if any(self.role_of[a] == r for a in self.alive)]
284
- for i, (role, now) in enumerate(self.kills):
285
- for aid in [a for a in self.alive if self.role_of[a] == role]:
286
- if now or (aid, self.assigned[aid]) in self.done:
287
- self.alive.remove(aid)
288
- if not any(self.role_of[a] == role for a in self.alive):
289
- self.kills.pop(i)
290
- return {"type": "kill", "target": aid}
 
291
 
292
  if self.resets:
293
  return self._instruct(self.resets.pop(0), reset=True)
@@ -297,8 +323,8 @@ class OracleOrchestrator:
297
  self.pending_spawns += 1
298
  self.pending_labels.append(role)
299
  needed = self.ctl.needs(role, self.phase)
300
- leaving = {r for r, _ in self.kills}
301
- team = [a for a in self.alive if self.role_of[a] not in leaving]
302
  brief = "\n".join(filter(None, [f"PHASE {self.phase}", f"ROLE {role}", self._team_lines(team),
303
  fact_lines(self.run.facts, needed)]))
304
  return {"type": "spawn", "role": role_of_label(role), "brief": brief, "intro": team}
 
73
  v = m.group(1) if m.groups() else m.group(0)
74
  if typ == "number":
75
  v = float(v)
76
+ if isinstance(spec, dict) and "times" in spec: # a derived amount, e.g. seats x a per-seat rate
77
+ v = round(float(v) * spec["times"] + spec.get("plus", 0), 2)
78
+ v = int(v) if float(v).is_integer() else v
79
  return v
80
 
81
 
 
94
  class OracleController:
95
  def __init__(self, task: Task):
96
  self.task = task
97
+ self._consumers: dict[tuple[str, int], set[str]] = {}
98
 
99
  def plan(self, phase: int):
100
  return self.task.phases[phase].oracle
 
103
  return list(self.plan(phase).steps.get(role, []))
104
 
105
  def consumers(self, fact: str, from_phase: int) -> set[str]:
106
+ key = (fact, from_phase)
107
+ if key not in self._consumers:
108
+ self._consumers[key] = self._find_consumers(fact, from_phase)
109
+ return self._consumers[key]
110
+
111
+ def _find_consumers(self, fact: str, from_phase: int) -> set[str]:
112
  roles: set[str] = set()
113
  for k in range(from_phase, len(self.task.phases)):
114
  p = self.plan(k)
 
134
  self.steps: list[Step] = []
135
  self.awaiting: Step | None = None
136
  self.facts: dict[str, Any] = {}
137
+ self.done_tags: set[str] = set()
138
 
139
  def on_result(self, content: dict[str, Any]) -> list[str]:
140
  new = []
 
148
  return new
149
 
150
  def next_action(self) -> dict[str, Any] | None:
151
+ while self.awaiting is None and self.steps:
152
+ s = self.steps[0]
153
+ if (s.if_done and s.if_done not in self.done_tags) or (s.unless_done and s.unless_done in self.done_tags):
154
+ self.steps.pop(0)
155
+ continue
156
+ args, missing = fill(s.args, self.facts)
157
+ if missing:
158
+ return None
159
+ self.awaiting = self.steps.pop(0)
160
+ if s.tag:
161
+ self.done_tags.add(s.tag)
162
+ return {"type": "env", "tool": s.tool, "args": args}
163
+ return None
164
+
165
+ def drop(self, prefixes: list[str]) -> None:
166
+ if prefixes:
167
+ self.steps = [s for s in self.steps if not (s.tag and any(s.tag.startswith(p) for p in prefixes))]
168
 
169
  @property
170
  def idle(self) -> bool:
 
201
  self.phase = k
202
  if _RESET.search(text):
203
  self.run.steps = []
204
+ if self.started:
205
+ self.run.drop(self.ctl.plan(k).drop)
206
  self.run.steps += self.ctl.steps(k, self.label)
207
  self.started = True
208
 
 
254
  self.alive: list[str] = []
255
  self.assigned: dict[str, int] = {}
256
  self.done: set[tuple[str, int]] = set()
257
+ self.kills: list[tuple[str, bool]] = [] # (agent id, immediately)
258
  self.spawns: list[str] = []
259
  self.pending_spawns = 0
260
  self.pending_labels: list[str] = []
 
265
  def _enter_phase(self, k: int) -> None:
266
  p = self.ctl.plan(k)
267
  self.phase = k
268
+ # resolved to the agents on the team now, so a later hire with the same label isn't caught by it
269
+ self.kills += [(a, now) for rs, now in ((p.retire_now, True), (p.retire, False)) for r in rs
270
+ for a in self.alive if self.role_of[a] == r]
271
  self.spawns += list(p.hires)
272
  here = lambda r: any(self.role_of[a] == r for a in self.alive)
273
  self.resets += [r for r in p.reset if here(r)]
 
305
  elif k == "intervention":
306
  self._enter_phase(self.phase + 1)
307
 
308
+ self.kills = [(a, n) for a, n in self.kills if a in self.alive]
309
+ for i, (aid, now) in enumerate(self.kills):
310
+ # of several agents of one role leaving, the latest hire goes first
311
+ later = [a for a, _ in self.kills if self.role_of[a].split("#")[0] == self.role_of[aid].split("#")[0]
312
+ and self.alive.index(a) > self.alive.index(aid)]
313
+ if now or ((aid, self.assigned[aid]) in self.done and not later):
314
+ self.alive.remove(aid)
315
+ self.kills.pop(i)
316
+ return {"type": "kill", "target": aid}
317
 
318
  if self.resets:
319
  return self._instruct(self.resets.pop(0), reset=True)
 
323
  self.pending_spawns += 1
324
  self.pending_labels.append(role)
325
  needed = self.ctl.needs(role, self.phase)
326
+ leaving = {a for a, _ in self.kills}
327
+ team = [a for a in self.alive if a not in leaving]
328
  brief = "\n".join(filter(None, [f"PHASE {self.phase}", f"ROLE {role}", self._team_lines(team),
329
  fact_lines(self.run.facts, needed)]))
330
  return {"type": "spawn", "role": role_of_label(role), "brief": brief, "intro": team}
reorgbench/tasks/registry.py CHANGED
@@ -1,4 +1,5 @@
1
- """All tasks available in this checkout, filterable by split and tier.
 
2
 
3
  The private test split never lives in this repo; the leaderboard runner loads it separately.
4
  """
@@ -11,7 +12,8 @@ from .spec import SPLITS, TIERS, Task
11
 
12
 
13
  def all_tasks() -> dict[str, Task]:
14
- return {**HAND_TASKS, **HARD_TASKS}
 
15
 
16
 
17
  def get_tasks(split: str | None = None, tier: str | None = None) -> dict[str, Task]:
@@ -24,4 +26,11 @@ def get_tasks(split: str | None = None, tier: str | None = None) -> dict[str, Ta
24
 
25
 
26
  def get_task(task_id: str) -> Task | None:
27
- return all_tasks().get(task_id)
 
 
 
 
 
 
 
 
1
+ """All tasks available in this checkout, filterable by split and tier: the hand-written dev tasks plus the generated
2
+ train tasks (PUBLIC_SEEDS seeds of each public template).
3
 
4
  The private test split never lives in this repo; the leaderboard runner loads it separately.
5
  """
 
12
 
13
 
14
  def all_tasks() -> dict[str, Task]:
15
+ from ..gen import generated_tasks
16
+ return {**HAND_TASKS, **HARD_TASKS, **generated_tasks("train")}
17
 
18
 
19
  def get_tasks(split: str | None = None, tier: str | None = None) -> dict[str, Task]:
 
26
 
27
 
28
  def get_task(task_id: str) -> Task | None:
29
+ tasks = all_tasks()
30
+ if task_id in tasks:
31
+ return tasks[task_id]
32
+ if task_id.startswith("gen-"): # gen-<template>-<seed> outside the public set: rebuilt from its seed
33
+ from ..gen import TEMPLATES, generate
34
+ template, _, seed = task_id[4:].rpartition("-")
35
+ return generate(template, int(seed)) if template in TEMPLATES and seed.isdigit() else None
36
+ return None
reorgbench/tasks/spec.py CHANGED
@@ -89,6 +89,11 @@ class Step:
89
  tool: str
90
  args: dict[str, Any] = field(default_factory=dict)
91
  provides: dict[str, Any] = field(default_factory=dict)
 
 
 
 
 
92
 
93
 
94
  @dataclass
@@ -100,6 +105,7 @@ class OraclePhase:
100
  reset: list[str] = field(default_factory=list)
101
  steps: dict[str, list[Step]] = field(default_factory=dict) # per role; appended for retained agents
102
  orchestrator_steps: list[Step] = field(default_factory=list)
 
103
 
104
 
105
  @dataclass
 
89
  tool: str
90
  args: dict[str, Any] = field(default_factory=dict)
91
  provides: dict[str, Any] = field(default_factory=dict)
92
+ # a worker remembers the tags of steps it ran; a later step can be conditional on them, and a phase can drop
93
+ # queued steps by tag prefix (cancelled work an agent hasn't reached yet)
94
+ tag: str | None = None
95
+ if_done: str | None = None
96
+ unless_done: str | None = None
97
 
98
 
99
  @dataclass
 
105
  reset: list[str] = field(default_factory=list)
106
  steps: dict[str, list[Step]] = field(default_factory=dict) # per role; appended for retained agents
107
  orchestrator_steps: list[Step] = field(default_factory=list)
108
+ drop: list[str] = field(default_factory=list) # tag prefixes retained agents drop from their queue
109
 
110
 
111
  @dataclass
tests/test_generator.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The generator: deterministic, held-out templates stay out of the public splits, and its knobs reach the tasks."""
2
+
3
+ import pytest
4
+
5
+ from reorgbench.gen import PUBLIC_SEEDS, TEMPLATES, Knobs, generate, generated_tasks
6
+ from reorgbench.gen.build import run_oracle
7
+ from reorgbench.gen.templates import PlanRetirement
8
+ from reorgbench.tasks.registry import all_tasks, get_task, get_tasks
9
+
10
+ GEN = generated_tasks("train")
11
+
12
+
13
+ def test_public_train_split_is_generated():
14
+ assert len(GEN) == PUBLIC_SEEDS * len([t for t in TEMPLATES.values() if t.split == "train"]) >= 200
15
+ assert set(GEN) == set(get_tasks("train"))
16
+ assert {t.template for t in GEN.values()} == {t.id for t in TEMPLATES.values() if t.split == "train"}
17
+
18
+
19
+ def test_same_seed_same_task():
20
+ a, b = generate("region-migration", 7), generate("region-migration", 7)
21
+ assert a.initial_objects == b.initial_objects and a.budgets == b.budgets
22
+ assert [p.goal for p in a.phases] == [p.goal for p in b.phases]
23
+ assert [p.staffings for p in a.phases] == [p.staffings for p in b.phases]
24
+ assert generate("region-migration", 8).initial_objects != a.initial_objects
25
+
26
+
27
+ def test_generated_ids_resolve_from_their_seed():
28
+ t = get_task("gen-overcharge-refund-0003")
29
+ assert t is not None and t.initial_objects == GEN["gen-overcharge-refund-0003"].initial_objects
30
+ assert get_task("gen-no-such-template-0001") is None
31
+
32
+
33
+ def test_held_out_templates_never_reach_the_public_splits():
34
+ class Private(PlanRetirement):
35
+ id, split = "private-plan-retirement", "test"
36
+
37
+ TEMPLATES[Private.id] = Private()
38
+ try:
39
+ t = generate(Private.id, 0)
40
+ assert t.split == "test" and t.template == Private.id
41
+ assert run_oracle(t).verdict.success
42
+ assert Private.id not in {x.template for x in all_tasks().values()}
43
+ assert generated_tasks("test", seeds=1) # what the leaderboard runner loads, outside this repo
44
+ finally:
45
+ del TEMPLATES[Private.id]
46
+
47
+
48
+ def test_every_change_kind_each_template_offers_shows_up():
49
+ for tpl in (t for t in TEMPLATES.values() if t.split == "train"):
50
+ seen = {c for t in GEN.values() if t.template == tpl.id for c in t.tags}
51
+ for kind in tpl.pool:
52
+ assert kind.lower().replace(":", "-") in seen, (tpl.id, kind)
53
+
54
+
55
+ def test_budgets_follow_the_tier():
56
+ """Budgets are a fixed multiple of the fastest careful plan: 1.5x for hard tasks, 3x for standard ones."""
57
+ for t in list(GEN.values())[::7]:
58
+ res = run_oracle(t)
59
+ assert res.verdict.success
60
+ mult = 1.5 if t.tier == "hard" else 3.0
61
+ assert t.budgets.round_cap == pytest.approx(mult * res.rounds, abs=1), t.id
62
+
63
+
64
+ def test_some_hard_tasks_need_several_agents_of_a_role():
65
+ """Volume plus a tight budget: no acceptable starting team has a single agent per role."""
66
+ need = [t for t in GEN.values() if t.tier == "hard"
67
+ and all(any(s.count(r) > 1 for r in set(s)) for s in t.phases[0].staffings)]
68
+ assert need
69
+
70
+
71
+ def test_explicit_knobs():
72
+ t = generate("plan-retirement", 1, Knobs(n=6, crew=1, changes=("CANCEL", "ADD:credit"), traps=3, code=True))
73
+ assert len(t.phases) == 3 and [i.change for i in t.interventions] == ["CANCEL", "ADD"]
74
+ assert {"n6", "cancel", "add-credit", "code"} <= set(t.tags)
75
+ assert run_oracle(t).verdict.success
tests/test_splits_reward.py CHANGED
@@ -38,11 +38,13 @@ def test_success_outranks_any_failure_with_shaping():
38
  assert reward(good.verdict, 0.9) > reward(bad.verdict, 0.9)
39
 
40
 
41
- def test_tiers_filter_and_hard_tasks_are_public_dev():
42
  hard = get_tasks(tier="hard")
43
- assert hard and all(t.tier == "hard" and t.split == "dev" for t in hard.values())
44
  assert set(hard) | set(get_tasks(tier="standard")) == set(all_tasks())
45
- assert set(get_tasks("dev", "hard")) == set(hard)
 
 
46
  with pytest.raises(ValueError):
47
  get_tasks(tier="extreme")
48
 
 
38
  assert reward(good.verdict, 0.9) > reward(bad.verdict, 0.9)
39
 
40
 
41
+ def test_tiers_filter_and_hard_tasks_are_public():
42
  hard = get_tasks(tier="hard")
43
+ assert hard and all(t.tier == "hard" and t.split in ("dev", "train") for t in hard.values())
44
  assert set(hard) | set(get_tasks(tier="standard")) == set(all_tasks())
45
+ # the hand-written hard tier is dev; generated hard tasks are train
46
+ assert {t.id for t in hard.values() if t.template == "hand"} == set(get_tasks("dev", "hard"))
47
+ assert get_tasks("train", "hard")
48
  with pytest.raises(ValueError):
49
  get_tasks(tier="extreme")
50