README.md CHANGED
@@ -88,6 +88,26 @@ print(ds)
88
  print(ds["train"][0].keys())
89
  ```
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  ## Citation
92
 
93
  ```bibtex
@@ -120,4 +140,4 @@ Disallow: /
120
  We ask that:
121
  • You do *not* crawl, scrape, index, or download this dataset programmatically.
122
  • You do *not* use this dataset for training models or any automated processing
123
- without express permission from the dataset owner.
 
88
  print(ds["train"][0].keys())
89
  ```
90
 
91
+ ## Expose Workflow Labels (Inferred)
92
+ The public `tasks_and_rubrics.json` currently does not include per-task `workflow` labels, even though the paper describes workflow metadata.
93
+
94
+ This repo includes a helper script to expose inferred workflow labels for all three domains (Investment Banking, Management Consulting, Law):
95
+
96
+ ```bash
97
+ python3 scripts/expose_workflows.py
98
+ ```
99
+
100
+ Outputs:
101
+ - `tasks_and_rubrics_with_workflow.json` (original tasks plus inferred `workflow`)
102
+ - `workflow_inference_audit.csv` (task-level confidence/rank/signals for manual QA)
103
+
104
+ Method summary:
105
+ - Uses prompt/rubric/gold-response/file-name signals to score workflows per domain.
106
+ - Applies quota-constrained assignment so each domain’s workflow counts match Table 6 in the APEX–Agents paper.
107
+
108
+ Important:
109
+ - These are **inferred labels**, not official ground-truth workflow annotations from Mercor.
110
+
111
  ## Citation
112
 
113
  ```bibtex
 
140
  We ask that:
141
  • You do *not* crawl, scrape, index, or download this dataset programmatically.
142
  • You do *not* use this dataset for training models or any automated processing
143
+ without express permission from the dataset owner.
scripts/expose_workflows.py ADDED
@@ -0,0 +1,586 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Expose inferred workflow labels for APEX-Agents tasks.
3
+
4
+ The public `tasks_and_rubrics.json` includes `domain` metadata but omits
5
+ workflow/sub-task labels. This script infers per-domain workflows from task
6
+ text and task file names, then applies quota-constrained assignment so each
7
+ domain matches the workflow distribution reported in Table 6 of the paper.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import csv
14
+ import json
15
+ import math
16
+ import re
17
+ from collections import Counter, defaultdict
18
+ from pathlib import Path
19
+ from typing import DefaultDict
20
+
21
+ import numpy as np
22
+ from scipy.optimize import linear_sum_assignment
23
+
24
+
25
+ DOMAIN_WORKFLOW_QUOTAS = {
26
+ "Investment Banking": {
27
+ "Comparables": 16,
28
+ "DCF": 42,
29
+ "Debt Model": 6,
30
+ "LBO": 12,
31
+ "Market / Sector Research": 3,
32
+ "Merger Model": 7,
33
+ "Sensitivity Analysis": 46,
34
+ "Valuation Analysis": 28,
35
+ },
36
+ "Management Consulting": {
37
+ "Benchmarking / Competitive Analysis": 26,
38
+ "Cost Benefit Analysis": 11,
39
+ "Market Sizing, TAM, SAM": 14,
40
+ "Operations Analysis": 23,
41
+ "Scenario/Sensitivity Analysis": 35,
42
+ "Strategy Recommendations": 5,
43
+ "Survey / Interview Analysis": 31,
44
+ "Variance / Performance Analysis": 15,
45
+ },
46
+ "Law": {
47
+ "Compliance Program Review": 16,
48
+ "Contract Review": 30,
49
+ "Due Diligence": 18,
50
+ "Internal Investigations": 3,
51
+ "Legal Research": 47,
52
+ "Litigation Strategy": 8,
53
+ "Motion Drafting": 6,
54
+ "Risk Assessment": 24,
55
+ "Other": 8,
56
+ },
57
+ }
58
+
59
+
60
+ DOMAIN_BASE_PRIORS = {
61
+ "Investment Banking": {
62
+ "Comparables": 0.12,
63
+ "DCF": 0.25,
64
+ "Debt Model": 0.05,
65
+ "LBO": 0.12,
66
+ "Market / Sector Research": 0.05,
67
+ "Merger Model": 0.07,
68
+ "Sensitivity Analysis": 0.22,
69
+ "Valuation Analysis": 0.18,
70
+ },
71
+ "Management Consulting": {
72
+ "Benchmarking / Competitive Analysis": 0.18,
73
+ "Cost Benefit Analysis": 0.08,
74
+ "Market Sizing, TAM, SAM": 0.12,
75
+ "Operations Analysis": 0.16,
76
+ "Scenario/Sensitivity Analysis": 0.2,
77
+ "Strategy Recommendations": 0.06,
78
+ "Survey / Interview Analysis": 0.15,
79
+ "Variance / Performance Analysis": 0.12,
80
+ },
81
+ "Law": {
82
+ "Compliance Program Review": 0.1,
83
+ "Contract Review": 0.2,
84
+ "Due Diligence": 0.1,
85
+ "Internal Investigations": 0.1,
86
+ "Legal Research": 0.2,
87
+ "Litigation Strategy": 0.1,
88
+ "Motion Drafting": 0.1,
89
+ "Risk Assessment": 0.2,
90
+ "Other": 0.1,
91
+ },
92
+ }
93
+
94
+
95
+ # (signal_name, regex, weight)
96
+ DOMAIN_SIGNALS = {
97
+ "Investment Banking": {
98
+ "Comparables": [
99
+ ("comparables_term", r"\bcomparables?\b|\bcomps?\b|\bpublic comparables?\b", 4.2),
100
+ ("precedent_transactions", r"\bprecedent transactions?\b|\bprecedents?\b", 3.2),
101
+ ("peer_group", r"\bpeer group\b|\bpeer set\b|\bpeer analysis\b", 2.6),
102
+ ("multiple_focus", r"\bev/?ebitda\b|\bev/?ebit\b|\bp/?e\b|\bev/?fcf\b|\btrading multiples?\b", 1.8),
103
+ ],
104
+ "DCF": [
105
+ ("dcf_term", r"\bdcf\b|\bdiscounted cash flow\b", 4.6),
106
+ ("wacc_terminal", r"\bwacc\b|\bterminal value\b|\bterminal growth\b|\bperpetuity\b", 2.7),
107
+ ("discount_build", r"\bcost of equity\b|\brisk[- ]free rate\b|\bbeta\b|\bequity risk premium\b", 2.3),
108
+ ("discounted_fcf", r"\bdiscounted free cash flow\b|\b(un)?levered free cash flow\b|\bpv of free cash flows?\b", 2.2),
109
+ ],
110
+ "Debt Model": [
111
+ ("debt_model_term", r"\bdebt model\b|\bdebt schedule\b", 4.8),
112
+ ("debt_instruments", r"\brevolver\b|\bterm loan\b|\bdebenture\b|\bcoupon\b|\bamortization\b|\bprincipal\b", 3.0),
113
+ ("debt_metrics", r"\binterest coverage\b|\bleverage ratio\b|\bnet debt\b|\bdebt capacity\b", 2.4),
114
+ ],
115
+ "LBO": [
116
+ ("lbo_term", r"\blbo\b|\bleveraged buyout\b", 4.8),
117
+ ("returns_terms", r"\birr\b|\bmoic\b|\bsponsor equity\b", 3.5),
118
+ ("entry_exit_terms", r"\bentry multiple\b|\bexit multiple\b|\bpremium paid\b|\bability to pay\b", 2.2),
119
+ ],
120
+ "Market / Sector Research": [
121
+ ("market_sector_research_term", r"\bmarket (?:or )?sector research\b|\bsector research\b", 4.2),
122
+ ("industry_outlook", r"\bindustry outlook\b|\bsector outlook\b|\bmarket outlook\b", 3.1),
123
+ ("addressable_market", r"\baddressable market\b|\btam\b|\bsam\b", 2.0),
124
+ ],
125
+ "Merger Model": [
126
+ ("merger_model_term", r"\bmerger model\b|\baccretion dilution model\b", 4.5),
127
+ ("accretion_dilution", r"\baccretion\b|\bdilution\b", 3.6),
128
+ ("proforma_exchange", r"\bpro[\s-]?forma\b|\bexchange ratio\b|\bcombined company\b", 3.0),
129
+ ("consideration_mix", r"\bcash consideration\b|\bstock consideration\b|\bstock portion\b", 2.1),
130
+ ],
131
+ "Sensitivity Analysis": [
132
+ ("sensitivity_term", r"\bsensitivity\b|\bscenario\b", 3.4),
133
+ ("scenario_cases", r"\bupside\b|\bdownside\b|\blow case\b|\bmid case\b|\bhigh case\b", 2.7),
134
+ ("shock_flex", r"\bshock\b|\bstep-?up\b|\bstep-?down\b|\bflex(?:ing)?\b|\bcritical point\b", 2.6),
135
+ ("assumption_change", r"\bassuming\b|\badjust\b|\bwhat if\b", 1.4),
136
+ ],
137
+ "Valuation Analysis": [
138
+ ("valuation_term", r"\bvaluation\b|\bfair value\b", 2.9),
139
+ ("implied_value", r"\bimplied share price\b|\benterprise value\b|\bprice per share\b|\boffer price\b", 2.6),
140
+ ("premium_discount", r"\bpremium\b|\bdiscount\b|\bimplied upside/downside\b", 2.0),
141
+ ("npv_present_value", r"\bnpv\b|\bnet present value\b|\bpresent value\b", 1.8),
142
+ ],
143
+ },
144
+ "Management Consulting": {
145
+ "Benchmarking / Competitive Analysis": [
146
+ ("benchmarking_term", r"\bbenchmark(?:ing)?\b", 3.7),
147
+ ("competitive_term", r"\bcompetitive\b|\bcompetitor(?:s)?\b|\bpeer(?:s)?\b|\blandscape\b", 3.0),
148
+ ("ranking_compare", r"\brank(?:ing)?\b|\bcompare\b|\bversus\b|\bagainst\b", 1.9),
149
+ ("market_share_compare", r"\bmarket share\b", 1.7),
150
+ ],
151
+ "Cost Benefit Analysis": [
152
+ ("cost_benefit_term", r"\bcost[- ]benefit\b|\bcost benefit\b", 4.8),
153
+ ("payback_roi", r"\bpayback period\b|\broi\b", 3.3),
154
+ ("npv_term", r"\bnpv\b|\bnet present value\b", 3.1),
155
+ ("savings_investment", r"\btotal savings\b|\bone-time investment\b|\bannual benefit\b|\bprofit opportunity\b", 2.2),
156
+ ],
157
+ "Market Sizing, TAM, SAM": [
158
+ ("market_sizing_term", r"\bmarket sizing\b|\bmarket size\b", 4.1),
159
+ ("tam_sam_som", r"\btam\b|\bsam\b|\bsom\b|\baddressable market\b", 4.6),
160
+ ("implied_share_size", r"\bimplied market share\b|\btotal market size\b", 2.2),
161
+ ],
162
+ "Operations Analysis": [
163
+ ("operations_term", r"\boperations?\b|\boperational\b|\bproductivity\b|\bworkforce\b|\bstaffing\b|\bheadcount\b", 2.8),
164
+ ("plant_asset_maintenance", r"\bplant\b|\bequipment\b|\bmaintenance\b|\bdowntime\b|\bscrap\b|\byield\b|\basset\b", 2.5),
165
+ ("throughput_capacity", r"\bcapacity\b|\butilization\b|\bthroughput\b|\bspan of control\b", 2.0),
166
+ ("regression_term", r"\bregression\b|\bcorrelated\b", 1.8),
167
+ ],
168
+ "Scenario/Sensitivity Analysis": [
169
+ ("scenario_term", r"\bscenario\b|\bsensitivity\b", 3.8),
170
+ ("case_terms", r"\blow case\b|\bmid case\b|\bhigh case\b|\bstress case\b", 2.8),
171
+ ("assumption_shifts", r"\bassuming\b|\bwhat if\b|\badjust(?:ed|ment)\b|\bchange in\b", 1.5),
172
+ ("if_then", r"\bif\b.{0,35}\bthen\b", 1.6),
173
+ ],
174
+ "Strategy Recommendations": [
175
+ ("recommend_term", r"\brecommend(?:ation|ed)?\b|\bshould proceed\b|\bgo/no-go\b", 4.8),
176
+ ("strategic_option", r"\bstrategic option\b|\brecommended path\b|\bdecision score\b", 2.8),
177
+ ],
178
+ "Survey / Interview Analysis": [
179
+ ("survey_term", r"\bsurvey\b|\bquestionnaire\b|\brespondents?\b|\bresponse dataset\b", 4.0),
180
+ ("interview_term", r"\binterview\b|\bcall summary\b|\bcohort\b|\bsentiment\b", 3.0),
181
+ ("satisfaction_intent", r"\bsatisfaction\b|\bintent\b|\bpreferences?\b", 1.7),
182
+ ],
183
+ "Variance / Performance Analysis": [
184
+ ("variance_term", r"\bvariance\b|\bperformance analysis\b", 4.2),
185
+ ("gap_delta", r"\bgap\b|\bdelta\b|\bdifference\b|\bvs\.?\b|\brelative to\b", 2.4),
186
+ ("target_attainment", r"\btarget\b|\bover[- ]?perform\b|\bunder[- ]?perform\b|\battainment\b", 2.2),
187
+ ("pp_change", r"\bpercentage points?\b|\b% change\b", 2.0),
188
+ ],
189
+ },
190
+ "Law": {
191
+ "Compliance Program Review": [
192
+ ("compliance_review", r"\bcompliance review\b", 4.0),
193
+ ("compliance_program", r"\bcompliance program\b", 3.0),
194
+ ("policy_or_procedure", r"\bpolic(?:y|ies)\b|\bprocedures?\b|\bprotocols?\b", 1.9),
195
+ ("regulatory_compliance", r"\bregulatory compliance\b|\bin compliance with\b", 2.0),
196
+ ("framework_or_controls", r"\bframework\b|\bcontrols?\b", 1.6),
197
+ ("audit_or_supervision", r"\baudit\b|\bmra\b|\bcfpb\b|\bsupervision and examination\b", 1.8),
198
+ ("notice_obligation", r"\bnotification requirements?\b|\bbreach and incident response policy\b", 1.4),
199
+ ("sec_disclosure_controls", r"\b8-k\b|\bform 8-k\b|\bsec\b|\breg fd\b|\brule 10b-5\b", 2.1),
200
+ ("facility_fire_safety", r"\bfire safety\b|\binspection report\b|\bexit signage\b", 1.7),
201
+ ],
202
+ "Contract Review": [
203
+ ("agreement_or_contract", r"\bagreement\b|\bcontract\b|\bclause\b|\bterms?\b", 1.5),
204
+ ("specific_agreement_type", r"\bmaster supply agreement\b|\bmsa\b|\blease\b|\boperating agreement\b|\bcharter party\b|\bjv agreement\b", 2.3),
205
+ ("force_majeure", r"\bforce majeure\b", 2.8),
206
+ ("execution_or_amendment", r"\bexecuted\b|\bamend(?:ed|ment)\b|\brevise\b|\bredline\b", 1.3),
207
+ ("validity_or_notice", r"\bvalid\b.{0,35}\bnotice\b|\bcommencement date\b", 1.6),
208
+ ("section_by_section", r"\barticles?\b\s+\d|\bsection[s]?\b\s+\d", 1.2),
209
+ ],
210
+ "Due Diligence": [
211
+ ("due_diligence_phrase", r"\bdue diligence\b|\bdiligence file\b|\bdiligence memo\b", 4.8),
212
+ ("transaction_context", r"\bacquisition\b|\btransaction\b|\bpurchaser\b|\bseller\b|\bpost-?closing\b|\bpre-?closing\b", 2.4),
213
+ ("deal_docs", r"\bshare purchase agreement\b|\bstock purchase agreement\b|\bspa\b|\bindemnities?\b|\brepresentations?\b", 2.0),
214
+ ("diligence_review", r"\breview\b.{0,35}\bdiligence\b|\bdiligence\b.{0,35}\breview\b", 2.5),
215
+ ("closing_checklist", r"\bclosing checklist\b|\bchecklist\b", 1.4),
216
+ ("regulatory_deal_filing", r"\bhsr\b|\bfiling submission\b|\bpremerger\b", 1.8),
217
+ ],
218
+ "Internal Investigations": [
219
+ ("internal_investigation", r"\binternal investigation\b|\bincident investigation\b|\boutage investigation\b", 4.6),
220
+ ("incident_postmortem", r"\bincident report\b|\bpostmortem\b|\broot cause\b|\btimeline\b|\bevent logs?\b", 3.4),
221
+ ("email_chain", r"\bemail chain\b|\bemail exchange\b", 2.2),
222
+ ("outage_findings", r"\boutage\b.{0,35}\binvestigation\b|\bindependent investigation\b", 2.4),
223
+ ("forensic_review", r"\bforensic\b|\binterrogatories\b|\bcivil investigative demand\b", 1.6),
224
+ ],
225
+ "Legal Research": [
226
+ ("law_or_statute_question", r"\bunder\b.{0,45}\b(?:law|code|act|rule|regulation|statute)\b", 2.1),
227
+ ("citation_request", r"\bcite\b|\brelevant section\b|\bwhat (?:does|is)\b|\bwhich section\b", 1.7),
228
+ ("authority_tokens", r"\b\d+\s*u\.?s\.?c\.?\b|\b\d+\s*c\.?f\.?r\.?\b|\bfrcp\b|\bgdpr\b|\barticle \d+\b|\bncac\b|\bplanning act\b", 2.3),
229
+ ("cases_and_courts", r"\bcase law\b|\bcourt\b|\bprecedent\b|\bholding\b|\bopinion\b", 1.9),
230
+ ("requirements_question", r"\bdoes\b.{0,40}\brequire\b|\bis .* legal\b", 1.4),
231
+ ],
232
+ "Litigation Strategy": [
233
+ ("likelihood_success", r"\blikelihood of success\b|\bchance of success\b|\bsurviv(?:e|ing)\b.{0,40}\bsummary judgment\b", 4.2),
234
+ ("claims_defenses", r"\bclaims?\b|\bdefenses?\b|\bcounterclaims?\b|\bstrongest argument\b", 2.3),
235
+ ("forum_and_venue", r"\bvenue\b|\bjurisdiction\b|\barbitration\b|\bpre-?trial\b|\bsettlement\b", 1.9),
236
+ ("dismissal_strategy", r"\bmotion to dismiss\b|\brule 12\b|\bstrategy\b", 1.9),
237
+ ],
238
+ "Motion Drafting": [
239
+ ("draft_motion_material", r"\bdraft\b.{0,55}\b(?:motion|complaint|brief|memorandum|memo|outline)\b", 4.4),
240
+ ("prepare_motion_material", r"\bprepare\b.{0,55}\b(?:motion|brief|memorandum|outline)\b", 3.9),
241
+ ("new_doc_litigation", r"\bpre-?litigation legal memorandum\b|\bsummary judgment\b", 2.7),
242
+ ("edit_litigation_doc", r"\bedit existing\b.{0,35}\b(?:agreement|complaint|motion)\b", 1.8),
243
+ ],
244
+ "Risk Assessment": [
245
+ ("risk_or_exposure", r"\brisk\b|\bexposure\b|\bfinancial exposure\b", 2.0),
246
+ ("liability_penalty", r"\bliability\b|\bfine\b|\bpenalty\b|\bdamages?\b|\brefund\b", 1.8),
247
+ ("max_amount", r"\bmaximum\b.{0,35}\b(?:liability|fine|penalty|refund|exposure)\b", 2.4),
248
+ ("amount_question", r"\bhow much\b|\bwhat amount\b|\bpotential\b", 1.2),
249
+ ("risk_matrix", r"\bheat map\b|\bmitigation\b", 1.6),
250
+ ("defect_or_fault", r"\bfaulty\b|\bdefect(?:ive)?\b|\boutage\b", 1.2),
251
+ ],
252
+ "Other": [
253
+ ("spreadsheet_output", r"\bmake_new_sheet\b|\bedit_existing_sheet\b", 4.8),
254
+ ("capital_account", r"\bcapital account\b|\bdistribution amounts?\b", 2.6),
255
+ ("child_support_calc", r"\bchild support\b", 2.8),
256
+ ("quant_membership", r"\bpart of the class\b|\bhistoric stock transactions\b|\bmaximum refund amount\b", 2.4),
257
+ ("distribution_calc", r"\bdetermine\b.{0,35}\bamounts? to be distributed\b", 2.6),
258
+ ],
259
+ },
260
+ }
261
+
262
+
263
+ def _build_task_file_index(task_files_root: Path) -> dict[str, str]:
264
+ """Build task_id -> concatenated file-name hint string."""
265
+ index: dict[str, str] = {}
266
+ if not task_files_root.exists():
267
+ return index
268
+
269
+ for task_dir in sorted(task_files_root.glob("task_*")):
270
+ if not task_dir.is_dir():
271
+ continue
272
+ file_tokens: list[str] = []
273
+ for path in task_dir.rglob("*"):
274
+ if path.is_file():
275
+ file_tokens.append(path.relative_to(task_dir).as_posix())
276
+ index[task_dir.name] = "\n".join(file_tokens)
277
+ return index
278
+
279
+
280
+ def _task_text(task: dict, task_file_hints: str) -> str:
281
+ rubric_text = "\n".join(item.get("criteria", "") for item in task.get("rubric", []))
282
+ parts = [
283
+ task.get("prompt", ""),
284
+ rubric_text,
285
+ task.get("gold_response", ""),
286
+ task.get("expected_output", ""),
287
+ task_file_hints,
288
+ ]
289
+ return "\n".join(parts)
290
+
291
+
292
+ def _score_task(task: dict, task_file_hints: str) -> tuple[dict[str, float], dict[str, list[str]]]:
293
+ domain = task.get("domain")
294
+ if domain not in DOMAIN_WORKFLOW_QUOTAS:
295
+ return {}, {}
296
+
297
+ workflows = list(DOMAIN_WORKFLOW_QUOTAS[domain].keys())
298
+ priors = DOMAIN_BASE_PRIORS[domain]
299
+ signals = DOMAIN_SIGNALS[domain]
300
+
301
+ text = _task_text(task, task_file_hints).lower()
302
+ scores: dict[str, float] = {workflow: priors.get(workflow, 0.0) for workflow in workflows}
303
+ reasons: DefaultDict[str, list[str]] = defaultdict(list)
304
+
305
+ def add(workflow: str, amount: float, reason: str) -> None:
306
+ scores[workflow] += amount
307
+ reasons[workflow].append(f"{reason} (+{amount:.1f})")
308
+
309
+ for workflow, rules in signals.items():
310
+ for name, pattern, weight in rules:
311
+ if re.search(pattern, text, flags=re.IGNORECASE):
312
+ add(workflow, weight, name)
313
+
314
+ expected_output = task.get("expected_output", "")
315
+
316
+ if domain == "Investment Banking":
317
+ if expected_output in {"make_new_sheet", "edit_existing_sheet"}:
318
+ add("Sensitivity Analysis", 2.4, "sheet_output_sensitivity")
319
+ if expected_output == "make_new_slide_deck":
320
+ add("Valuation Analysis", 1.3, "slide_output_valuation")
321
+
322
+ if re.search(r"\blbo\b", text) and re.search(r"\bscenario\b|\bsensitivity\b|\bshock\b|\bflex\b", text):
323
+ add("Sensitivity Analysis", 1.5, "lbo_with_sensitivity")
324
+ if re.search(r"\bdcf\b", text) and re.search(r"\bscenario\b|\bsensitivity\b|\bassum", text):
325
+ add("Sensitivity Analysis", 1.2, "dcf_with_sensitivity")
326
+ if re.search(r"\baccretion dilution model\b|\bmerger model\b", text):
327
+ add("Merger Model", 2.0, "explicit_merger_model")
328
+ if re.search(r"\bprecedent\b|\bpublic comparables?\b", text) and re.search(r"\bmultiple\b", text):
329
+ add("Comparables", 1.4, "comparables_with_multiples")
330
+ if re.search(r"\bimplied share price\b|\benterprise value\b", text) and not re.search(
331
+ r"\blbo\b|\bmerger model\b", text
332
+ ):
333
+ add("Valuation Analysis", 1.2, "implied_value_focus")
334
+ if re.search(r"\bdebt\b", text) and re.search(r"\bterm loan\b|\brevolver\b|\binterest coverage\b", text):
335
+ add("Debt Model", 1.6, "debt_instrument_focus")
336
+
337
+ if domain == "Management Consulting":
338
+ if expected_output in {"make_new_slide_deck", "edit_existing_slide_deck"}:
339
+ add("Benchmarking / Competitive Analysis", 0.9, "slide_output_benchmarking")
340
+ if expected_output == "make_new_doc":
341
+ add("Strategy Recommendations", 1.0, "doc_output_strategy")
342
+
343
+ if re.search(r"\bsurvey\b", text) and re.search(r"\brecommend", text):
344
+ add("Strategy Recommendations", 1.1, "survey_with_recommendation")
345
+ if re.search(r"\bpayback period\b|\bone-time investment\b|\bannual savings\b", text):
346
+ add("Cost Benefit Analysis", 2.2, "payback_investment_focus")
347
+ if re.search(r"\bregression\b|\bcorrelat", text):
348
+ add("Operations Analysis", 1.6, "regression_operations_focus")
349
+ if re.search(r"\bgap\b|\bdelta\b|\bversus target\b|\brelative to\b", text):
350
+ add("Variance / Performance Analysis", 1.3, "gap_vs_target")
351
+ if re.search(r"\bscenario\b", text) and re.search(r"\bassum", text):
352
+ add("Scenario/Sensitivity Analysis", 1.4, "scenario_with_assumptions")
353
+ if re.search(r"\btam\b|\bsam\b|\bsom\b", text):
354
+ add("Market Sizing, TAM, SAM", 1.7, "tam_sam_som_bonus")
355
+
356
+ if domain == "Law":
357
+ if expected_output in {"make_new_doc", "edit_existing_doc"}:
358
+ if re.search(r"\bmotion\b|\bcomplaint\b|\bbrief\b|\bsummary judgment\b", text):
359
+ add("Motion Drafting", 2.0, "doc_output_with_litigation_terms")
360
+ elif re.search(r"\bagreement\b|\bcontract\b|\blease\b|\bmsa\b", text):
361
+ add("Contract Review", 1.3, "doc_output_with_contract_terms")
362
+ else:
363
+ add("Motion Drafting", 0.8, "doc_output_default")
364
+
365
+ if expected_output in {"make_new_sheet", "edit_existing_sheet"}:
366
+ add("Other", 5.0, "sheet_output")
367
+
368
+ if re.search(r"\bclass action\b|\bmotion to dismiss\b|\bsummary judgment\b", text):
369
+ add("Litigation Strategy", 1.2, "litigation_posture")
370
+
371
+ if re.search(r"\bcheck these (?:four )?faxes\b|\bfor each item\b|\bindicate whether\b", text):
372
+ add("Compliance Program Review", 1.0, "compliance_checklist_style")
373
+
374
+ if re.search(r"\b8-k\b|\bform 8-k\b|\bsec\b|\brule 10b-5\b|\breg fd\b", text):
375
+ add("Compliance Program Review", 1.4, "sec_disclosure_context")
376
+ add("Legal Research", 0.8, "sec_disclosure_context")
377
+
378
+ if re.search(r"\breview\b.{0,30}\bagreement\b", text) and re.search(r"\bcan\b|\bmay\b|\bvalid\b", text):
379
+ add("Contract Review", 1.1, "agreement_interpretation")
380
+
381
+ if re.search(r"\bbreach\b|\boutage\b", text) and re.search(r"\bincident report\b|\bpostmortem\b", text):
382
+ add("Internal Investigations", 1.5, "breach_incident_combo")
383
+
384
+ if re.search(
385
+ r"\bcapital account\b|\bamounts? to be distributed\b|\bchild support\b|\bmaximum refund amount\b",
386
+ text,
387
+ ):
388
+ add("Other", 1.8, "quantitative_legal_calculation")
389
+
390
+ return scores, reasons
391
+
392
+
393
+ def _quota_assign(
394
+ task_ids: list[str],
395
+ scores_by_task: dict[str, dict[str, float]],
396
+ workflow_quotas: dict[str, int],
397
+ domain: str,
398
+ ) -> dict[str, str]:
399
+ slots: list[str] = []
400
+ for workflow, count in workflow_quotas.items():
401
+ slots.extend([workflow] * count)
402
+
403
+ if len(task_ids) != len(slots):
404
+ raise ValueError(
405
+ f"{domain} task count ({len(task_ids)}) does not match workflow quota total ({len(slots)})."
406
+ )
407
+
408
+ score_matrix = np.zeros((len(task_ids), len(slots)), dtype=np.float64)
409
+ for row_idx, task_id in enumerate(task_ids):
410
+ scores = scores_by_task[task_id]
411
+ for col_idx, workflow in enumerate(slots):
412
+ score_matrix[row_idx, col_idx] = scores[workflow]
413
+
414
+ row_ind, col_ind = linear_sum_assignment(-score_matrix)
415
+ assignments: dict[str, str] = {}
416
+ for row_idx, col_idx in zip(row_ind, col_ind):
417
+ assignments[task_ids[row_idx]] = slots[col_idx]
418
+ return assignments
419
+
420
+
421
+ def _score_rank(scores: dict[str, float], assigned_workflow: str) -> int:
422
+ sorted_items = sorted(scores.items(), key=lambda item: item[1], reverse=True)
423
+ for idx, (workflow, _) in enumerate(sorted_items, start=1):
424
+ if workflow == assigned_workflow:
425
+ return idx
426
+ return len(sorted_items)
427
+
428
+
429
+ def _confidence(scores: dict[str, float], assigned_workflow: str) -> float:
430
+ vals = sorted(scores.values(), reverse=True)
431
+ top = vals[0]
432
+ second = vals[1] if len(vals) > 1 else vals[0]
433
+ assigned = scores[assigned_workflow]
434
+ margin = assigned - second if assigned == top else assigned - top
435
+ spread = max(vals) - min(vals) + 1e-6
436
+ scaled = margin / (spread / 2.0 + 1e-6)
437
+ return 1.0 / (1.0 + math.exp(-scaled))
438
+
439
+
440
+ def _augment_tasks(tasks: list[dict], task_file_index: dict[str, str]) -> tuple[list[dict], list[dict]]:
441
+ domain_scores: dict[str, dict[str, dict[str, float]]] = {}
442
+ domain_reasons: dict[str, dict[str, dict[str, list[str]]]] = {}
443
+ domain_assignments: dict[str, dict[str, str]] = {}
444
+
445
+ for domain, quotas in DOMAIN_WORKFLOW_QUOTAS.items():
446
+ domain_tasks = [task for task in tasks if task.get("domain") == domain]
447
+ task_ids = [task["task_id"] for task in domain_tasks]
448
+
449
+ scores_by_task: dict[str, dict[str, float]] = {}
450
+ reasons_by_task: dict[str, dict[str, list[str]]] = {}
451
+ for task in domain_tasks:
452
+ task_id = task["task_id"]
453
+ file_hints = task_file_index.get(task_id, "")
454
+ scores, reasons = _score_task(task, file_hints)
455
+ scores_by_task[task_id] = scores
456
+ reasons_by_task[task_id] = reasons
457
+
458
+ assignments = _quota_assign(task_ids, scores_by_task, quotas, domain)
459
+ domain_scores[domain] = scores_by_task
460
+ domain_reasons[domain] = reasons_by_task
461
+ domain_assignments[domain] = assignments
462
+
463
+ augmented: list[dict] = []
464
+ audit_rows: list[dict] = []
465
+
466
+ for task in tasks:
467
+ task_copy = dict(task)
468
+ domain = task_copy.get("domain")
469
+ if domain in DOMAIN_WORKFLOW_QUOTAS:
470
+ task_id = task_copy["task_id"]
471
+ workflow = domain_assignments[domain][task_id]
472
+ scores = domain_scores[domain][task_id]
473
+ conf = _confidence(scores, workflow)
474
+ rank = _score_rank(scores, workflow)
475
+
476
+ task_copy["workflow"] = workflow
477
+ task_copy["workflow_inference"] = {
478
+ "source": "heuristic_quota_constrained_v2_all_domains",
479
+ "confidence": round(conf, 4),
480
+ "assigned_score_rank": rank,
481
+ "reason_signals": domain_reasons[domain][task_id].get(workflow, [])[:6],
482
+ "paper_domain_quota_aligned": True,
483
+ }
484
+
485
+ sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True)
486
+ audit_rows.append(
487
+ {
488
+ "domain": domain,
489
+ "task_id": task_id,
490
+ "task_name": task_copy.get("task_name", ""),
491
+ "workflow": workflow,
492
+ "confidence": f"{conf:.4f}",
493
+ "assigned_score_rank": rank,
494
+ "top1_workflow": sorted_scores[0][0],
495
+ "top1_score": f"{sorted_scores[0][1]:.3f}",
496
+ "top2_workflow": sorted_scores[1][0],
497
+ "top2_score": f"{sorted_scores[1][1]:.3f}",
498
+ "top3_workflow": sorted_scores[2][0],
499
+ "top3_score": f"{sorted_scores[2][1]:.3f}",
500
+ "assigned_signals": " | ".join(domain_reasons[domain][task_id].get(workflow, [])[:6]),
501
+ }
502
+ )
503
+
504
+ augmented.append(task_copy)
505
+
506
+ return augmented, audit_rows
507
+
508
+
509
+ def _write_audit_csv(rows: list[dict], path: Path) -> None:
510
+ fieldnames = [
511
+ "domain",
512
+ "task_id",
513
+ "task_name",
514
+ "workflow",
515
+ "confidence",
516
+ "assigned_score_rank",
517
+ "top1_workflow",
518
+ "top1_score",
519
+ "top2_workflow",
520
+ "top2_score",
521
+ "top3_workflow",
522
+ "top3_score",
523
+ "assigned_signals",
524
+ ]
525
+ with path.open("w", encoding="utf-8", newline="") as fp:
526
+ writer = csv.DictWriter(fp, fieldnames=fieldnames)
527
+ writer.writeheader()
528
+ writer.writerows(rows)
529
+
530
+
531
+ def parse_args() -> argparse.Namespace:
532
+ parser = argparse.ArgumentParser(description=__doc__)
533
+ parser.add_argument(
534
+ "--input",
535
+ type=Path,
536
+ default=Path("tasks_and_rubrics.json"),
537
+ help="Input task JSON file.",
538
+ )
539
+ parser.add_argument(
540
+ "--output",
541
+ type=Path,
542
+ default=Path("tasks_and_rubrics_with_workflow.json"),
543
+ help="Output JSON file with inferred `workflow` labels.",
544
+ )
545
+ parser.add_argument(
546
+ "--task-files-root",
547
+ type=Path,
548
+ default=Path("task_files"),
549
+ help="Root folder containing `task_<id>` subfolders.",
550
+ )
551
+ parser.add_argument(
552
+ "--audit-output",
553
+ type=Path,
554
+ default=Path("workflow_inference_audit.csv"),
555
+ help="CSV path for per-task assignment diagnostics.",
556
+ )
557
+ return parser.parse_args()
558
+
559
+
560
+ def main() -> None:
561
+ args = parse_args()
562
+ tasks = json.loads(args.input.read_text(encoding="utf-8"))
563
+ if not isinstance(tasks, list):
564
+ raise ValueError("Input JSON must be an array of task objects.")
565
+
566
+ task_file_index = _build_task_file_index(args.task_files_root)
567
+ augmented_tasks, audit_rows = _augment_tasks(tasks, task_file_index)
568
+
569
+ args.output.write_text(json.dumps(augmented_tasks, indent=2, ensure_ascii=False), encoding="utf-8")
570
+ _write_audit_csv(audit_rows, args.audit_output)
571
+
572
+ print(f"Wrote {args.output} ({len(augmented_tasks)} tasks)")
573
+ print(f"Wrote {args.audit_output} ({len(audit_rows)} labeled tasks)")
574
+ for domain, quotas in DOMAIN_WORKFLOW_QUOTAS.items():
575
+ distribution = Counter(
576
+ task.get("workflow")
577
+ for task in augmented_tasks
578
+ if task.get("domain") == domain
579
+ )
580
+ print(f"Inferred {domain} workflow distribution:")
581
+ for workflow in quotas:
582
+ print(f" {workflow}: {distribution.get(workflow, 0)}")
583
+
584
+
585
+ if __name__ == "__main__":
586
+ main()
tasks_and_rubrics_with_workflow.json ADDED
The diff for this file is too large to render. See raw diff
 
workflow_inference_audit.csv ADDED
The diff for this file is too large to render. See raw diff