HassamGani commited on
Commit
fabe4fe
·
1 Parent(s): 4a65b70

Team chat and directory; exception approvals that need the right approver

Browse files
reorgbench/env/roles.py CHANGED
@@ -18,7 +18,7 @@ class Role:
18
  services: frozenset[str]
19
 
20
 
21
- SHARED_SERVICES = frozenset({"docs"})
22
 
23
  ROLES: dict[str, Role] = {
24
  r.name: r
 
18
  services: frozenset[str]
19
 
20
 
21
+ SHARED_SERVICES = frozenset({"docs", "chat"})
22
 
23
  ROLES: dict[str, Role] = {
24
  r.name: r
reorgbench/env/tools.py CHANGED
@@ -297,6 +297,48 @@ def _contracts_read(w: World, a: dict, log: AccessLog, rnd: int) -> dict:
297
  return {"error": "no such contract"} if d is None else {"contract_id": a["contract_id"], **d}
298
 
299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  def _t(name, service, desc, fn, params, optional=()):
301
  return Tool(name, service, desc, params, frozenset(optional), fn)
302
 
@@ -332,6 +374,10 @@ TOOLS: dict[str, Tool] = {
332
  _t("inbox.read", "vendor", "Read the procurement inbox.", _inbox_read, {}),
333
  _t("contracts.search", "contracts", "Search contracts by keyword.", _contracts_search, {"query": str}),
334
  _t("contracts.read", "contracts", "Read a contract.", _contracts_read, {"contract_id": str}),
 
 
 
 
335
  ]
336
  }
337
 
 
297
  return {"error": "no such contract"} if d is None else {"contract_id": a["contract_id"], **d}
298
 
299
 
300
+ # ---- team chat and the people directory (shared) ----------------------------------------------------------
301
+
302
+ CHAT_PER_PAGE = 20
303
+
304
+
305
+ def _chat_search(w: World, a: dict, log: AccessLog, rnd: int) -> dict:
306
+ q, ch = a["query"].lower(), a.get("channel")
307
+ out = []
308
+ for oid, d in w.iter("chat"):
309
+ text = " ".join([d["text"], *(r["text"] for r in d.get("replies", []))]).lower()
310
+ if (ch is None or d["channel"] == ch.lstrip("#")) and all(t in text for t in q.split()):
311
+ out.append((oid, {"thread_id": oid.split("/", 1)[1], "channel": d["channel"], "author": d["author"],
312
+ "date": d["date"], "preview": d["text"][:120]}))
313
+ page = _page(out, a, CHAT_PER_PAGE, "threads")
314
+ for oid, _ in page["threads"]:
315
+ log.read(oid)
316
+ page["threads"] = [t for _, t in page["threads"]]
317
+ return page
318
+
319
+
320
+ def _chat_read(w: World, a: dict, log: AccessLog, rnd: int) -> dict:
321
+ d = w.get(f"chat/{a['thread_id']}", log)
322
+ return {"error": "no such thread"} if d is None else {"thread_id": a["thread_id"], **d}
323
+
324
+
325
+ def _chat_post(w: World, a: dict, log: AccessLog, rnd: int) -> dict:
326
+ tid = w.next_id("chat", "TH-")
327
+ w.put(f"chat/{tid}", {"channel": a["channel"].lstrip("#"), "author": "(you)", "date": "2026-10-15",
328
+ "text": a["text"]}, log)
329
+ return {"ok": True, "thread_id": tid}
330
+
331
+
332
+ def _directory(w: World, a: dict, log: AccessLog, rnd: int) -> dict:
333
+ q = a["query"].lower()
334
+ out = []
335
+ for oid, d in w.iter("directory"):
336
+ if all(t in " ".join(str(v) for v in d.values()).lower() for t in q.split()):
337
+ log.read(oid)
338
+ out.append(dict(d))
339
+ return {"people": out[:25], "total": len(out)}
340
+
341
+
342
  def _t(name, service, desc, fn, params, optional=()):
343
  return Tool(name, service, desc, params, frozenset(optional), fn)
344
 
 
374
  _t("inbox.read", "vendor", "Read the procurement inbox.", _inbox_read, {}),
375
  _t("contracts.search", "contracts", "Search contracts by keyword.", _contracts_search, {"query": str}),
376
  _t("contracts.read", "contracts", "Read a contract.", _contracts_read, {"contract_id": str}),
377
+ _t("chat.search", "chat", f"Search team chat threads by keywords (all must appear), optionally in one channel. Returns up to {CHAT_PER_PAGE} a call with the total; when there are more, pass next_offset as offset for the next page.", _chat_search, {"query": str, "channel": str, "offset": int, "limit": int}, ["channel", "offset", "limit"]),
378
+ _t("chat.read", "chat", "Read a team chat thread with its replies.", _chat_read, {"thread_id": str}),
379
+ _t("chat.post", "chat", "Start a thread in a team chat channel.", _chat_post, {"channel": str, "text": str}),
380
+ _t("directory.lookup", "chat", "Look people up in the company directory by name, title or team.", _directory, {"query": str}),
381
  ]
382
  }
383
 
reorgbench/gen/build.py CHANGED
@@ -77,6 +77,8 @@ class Gen:
77
  held: list[str] = field(default_factory=list) # active, matching, but a contract keeps them where they are
78
  claims: list[tuple[str, str]] = field(default_factory=list) # (customer, contract) a ticket cites
79
  holds: list[str] = field(default_factory=list) # on a collections hold for non-payment: no credits
 
 
80
  expired: list[str] = field(default_factory=list) # cite a contract that has run out: treated like everyone
81
  disputed: list[str] = field(default_factory=list) # on hold over a disputed invoice: credits still allowed
82
  merged: list[tuple[str, str]] = field(default_factory=list) # (customer, the old ticket merged into a new one)
@@ -266,6 +268,14 @@ def careful_reads(g: Gen, b: PhaseBuilder) -> None:
266
  for label, steps in b.steps.items():
267
  role = role_of_label(label)
268
  pre = [Step("docs.read", {"doc_id": d}) for d in ["operations-handbook", "policy-updates", *reads.get(role, [])]]
 
 
 
 
 
 
 
 
269
  if role == "support":
270
  mine = [c for c in g.chunk(label) if c in g.in_scope]
271
  if label == "support":
@@ -687,6 +697,18 @@ def mutants(g: Gen, cancel_id: str | None) -> list[Mutant]:
687
  m = u["moved"]
688
  out.append(Mutant("others_untouched", "wrong", "a customer under contract moved",
689
  set_row(h, **{m.field_name: m.target})))
 
 
 
 
 
 
 
 
 
 
 
 
690
  if cancel_id and len(scope) < len(g.cohort):
691
  x0, x1 = g.excluded[0], g.excluded[-1]
692
  tell = g.template.tell_text(g, x0, "100")
 
77
  held: list[str] = field(default_factory=list) # active, matching, but a contract keeps them where they are
78
  claims: list[tuple[str, str]] = field(default_factory=list) # (customer, contract) a ticket cites
79
  holds: list[str] = field(default_factory=list) # on a collections hold for non-payment: no credits
80
+ approved_out: list[str] = field(default_factory=list) # left out by an approved exception
81
+ not_approved: list[str] = field(default_factory=list) # asked to be left out, but the approval doesn't count
82
  expired: list[str] = field(default_factory=list) # cite a contract that has run out: treated like everyone
83
  disputed: list[str] = field(default_factory=list) # on hold over a disputed invoice: credits still allowed
84
  merged: list[tuple[str, str]] = field(default_factory=list) # (customer, the old ticket merged into a new one)
 
268
  for label, steps in b.steps.items():
269
  role = role_of_label(label)
270
  pre = [Step("docs.read", {"doc_id": d}) for d in ["operations-handbook", "policy-updates", *reads.get(role, [])]]
271
+ if role in ("analyst", "support", "finance") and "#" not in label:
272
+ threads = [o.split("/", 1)[1] for o, d in g.objects.items() if o.startswith("chat/")
273
+ and d["channel"] == "approvals" and "leave" in d["text"]]
274
+ names = sorted({r["author"] for o, d in g.objects.items() if o.startswith("chat/")
275
+ and d["channel"] == "approvals" and "leave" in d["text"] for r in d["replies"]})
276
+ pre += [Step("chat.search", {"query": "leave", "channel": "approvals"})]
277
+ pre += [Step("chat.read", {"thread_id": t}) for t in threads]
278
+ pre += [Step("directory.lookup", {"query": n}) for n in names]
279
  if role == "support":
280
  mine = [c for c in g.chunk(label) if c in g.in_scope]
281
  if label == "support":
 
697
  m = u["moved"]
698
  out.append(Mutant("others_untouched", "wrong", "a customer under contract moved",
699
  set_row(h, **{m.field_name: m.target})))
700
+ for c in g.approved_out[:1]:
701
+ out.append(Mutant("held_not_told", "wrong", "a customer with an approved exception sent the notice",
702
+ add_reply(c, g.template.tell_text(g, c, str(n.value(acc[c].seats))))))
703
+ if "moved" in u:
704
+ m = u["moved"]
705
+ for c in [c for c in g.not_approved if c in scope and str(acc[c].row[m.field_name]).lower()
706
+ != str(m.target).lower()][:1]:
707
+ out.append(Mutant(m.ck, "wrong", "a customer whose exception wasn't validly approved left as it was",
708
+ set_row(c, **{m.field_name: acc[c].row[m.field_name]})))
709
+ for c in [c for c in g.not_approved if c in scope][:1]:
710
+ out.append(Mutant(n.ck, "wrong", "a customer whose exception wasn't validly approved never told",
711
+ lambda w, v, c=c: set_replies(w, acc[c].ticket, [])))
712
  if cancel_id and len(scope) < len(g.cohort):
713
  x0, x1 = g.excluded[0], g.excluded[-1]
714
  tell = g.template.tell_text(g, x0, "100")
reorgbench/gen/company.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The company around a messy task: people and who may approve what, team chat with its everyday noise, and
2
+ exception requests in #approvals. Some exceptions are approved by someone who can approve them, some by someone
3
+ who can't, and some approvals have lapsed; only the first kind changes the work."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+ _FIRST = ["Dana", "Priya", "Marcus", "Elena", "Tomas", "Aisha", "Jonah", "Mei", "Rafael", "Ingrid", "Kwame", "Lucia",
10
+ "Owen", "Sana", "Felix", "Noor", "Hugo", "Yara", "Caleb", "Ines", "Ravi", "Greta", "Malik", "Chloe", "Emeka",
11
+ "Saoirse", "Arjun", "Leila", "Bruno", "Tess"]
12
+ _LAST = ["Whitfield", "Okafor", "Lindqvist", "Moreau", "Haddad", "Tanaka", "Brennan", "Castillo", "Novak", "Achterberg",
13
+ "Mensah", "Ferreira", "Kowalski", "Rahman", "Duarte", "Sato", "Ellery", "Varga", "Oyelaran", "Petrov",
14
+ "Quinlan", "Abara", "Holm", "Iyer", "Marchetti", "Szabo", "Delacroix", "Nakamura", "Osei", "Brandt"]
15
+
16
+ APPROVERS = ("VP of Customer Success", "Chief Financial Officer")
17
+ # titles that sound senior but can't approve exceptions to a rollout
18
+ NOT_APPROVERS = ("Head of Support", "Director of Sales", "Senior Account Executive", "Support Team Lead",
19
+ "Finance Manager")
20
+ _STAFF = ("Support Agent", "Support Agent", "Billing Specialist", "Site Reliability Engineer", "Software Engineer",
21
+ "Account Executive", "Legal Counsel", "Procurement Specialist", "Data Analyst", "Customer Success Manager")
22
+ _TEAM = {"Support": "Support", "Billing": "Finance", "Site": "Engineering", "Software": "Engineering",
23
+ "Account": "Sales", "Legal": "Legal", "Procurement": "Operations", "Data": "Operations",
24
+ "Customer": "Customer Success", "VP": "Customer Success", "Chief": "Finance", "Head": "Support",
25
+ "Director": "Sales", "Senior": "Sales", "Finance": "Finance"}
26
+
27
+ _NOISE = [
28
+ ("support", "Reminder: the macro for password resets was updated, please use the new one."),
29
+ ("support", "Anyone else seeing slow ticket search this morning?"),
30
+ ("finance", "Month-end close starts Friday. Get invoice corrections in by Thursday."),
31
+ ("finance", "Approved the Q4 travel budget, thanks all."),
32
+ ("eng", "Deploy freeze lifts at 14:00. Ping me if you have something urgent."),
33
+ ("eng", "CI flake in the export tests is fixed on main."),
34
+ ("general", "Lunch and learn on Thursday: our new incident process."),
35
+ ("general", "Welcome to the three new starters in Support this week!"),
36
+ ("approvals", "Approved: purchase order for the new laptops (12 units)."),
37
+ ("approvals", "Approved: waive the late fee on the Nimbus renewal invoice, one-off."),
38
+ ]
39
+
40
+
41
+ def people(g) -> dict[str, dict[str, Any]]:
42
+ """The directory: one person per approver and non-approver title, plus staff."""
43
+ rng, used, out = g.rng, set(), {}
44
+ titles = list(APPROVERS) + list(NOT_APPROVERS) + list(_STAFF)
45
+ for i, title in enumerate(titles, 1):
46
+ while True:
47
+ name = f"{rng.choice(_FIRST)} {rng.choice(_LAST)}"
48
+ if name not in used:
49
+ used.add(name)
50
+ break
51
+ p = {"name": name, "title": title, "team": _TEAM[title.split()[0]],
52
+ "email": name.lower().replace(" ", ".") + "@company.example"}
53
+ out[title] = p
54
+ g.objects[f"directory/P-{100 + i}"] = p
55
+ g.leave_alone.append(f"directory/P-{100 + i}")
56
+ return out
57
+
58
+
59
+ def _thread(g, channel: str, author: str, date: str, text: str, replies: list[tuple[str, str, str]]) -> str:
60
+ tid = g.ids.new("TH-", 1000, 9999)
61
+ g.objects[f"chat/{tid}"] = {"channel": channel, "author": author, "date": date, "text": text,
62
+ "replies": [{"author": a, "date": d, "text": t} for a, d, t in replies]}
63
+ g.leave_alone.append(f"chat/{tid}")
64
+ return tid
65
+
66
+
67
+ def chatter(g, who: dict[str, dict[str, Any]]) -> None:
68
+ rng = g.rng
69
+ staff = [p["name"] for p in who.values()]
70
+ for channel, text in _NOISE:
71
+ _thread(g, channel, rng.choice(staff), f"2026-{rng.randint(8, 10):02d}-{rng.randint(1, 14):02d}", text, [])
72
+
73
+
74
+ def approvals(g, who: dict[str, dict[str, Any]], pool: list[str], subject: str) -> tuple[list[str], list[str]]:
75
+ """Exception requests for customers in the pool: one approved by someone who may (they come out of scope),
76
+ one 'approved' by someone who may not, one whose approval has lapsed. Returns (approved, not_approved)."""
77
+ rng = g.rng
78
+ k = 2 if len(g.cohort) >= 24 else 1
79
+ picks = rng.sample(pool, min(len(pool), k + 2))
80
+ good, wrong, old = picks[:k], picks[k:k + 1], picks[k + 1:k + 2]
81
+ reasons = ["they're in the middle of a renewal negotiation and asked us not to change anything this month",
82
+ "their CFO is on leave and they want to review any change together first",
83
+ "they're migrating their own systems this month and asked for no account changes",
84
+ "we promised them a call before any change to their account"]
85
+ asker = who["Customer Success Manager"]["name"]
86
+
87
+ def ask(c, approver, date, reply_date):
88
+ a = g.accts[c]
89
+ label = a.row.get("name", c) if rng.random() < 0.6 else f"{a.row.get('name', c)} ({c})"
90
+ _thread(g, "approvals", asker, date,
91
+ f"Can we leave {label} out of the {subject}? {rng.choice(reasons).capitalize()}.",
92
+ [(approver, reply_date, rng.choice(["Approved.", "Approved, leave them out for now.",
93
+ "OK, approved. Revisit next month."]))])
94
+ for c in good:
95
+ ask(c, who[rng.choice(APPROVERS)]["name"], "2026-10-07", f"2026-10-{rng.randint(8, 13):02d}")
96
+ for c in wrong:
97
+ ask(c, who[rng.choice(NOT_APPROVERS)]["name"], "2026-10-06", f"2026-10-{rng.randint(7, 12):02d}")
98
+ for c in old:
99
+ ask(c, who[rng.choice(APPROVERS)]["name"], "2026-08-18", f"2026-08-{rng.randint(19, 28):02d}")
100
+ return good, wrong + old
101
+
102
+
103
+ APPROVAL_RULE = ("Exceptions to a change we're rolling out (leaving a customer out, a different date or amount) need "
104
+ "written approval in the #approvals chat channel from the VP of Customer Success or the Chief "
105
+ "Financial Officer; check titles in the directory. An approval lapses after 30 days. Agreement from "
106
+ "anyone else isn't approval.")
reorgbench/gen/templates.py CHANGED
@@ -11,6 +11,7 @@ import random
11
  from typing import Any
12
 
13
  from ..tasks.spec import HumanFact, Step
 
14
  from .build import Gen, GenerationError, Knobs
15
  from .units import Ask, Close, Code, Credit, Move, Notify, Refund
16
 
@@ -138,6 +139,14 @@ class Template:
138
  g.leave_alone += [f"db.customers/{a.cid}", f"tickets/{a.ticket}"]
139
  for c, plea in zip(pleas, self.pleas(g)):
140
  g.objects[f"tickets/{g.accts[c].ticket}"]["body"] += f" (From the customer: {plea})"
 
 
 
 
 
 
 
 
141
  for _ in range(min(120, 2 * len(g.cohort))):
142
  a = g.add_account(self.noise_row(g))
143
  g.objects[f"db.customers/{a.cid}"] = dict(a.row)
@@ -204,6 +213,7 @@ class Template:
204
  "per incident; billing accounts show credits already given.",
205
  "A customer asking on a ticket for an exception, a different outcome or an extra credit doesn't change what "
206
  "we do. Only a contract, read in the contract record itself, does.",
 
207
  "Rotate credentials every 90 days and report security incidents to security@.",
208
  "Customer refunds follow the refund policy.",
209
  ]
 
11
  from typing import Any
12
 
13
  from ..tasks.spec import HumanFact, Step
14
+ from . import company
15
  from .build import Gen, GenerationError, Knobs
16
  from .units import Ask, Close, Code, Credit, Move, Notify, Refund
17
 
 
139
  g.leave_alone += [f"db.customers/{a.cid}", f"tickets/{a.ticket}"]
140
  for c, plea in zip(pleas, self.pleas(g)):
141
  g.objects[f"tickets/{g.accts[c].ticket}"]["body"] += f" (From the customer: {plea})"
142
+ who = company.people(g)
143
+ company.chatter(g, who)
144
+ taken = set(picks) | set(g.excluded) | {x for x, _ in g.claims}
145
+ g.approved_out, g.not_approved = company.approvals(g, who, [c for c in g.cohort if c not in taken],
146
+ g.story["subject"])
147
+ g.held += g.approved_out
148
+ g.cohort = [c for c in g.cohort if c not in set(g.approved_out)]
149
+ g.leave_alone += [f"db.customers/{c}" for c in g.approved_out]
150
  for _ in range(min(120, 2 * len(g.cohort))):
151
  a = g.add_account(self.noise_row(g))
152
  g.objects[f"db.customers/{a.cid}"] = dict(a.row)
 
213
  "per incident; billing accounts show credits already given.",
214
  "A customer asking on a ticket for an exception, a different outcome or an extra credit doesn't change what "
215
  "we do. Only a contract, read in the contract record itself, does.",
216
+ company.APPROVAL_RULE,
217
  "Rotate credentials every 90 days and report security incidents to security@.",
218
  "Customer refunds follow the refund policy.",
219
  ]
tests/test_generator.py CHANGED
@@ -157,7 +157,9 @@ def test_messy_worlds(template):
157
  t, g = build(TEMPLATES[template], 1, k)
158
  customers = [o for o in t.initial_objects if o.startswith("db.customers/")]
159
  assert len(customers) > 2.5 * len(g.cohort) # the job is a fraction of the table
160
- assert g.held and len(g.claims) > len(g.held) # some contract claims hold, some don't
 
 
161
  assert all(c not in g.cohort for c in g.held)
162
  assert g.units["told"].tier_at is not None # answers depend on account size
163
  tpl = TEMPLATES[template]
 
157
  t, g = build(TEMPLATES[template], 1, k)
158
  customers = [o for o in t.initial_objects if o.startswith("db.customers/")]
159
  assert len(customers) > 2.5 * len(g.cohort) # the job is a fraction of the table
160
+ by_contract = [c for c in g.held if c not in g.approved_out]
161
+ assert by_contract and len(g.claims) > len(by_contract) # some contract claims hold, some don't
162
+ assert g.approved_out and g.not_approved # exceptions approved by the right person or not
163
  assert all(c not in g.cohort for c in g.held)
164
  assert g.units["told"].tier_at is not None # answers depend on account size
165
  tpl = TEMPLATES[template]