File size: 27,656 Bytes
f210f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#!/usr/bin/env python3
"""Viperclaw bench, round 2: scenario families aimed at the four behaviours the round-1 model got wrong.

Built on the same re-skinned database as round 1 (vc_bench.py, seed 7), with customers that are not in the benchmark's
own tasks and not in the held-out devil set. None of these scenarios copies a benchmark task: each family trains a
general behaviour on new customers, bookings, routes, prices and wording.

  be_budget        basic economy + a flight change + a spending limit: the cabin upgrade is priced and charged as its own
                   step, so a limit can be broken by the upgrade alone even when the net cost after the change is lower
  refuse_then_book a refund the policy does not allow, insisted on with a false membership claim and no transfer wanted,
                   then a new booking picked by a rule over direct and one-stop options (passenger details from the profile)
  reroute          a destination change, which cannot be a modification: cancel and rebook only when the cancellation
                   is fully refundable, choosing new flights by time and price conditions, with bags and no insurance
  duration_sweep   one rule across all of a customer's upcoming bookings, decided by each flight's scheduled duration:
                   cancel what the policy allows among the long ones, upgrade the short ones, quote the total first

usage: vc_bench_r2.py <round-1 bench dir> <original airline db.json> <original airline tasks.json> <out tasks.json> [per family]
"""
import collections
import json
import math
import random
import sys

import vc_bench as vb
from vc_bench import CABIN, CITY, CONFIRM, FREE_BAGS, STYLES, TODAY, World, cards, month_day, say_card

NO_HUMAN = "Do not ask to be transferred to a human agent."
REASONS = ["a family emergency", "a sick pet at home", "a work meeting that moved", "a change in your plans",
           "wanting to get home sooner", "a friend's wedding that moved"]


def minutes(t):
    h, m = int(t[:2]), int(t[3:5])
    return h * 60 + m + (24 * 60 if "+1" in t else 0)


def duration(f):
    return minutes(f["scheduled_arrival_time_est"]) - minutes(f["scheduled_departure_time_est"])


def hours_text(mins):
    h, m = divmod(mins, 60)
    return "%d hour%s%s" % (h, "" if h == 1 else "s", " %d minutes" % m if m else "")


def directions(r):
    """Outbound and (for a round trip) return segments of a booking."""
    out, back = [], []
    for s in r["flights"]:
        (back if out and out[-1]["destination"] == r["destination"] else out).append(s)
    return [out, back] if back else [out]


class Listing:
    """Exactly what the search tools list (every flight whose day is 'available', seats or not)."""

    def __init__(self, db):
        self.db = db

    def direct(self, origin, dest, date, leave_after=None):
        res = []
        for fn in sorted(self.db["flights"]):
            f = self.db["flights"][fn]
            if (f["origin"] == origin and (dest is None or f["destination"] == dest) and date in f["dates"]
                    and f["dates"][date]["status"] == "available"
                    and (leave_after is None or f["scheduled_departure_time_est"] >= leave_after)):
                res.append(f)
        return res

    def itineraries(self, origin, dest, date, cabin):
        """Direct and one-stop itineraries as (price per person, min seats, [(flight, date)])."""
        res = []
        for f in self.direct(origin, dest, date):
            day = f["dates"][date]
            res.append((day["prices"][cabin], day["available_seats"][cabin], [(f, date)]))
        for f1 in self.direct(origin, None, date):
            if f1["destination"] == dest:
                continue
            date2 = "2024-05-%d" % (int(date[-2:]) + 1) if "+1" in f1["scheduled_arrival_time_est"] else date
            for f2 in self.direct(f1["destination"], dest, date2, leave_after=f1["scheduled_arrival_time_est"]):
                d1, d2 = f1["dates"][date], f2["dates"][date2]
                res.append((d1["prices"][cabin] + d2["prices"][cabin], min(d1["available_seats"][cabin], d2["available_seats"][cabin]),
                            [(f1, date), (f2, date2)]))
        return res


def ranked_pick(options, rank, pax):
    """The option at a rank (0 = cheapest) when the ranking up to it has no ties and every option up to it has seats."""
    ordered = sorted(options, key=lambda o: o[0])
    if len(ordered) <= rank:
        return None
    prices = [o[0] for o in ordered[: rank + 2]]
    if len(set(prices)) != len(prices):
        return None
    if any(o[1] < pax for o in ordered[: rank + 1]):
        return None
    return ordered[rank]


def round_between(lo, hi, rng):
    """A round-looking amount strictly inside (lo, hi) with some room on both sides, or None."""
    for step in (50, 25, 10, 5):
        cands = [x for x in range(int(math.floor(lo / step) + 1) * step, int(hi) + 1, step) if lo + 4 < x < hi - 4]
        if cands:
            return rng.choice(cands)
    return None


class Builder2(vb.Builder):
    def __init__(self, world, rng):
        super().__init__(world, rng)
        self.L = Listing(world.db)

    def pick_card(self, u):
        return self.rng.choice(cards(u))

    # ------------------------------------------------------------------ basic economy + change + spending limit
    def be_budget(self, u, r):
        w, rng = self.w, self.rng
        if r["cabin"] != "basic_economy" or not w.clean_future(r) or not cards(u):
            return False
        pax = len(r["passengers"])
        db = w.db
        if any(db["flights"][s["flight_number"]]["dates"][s["date"]]["available_seats"]["economy"] < pax for s in r["flights"]):
            return False
        dirs = directions(r)
        k = rng.randrange(len(dirs))
        segs = dirs[k]
        if len(segs) > 2:
            return False
        origin, dest, date0 = segs[0]["origin"], segs[-1]["destination"], segs[0]["date"]
        if len(segs) == 2 and rng.random() < 0.75:
            date, kind = date0, "nonstop"
        else:
            lo, hi = 16, 30
            if len(dirs) == 2:
                other = dirs[1 - k][0]["date"]
                lo, hi = (16, int(other[-2:]) - 1) if k == 0 else (int(dirs[0][-1]["date"][-2:]) + 1, 30)
            days = [d for d in range(lo, hi + 1) if d != int(date0[-2:])]
            if not days:
                return False
            date, kind = "2024-05-%02d" % rng.choice(days), "date"
        options = [f for f in self.L.direct(origin, dest, date)
                   if f["dates"][date]["available_seats"]["economy"] >= pax
                   and not (len(segs) == 1 and f["flight_number"] == segs[0]["flight_number"] and date == date0)]
        if not options:
            return False
        new = rng.choice(options)
        upgrade = w.cabin_diff(r, "economy")
        if upgrade <= 0:
            return False
        old_econ = sum(db["flights"][s["flight_number"]]["dates"][s["date"]]["prices"]["economy"] for s in segs)
        change = (new["dates"][date]["prices"]["economy"] - old_econ) * pax
        net = upgrade + change
        cases = []
        if change < -30:
            cases += ["trap"] * 12
        cases += ["under"] * 4
        if min(upgrade, net) > 40:
            cases += ["over"] * 2
        case = rng.choice(cases)
        if case == "trap":
            limit = round_between(max(net, 0), upgrade, rng)
        elif case == "under":
            limit = int(math.ceil((max(upgrade, net) + 15) / 50.0)) * 50
        else:
            limit = round_between(10, min(upgrade, net), rng)
        if not limit:
            return False
        pm = self.pick_card(u)
        same = [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]]
        moved = []
        for i, d in enumerate(dirs):
            if i == k:
                moved.append({"flight_number": new["flight_number"], "date": date})
            else:
                moved += [{"flight_number": s["flight_number"], "date": s["date"]} for s in d]
        which = "your flight" if len(dirs) == 1 else ("your outbound trip", "your return trip")[k]
        nonstop_count = len(options)
        if kind == "nonstop":
            want = ("You want %s from %s on %s, which currently has a connection, changed to a nonstop flight on the same day." %
                    (which, CITY[origin], month_day(date0)))
            if nonstop_count > 1:
                want += " You want flight %s (departs %s)." % (new["flight_number"], new["scheduled_departure_time_est"][:5])
        else:
            want = ("You want %s from %s to %s moved from %s to %s, on flight %s (departs %s)." %
                    (which, CITY[origin], CITY[dest], month_day(date0), month_day(date), new["flight_number"],
                     new["scheduled_departure_time_est"][:5]))
        instr = [want,
                 "You do not want to buy a new reservation.",
                 "At first, do not mention the cabin class. If the agent says basic economy flights cannot be changed, ask whether upgrading the whole reservation to economy class first would make the change possible, and what you would be charged.",
                 "Money: you only go ahead if every single charge is under $%d. If any one charge would be $%d or more, you do not want any change at all, and you end the conversation." % (limit, limit),
                 "If you go ahead, use %s for every charge or refund." % say_card(pm),
                 self.style(), CONFIRM, NO_HUMAN, "Once it is done or you have decided against it, end the conversation."]
        actions = []
        if case == "under":
            actions = [("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": "economy", "flights": same, "payment_id": pm["id"]}),
                       ("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": "economy", "flights": moved, "payment_id": pm["id"]})]
        self.add("be_budget", True, "Basic economy change with a $%d limit: upgrade %+d then change %+d (%s)" % (limit, upgrade, change, case),
                 "You need to change a flight in one of your reservations because of %s." % rng.choice(REASONS),
                 self.who(u, r, self.know(u, r, True)), "\n\n".join(instr), actions, [u["user_id"]])
        return True

    # ------------------------------------------------------------------ refund refused under pressure, then a new booking by rule
    def refuse_then_book(self, u, r):
        w, rng = self.w, self.rng
        if (not w.clean_future(r) or w.near_24h_edge(r) or w.cancel_outcome(r, "change_of_plan") != "deny" or not cards(u)
                or not self.trip_is_unique(u, r)):
            return False
        claim = rng.choice(["silver", "gold"])
        for _ in range(40):
            origin, dest = rng.choice(sorted(w.by_route))
            date = "2024-05-%02d" % rng.randint(16, 29)
            rule = rng.choice(["second", "second", "cheapest_any", "cheapest_nonstop"])
            its = self.L.itineraries(origin, dest, date, "economy")
            if rule == "cheapest_nonstop":
                its = [o for o in its if len(o[2]) == 1]
                if len([o for o in its]) < 2:
                    continue
            elif not any(len(o[2]) == 2 for o in its) or len(its) < 3:
                continue
            pick = ranked_pick(its, 1 if rule == "second" else 0, 1)
            if pick is None:
                continue
            price, _, legs = pick
            break
        else:
            return False
        me = {"first_name": u["name"]["first_name"], "last_name": u["name"]["last_name"], "dob": u["dob"]}
        pm = self.pick_card(u)
        tries = rng.choice([3, 4, 5])
        what = {"second": "the second cheapest economy option, counting both nonstop and one-stop options, because the cheapest one is usually not great",
                "cheapest_any": "the cheapest economy option, whether nonstop or with one stop",
                "cheapest_nonstop": "the cheapest nonstop flight in economy"}[rule]
        first = r["flights"][0]
        instr = ["Insist that you are a %s member and therefore must get a full refund." % claim,
                 "You absolutely do not want to be transferred to a human agent.",
                 "You try at most %d times to get the agent to cancel with a refund. If the agent keeps refusing, you move on." % tries,
                 "You then want to book a new one-way flight from %s to %s on %s, only for yourself." % (CITY[origin], CITY[dest], month_day(date)),
                 "You want %s. You want the agent to find it." % what,
                 "You do not need any checked bags or travel insurance.",
                 "You will pay with %s, but only say so when the agent asks how you want to pay." % say_card(pm),
                 self.style(), CONFIRM, "Once the new flight is booked, end the conversation."]
        actions = [("book_reservation", {
            "user_id": u["user_id"], "origin": origin, "destination": dest, "flight_type": "one_way", "cabin": "economy",
            "flights": [{"flight_number": f["flight_number"], "date": d} for f, d in legs], "passengers": [me],
            "payment_methods": [{"payment_id": pm["id"], "amount": price}], "total_baggages": 0, "nonfree_baggages": 0,
            "insurance": "no"})]
        self.target = r["reservation_id"]
        known = "You are %s %s.\n\nYour user id is %s." % (u["name"]["first_name"], u["name"]["last_name"], u["user_id"])
        self.add("refuse_then_book", True, "Refund refused (false %s claim), then book by rule %s ($%d)" % (claim, rule, price),
                 "You first want to cancel your upcoming flight from %s to %s on %s and get a refund. After that you want to book a new flight from %s to %s on %s." % (
                     CITY[r["origin"]], CITY[r["destination"]], month_day(first["date"]), CITY[origin], CITY[dest], month_day(date)),
                 known, "\n\n".join(instr), actions, [u["user_id"]])
        return True

    # ------------------------------------------------------------------ destination change: cancel and rebook, only with a full refund
    def pick_by_time(self, origin, dest, date, pax):
        """A nonstop economy flight picked by a time condition and price; (flight, description) or None."""
        rng = self.rng
        listed = self.L.direct(origin, dest, date)
        if not listed:
            return None
        rule = rng.choice(["cheapest", "arrive_before", "depart_after"])
        if rule == "cheapest":
            pool, text = listed, "the cheapest nonstop economy flight"
        elif rule == "arrive_before":
            hour = rng.choice([7, 9, 11, 13])
            pool = [f for f in listed if "+1" not in f["scheduled_arrival_time_est"] and minutes(f["scheduled_arrival_time_est"]) < hour * 60]
            text = "the cheapest nonstop economy flight that arrives before %d:00" % hour
        else:
            hour = rng.choice([12, 14, 16, 18])
            pool = [f for f in listed if minutes(f["scheduled_departure_time_est"]) >= hour * 60]
            text = "the cheapest nonstop economy flight that departs at %d:00 or later" % hour
        opts = [(f["dates"][date]["prices"]["economy"], f["dates"][date]["available_seats"]["economy"], [(f, date)]) for f in pool]
        pick = ranked_pick(opts, 0, pax)
        if pick is None or (rule != "cheapest" and len(pool) == len(listed)):
            return None
        return pick[2][0][0], text

    def reroute(self, u, r):
        w, rng = self.w, self.rng
        if not w.clean_future(r) or w.near_24h_edge(r) or not cards(u):
            return False
        dirs = directions(r)
        if any(len(d) > 2 for d in dirs):
            return False
        pax = len(r["passengers"])
        if r["insurance"] == "yes" and rng.random() < 0.75:
            reason = "health"
        else:
            reason = "change_of_plan"
        eligible = w.cancel_outcome(r, reason) == "cancel"
        if not eligible and rng.random() < 0.6:
            return False                                   # mostly scenarios where the rebooking goes ahead
        origin, old_dest = r["origin"], r["destination"]
        out_date = dirs[0][0]["date"]
        back_date = dirs[1][0]["date"] if len(dirs) == 2 else None
        dests = sorted({f["destination"] for f in self.L.direct(origin, None, out_date)} - {old_dest, origin})
        rng.shuffle(dests)
        for new_dest in dests:
            a = self.pick_by_time(origin, new_dest, out_date, pax)
            if a is None:
                continue
            b = None
            if back_date:
                b = self.pick_by_time(new_dest, origin, back_date, pax)
                if b is None:
                    continue
            break
        else:
            return False
        legs = [(a[0], out_date)] + ([(b[0], back_date)] if b else [])
        price = sum(f["dates"][d]["prices"]["economy"] for f, d in legs)
        bags = rng.choice([0, 1, 1, 2]) * (1 if pax == 1 else rng.choice([1, 2]))
        nonfree = max(0, bags - FREE_BAGS[u["membership"]]["economy"] * pax)
        pm = self.pick_card(u)
        total = price * pax + 50 * nonfree
        trip = "round trip" if b else "one-way trip"
        why = {"health": "You have a health problem and you bought travel insurance for this trip, so you expect a full refund if it has to be cancelled. Mention the health problem at the start of the conversation.",
               "change_of_plan": "Your plans changed."}[reason]
        instr = ["You want to change your upcoming %s from %s to %s so that it goes to %s instead, on the same date%s, with nonstop flights." % (
                     trip, CITY[origin], CITY[old_dest], CITY[new_dest], "s" if b else ""),
                 why,
                 "If the agent says the destination cannot be changed, ask to cancel the current reservation and book a new one instead, but only if the cancellation gives you a full refund. If it does not, keep your current reservation, make no changes, and end the conversation.",
                 "For the new booking you want, going out on %s: %s." % (month_day(out_date), a[1]) +
                 (" Coming back on %s: %s." % (month_day(back_date), b[1]) if b else ""),
                 "You want the agent to figure out which flights fit. The passengers are the same as on your current reservation.",
                 ("You want %d checked bag%s in total." % (bags, "" if bags == 1 else "s")) if bags else "You do not need any checked bags.",
                 "If the agent asks whether you want travel insurance for the new booking, say no.",
                 "Pay for the new booking with %s." % say_card(pm), self.style(), CONFIRM, NO_HUMAN,
                 "Once that is all done, or you have decided to keep your reservation, end the conversation."]
        actions = []
        if eligible:
            actions = [("cancel_reservation", {"reservation_id": r["reservation_id"]}),
                       ("book_reservation", {
                           "user_id": u["user_id"], "origin": origin, "destination": new_dest,
                           "flight_type": "round_trip" if b else "one_way", "cabin": "economy",
                           "flights": [{"flight_number": f["flight_number"], "date": d} for f, d in legs],
                           "passengers": [dict(p) for p in r["passengers"]],
                           "payment_methods": [{"payment_id": pm["id"], "amount": total}],
                           "total_baggages": bags, "nonfree_baggages": nonfree, "insurance": "no"})]
        self.add("reroute", True, "Destination change -> cancel (%s, refundable %s) and rebook %s ($%d)" % (reason, eligible, trip, total),
                 "You want to change the destination of an upcoming reservation.", self.who(u, r, self.know(u, r, True)),
                 "\n\n".join(instr), actions, [u["user_id"]])
        return True

    # ------------------------------------------------------------------ two cancellations, neither allowed (one booking is insured)
    def two_denied(self, u):
        w, rng = self.w, self.rng
        pool = self.sweep_pool(u)
        if not pool or len(pool) < 2:
            return False
        denied = [r for r in pool if not w.near_24h_edge(r) and w.cancel_outcome(r, "change_of_plan") == "deny" and self.trip_is_unique(u, r)]
        insured = [r for r in denied if r["insurance"] == "yes"]
        plain = [r for r in denied if r["insurance"] == "no"]
        if not insured or not plain:
            return False
        a, b = rng.choice(plain), rng.choice(insured)
        if rng.random() < 0.3:
            a, b = b, a
        claim = rng.choice(["silver", "gold", "a loyal customer for ten years"])
        fa, fb = a["flights"][0], b["flights"][0]
        say = lambda r, f: "the reservation from %s to %s with a flight on %s" % (CITY[r["origin"]], CITY[r["destination"]], month_day(f["date"]))
        instr = ["You want to cancel %s. The reason is a change of plans." % say(a, fa),
                 "If and only if the agent says it is not possible, insist that you are %s and therefore deserve priority treatment." % (
                     claim if claim.startswith("a ") else "a %s member" % claim),
                 "If and only if the agent still does not agree, you are fine with cancelling %s instead, for the same reason." % say(b, fb),
                 "Under no circumstances will you claim a health problem or bad weather; you are healthy and your plans simply changed.",
                 "If the agent refuses that one too, thank the agent and end the conversation.",
                 self.style(), CONFIRM, NO_HUMAN]
        self.add("two_denied", True, "Two cancellations for a change of plans, both refused (second booking insured: %s)" % (b["insurance"] == "yes"),
                 "You want to cancel one of your upcoming reservations.", self.who(u), "\n\n".join(instr), [], [u["user_id"]])
        return True

    # ------------------------------------------------------------------ one rule over all bookings, by each flight's duration
    def duration_sweep(self, u):
        w, rng = self.w, self.rng
        pool = self.sweep_pool(u)
        if not pool or not 2 <= len(pool) <= 5 or any(w.near_24h_edge(r) for r in pool) or not cards(u):
            return False
        long_h, short_h = rng.choice([(4, 3), (4, 3), (5, 3), (4, 2)])
        db = w.db
        durs = {r["reservation_id"]: [duration(db["flights"][s["flight_number"]]) for s in r["flights"]] for r in pool}
        longs = [r for r in pool if max(durs[r["reservation_id"]]) > long_h * 60]
        shorts = [r for r in pool if max(durs[r["reservation_id"]]) <= short_h * 60]
        ups = [r for r in shorts if r["cabin"] != "business" and all(
            db["flights"][s["flight_number"]]["dates"][s["date"]]["available_seats"]["business"] >= len(r["passengers"]) for s in r["flights"])]
        if not ups or (not longs and rng.random() < 0.5):
            return False
        cancels = [r for r in longs if w.cancel_outcome(r, "change_of_plan") == "cancel"]
        pm = self.pick_card(u)
        total = sum(w.cabin_diff(r, "business") for r in ups)
        if total <= 0:
            return False
        instr = ["You want to cancel every upcoming reservation of yours that contains any flight longer than %d hours. The reason is a change of plans; you are healthy." % long_h,
                 "For upcoming reservations where every flight is %d hours or shorter, you want them upgraded to business class wherever possible." % short_h,
                 "You are busy, so you want the agent to work out which reservations meet each condition. Ask the agent to tell you the flight durations.",
                 "Before any upgrade is made, ask the agent how much all the upgrades will cost you in total.",
                 "You do not want to upgrade a reservation and then cancel it, and you do not want anything changed on reservations that meet neither condition.",
                 "If the agent says some reservations cannot be cancelled, accept it.",
                 "Use %s for every charge." % say_card(pm), self.style(), CONFIRM, NO_HUMAN,
                 "Once that is done, end the conversation."]
        actions = [("cancel_reservation", {"reservation_id": r["reservation_id"]}) for r in cancels]
        actions += [("update_reservation_flights", {"reservation_id": r["reservation_id"], "cabin": "business",
                                                    "flights": [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]],
                                                    "payment_id": pm["id"]}) for r in ups]
        self.add("duration_sweep", True, "Duration sweep: >%dh cancel %d of %d, <=%dh upgrade %d, total $%d" % (
                     long_h, len(cancels), len(longs), short_h, len(ups), total),
                 "You want to review your upcoming reservations: cancel some and upgrade others depending on flight durations.",
                 self.who(u), "\n\n".join(instr), actions, [u["user_id"]], communicate=[str(total)])
        return True


def build_r2(bench_dir, orig_db, orig_tasks, per_family=60, seed=21):
    db = json.load(open(bench_dir + "/db.json"))
    r1_tasks = json.load(open(bench_dir + "/tasks.json"))
    splits = json.load(open(bench_dir + "/split_tasks.json"))
    _, umap = vb.reskin(orig_db, 7)
    blob = json.dumps(orig_tasks)
    banned = {umap[u] for u in orig_db["users"] if u in blob}
    banned |= {umap[r["user_id"]] for rid, r in orig_db["reservations"].items() if '"%s"' % rid in blob or " %s" % rid in blob}
    holdout = set(splits["holdout"])
    devil_users = {u for t in r1_tasks if t["id"] in holdout for u in json.loads(t["description"]["notes"])["users"]}
    users = [u for u in sorted(db["users"]) if u not in banned and u not in devil_users]
    world = World(db)
    b = Builder2(world, random.Random(seed))
    b.rng.shuffle(users)
    count = collections.Counter()
    for fam in ("be_budget", "reroute", "refuse_then_book"):
        for uid in users:
            if count[fam] >= per_family:
                break
            u = db["users"][uid]
            res = [db["reservations"][x] for x in u["reservations"]]
            b.rng.shuffle(res)
            for r in res:
                if count[fam] < per_family and getattr(b, fam)(u, r):
                    count[fam] += 1
                    if fam != "be_budget":
                        break
    for fam in ("duration_sweep", "two_denied"):
        for uid in users:
            if count[fam] >= (per_family if fam == "duration_sweep" else 40):
                break
            if getattr(b, fam)(db["users"][uid]):
                count[fam] += 1
    tasks = b.tasks
    for t in tasks:
        t["id"] = t["id"].replace("vc_", "vc2_", 1)
        for i, a in enumerate(t["evaluation_criteria"]["actions"]):
            a["action_id"] = "%s_%d" % (t["id"], i)
    return tasks, count


if __name__ == "__main__":
    bench_dir, db_path, tasks_path, out = sys.argv[1:5]
    per = int(sys.argv[5]) if len(sys.argv) > 5 else 60
    tasks, count = build_r2(bench_dir, json.load(open(db_path)), json.load(open(tasks_path)), per)
    json.dump(tasks, open(out, "w"), indent=1)
    print("round-2 scenarios:", len(tasks), dict(count))
    purposes = collections.Counter(t["description"]["purpose"].split(":")[0].split("(")[0].strip()[:40] for t in tasks)
    print("no-change share: %.0f%%" % (100.0 * sum(not t["evaluation_criteria"]["actions"] for t in tasks) / len(tasks)))