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
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
#!/usr/bin/env python3
"""Build WorkSurface-Build from the official WorkSurface/Workspace releases.

The benchmark intentionally has no gold surface representation.  The Builder
sees raw files, a role brief, a budget, and (for the persona track) calibration
episodes.  Questions and existing WorkSurface gold remain evaluator-private
until the resulting artifacts have been frozen.
"""

from __future__ import annotations

import argparse
import concurrent.futures
import hashlib
import json
import os
import re
import shutil
import subprocess
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable


HERE = Path(__file__).resolve().parent
PROJECT = HERE.parent
DEFAULT_TASKS = PROJECT / "official_worksurface_data" / "data" / "tasks.jsonl"
DEFAULT_LOCK = PROJECT / "official_worksurface_bench" / "data" / "wsb_lock.json"
DEFAULT_CACHE = HERE / "cache" / "workspace-bench-lite-en"
DEFAULT_OUTPUT = HERE / "release"
CORE_EXTENSIONS = {
    ".csv", ".xlsx", ".xls", ".txt", ".md", ".json", ".py", ".java",
    ".xml", ".html",
}

ROLE_BRIEFS = {
    "Backend Developer": "Maintain software, permissions, services, tests, and technical documentation.",
    "Logistics Manager": "Manage administration, logistics, procurement, inventory, personnel, and operations.",
    "Operations Manager": "Analyze markets, customers, products, campaigns, sales, and operational performance.",
    "Product Manager": "Synthesize product requirements, user evidence, metrics, plans, and stakeholder records.",
    "Researcher": "Analyze literature, experiments, datasets, statistical evidence, and research reports.",
}


def canonical_json(value: Any) -> bytes:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")


def sha256_bytes(value: bytes) -> str:
    return hashlib.sha256(value).hexdigest()


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def write_json(path: Path, value: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False) + "\n")


def read_jsonl(path: Path) -> list[dict[str, Any]]:
    return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]


def persona_slug(persona: str) -> str:
    return re.sub(r"[^a-z0-9]+", "_", persona.lower()).strip("_")


def normalized_hash(expected: str) -> str:
    return expected.split(":", 1)[-1].lower()


def download_url(url: str, target: Path, expected_hash: str | None, retries: int = 4) -> str:
    if target.exists() and (not expected_hash or sha256_file(target) == normalized_hash(expected_hash)):
        return "cached"
    target.parent.mkdir(parents=True, exist_ok=True)
    temp = target.with_name(target.name + ".partial")
    for attempt in range(1, retries + 1):
        try:
            # curl is used here because the local Python/OpenSSL route to the
            # Hugging Face CDN can stall before TLS negotiation, while the
            # system curl route is stable.  Downloads remain resumable at the
            # file level and are always verified against the upstream lock.
            completed = subprocess.run(
                [
                    "curl", "-sS", "-L", "--fail",
                    "--connect-timeout", "10", "--max-time", "180",
                    "--retry", "2", "--retry-all-errors",
                    "-A", "WorkSurface-Build/0.1",
                    "-o", str(temp), url,
                ],
                capture_output=True,
                text=True,
                timeout=600,
            )
            if completed.returncode != 0:
                raise OSError(completed.stderr.strip() or f"curl exit {completed.returncode}")
            if expected_hash and sha256_file(temp) != normalized_hash(expected_hash):
                raise ValueError(f"hash mismatch for {target}")
            os.replace(temp, target)
            return "downloaded"
        except (OSError, ValueError, urllib.error.URLError) as exc:
            temp.unlink(missing_ok=True)
            if attempt == retries:
                raise RuntimeError(f"failed to download {url}: {exc}") from exc
            time.sleep(min(8, 2 ** (attempt - 1)))
    raise AssertionError("unreachable")


def download_workspace_files(
    lock: dict[str, Any], cache: Path, tier: str, workers: int
) -> dict[str, int]:
    revision = lock["wsb_commit"]
    base = (
        "https://huggingface.co/datasets/Workspace-Bench/Workspace-Bench-Lite/resolve/"
        f"{revision}/task_lite_clean_en"
    )
    metadata_jobs: list[tuple[str, Path, str | None]] = []
    for task_id in lock["task_id_to_file_hashes"]:
        meta_url = f"{base}/{task_id}/metadata.json"
        metadata_jobs.append((meta_url, cache / task_id / "metadata.json", None))

    counts: Counter[str] = Counter()
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
        futures = [pool.submit(download_url, *job) for job in metadata_jobs]
        for future in concurrent.futures.as_completed(futures):
            counts[future.result()] += 1

    jobs: list[tuple[str, Path, str | None]] = []
    for task_id, files in lock["task_id_to_file_hashes"].items():
        metadata = json.loads((cache / task_id / "metadata.json").read_text(encoding="utf-8"))
        stored_paths = {
            item["filename"]: item["stored_relpath"]
            for item in metadata.get("data_manifest", [])
        }
        for filename, expected in files.items():
            if tier == "core" and Path(filename).suffix.lower() not in CORE_EXTENSIONS:
                continue
            stored_relpath = stored_paths.get(filename)
            if not stored_relpath:
                raise RuntimeError(f"metadata for task {task_id} has no stored path for {filename}")
            quoted_path = "/".join(urllib.parse.quote(part, safe="") for part in stored_relpath.split("/"))
            jobs.append((f"{base}/{task_id}/{quoted_path}", cache / task_id / "data" / filename, expected))

    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
        futures = [pool.submit(download_url, *job) for job in jobs]
        for future in concurrent.futures.as_completed(futures):
            counts[future.result()] += 1
    counts["jobs"] = len(metadata_jobs) + len(jobs)
    return dict(counts)


def link_or_copy(source: Path, target: Path) -> None:
    target.parent.mkdir(parents=True, exist_ok=True)
    if target.exists():
        if source.stat().st_size == target.stat().st_size and sha256_file(source) == sha256_file(target):
            return
        raise RuntimeError(f"refusing to replace different release file: {target}")
    try:
        os.link(source, target)
    except OSError:
        shutil.copy2(source, target)


def public_question(task: dict[str, Any]) -> dict[str, Any]:
    return {
        "id": task["id"],
        "question": task["question"],
        "difficulty": task.get("difficulty", "unknown"),
        "answer_type": task.get("answer_type", "string"),
        "efficiency_budget_tokens": task.get("efficiency_budget_tokens"),
    }


def calibration_episode(task: dict[str, Any]) -> dict[str, Any]:
    return {
        "id": task["id"],
        "question": task["question"],
        "answer": task["gold_answer"],
        "answer_type": task.get("answer_type", "string"),
    }


def task_commitment(tasks: list[dict[str, Any]]) -> str:
    return "sha256:" + sha256_bytes(canonical_json(tasks))


def stable_calibration_sources(source_ids: list[str], ratio: float, seed: str) -> set[str]:
    ordered = sorted(
        source_ids,
        key=lambda source: sha256_bytes(f"{seed}:{source}".encode("utf-8")),
    )
    if len(ordered) <= 1 or ratio <= 0:
        return set()
    count = max(1, min(len(ordered) - 1, round(len(ordered) * ratio)))
    return set(ordered[:count])


def raw_evidence_name(evidence: dict[str, Any], source_id: str) -> str | None:
    value = evidence.get("source_file")
    if value:
        return Path(str(value)).name
    if evidence.get("surface") == "rag" and evidence.get("file"):
        value = Path(str(evidence["file"])).name
        value = re.sub(rf"^t{re.escape(source_id)}__", "", value)
        if value.endswith(".md"):
            value = value[:-3]
        return value
    path = evidence.get("graph_path") or []
    if path:
        value = str(path[-1]).split("::", 1)[-1]
        if "." in value:
            return Path(value).name
    return None


def norm_filename(value: str) -> str:
    return re.sub(r"[^a-z0-9]+", "", value.lower())


def evidence_mapping_audit(tasks: list[dict[str, Any]], lock: dict[str, Any]) -> dict[str, Any]:
    total = checked = hits = 0
    misses: list[dict[str, str]] = []
    for task in tasks:
        source_id = str(task["source"]["task_id"])
        raw_names = list(lock["task_id_to_file_hashes"][source_id])
        normalized = {norm_filename(name): name for name in raw_names}
        for evidence in task.get("gold_evidence", []):
            total += 1
            candidate = raw_evidence_name(evidence, source_id)
            if not candidate:
                continue
            checked += 1
            key = norm_filename(candidate)
            matched = key in normalized
            if not matched:
                matched = any(key.startswith(raw_key) or raw_key.startswith(key) for raw_key in normalized)
            if matched:
                hits += 1
            elif len(misses) < 50:
                misses.append({"task_id": task["id"], "source_task_id": source_id, "candidate": candidate})
    return {
        "total_gold_evidence_items": total,
        "file_addressable_evidence_items": checked,
        "mapped_evidence_items": hits,
        "file_addressable_coverage": round(checked / total, 6) if total else None,
        "mapping_rate_given_file_addressable": round(hits / checked, 6) if checked else None,
        "sample_misses": misses,
    }


def build_release(
    tasks: list[dict[str, Any]],
    lock: dict[str, Any],
    cache: Path,
    output: Path,
    tier: str,
    calibration_ratio: float,
    seed: str,
) -> dict[str, Any]:
    public = output / "public"
    private = output / "private"
    by_source: dict[str, list[dict[str, Any]]] = defaultdict(list)
    by_persona_sources: dict[str, set[str]] = defaultdict(set)
    for task in tasks:
        source_id = str(task["source"]["task_id"])
        persona = task["source"]["persona"]
        by_source[source_id].append(task)
        by_persona_sources[persona].add(source_id)

    if set(by_source) != set(lock["task_id_to_file_hashes"]):
        raise RuntimeError("official WorkSurface source tasks do not match the Workspace-Bench lock")

    task_unit_rows: list[dict[str, Any]] = []
    total_public_files = total_public_bytes = 0
    for source_id in sorted(by_source, key=int):
        source_tasks = sorted(by_source[source_id], key=lambda item: item["id"])
        persona = source_tasks[0]["source"]["persona"]
        unit_id = f"task_{int(source_id):03d}"
        workspace = public / "task_units" / unit_id / "workspace"
        workspace.mkdir(parents=True, exist_ok=True)
        source_data = cache / source_id / "data"
        included: list[dict[str, Any]] = []
        for filename, expected in lock["task_id_to_file_hashes"][source_id].items():
            source_file = source_data / filename
            if not source_file.exists():
                continue
            link_or_copy(source_file, workspace / filename)
            included.append({
                "path": filename,
                "bytes": source_file.stat().st_size,
                "sha256": "sha256:" + sha256_file(source_file),
            })
            total_public_files += 1
            total_public_bytes += source_file.stat().st_size

        commitment = task_commitment(source_tasks)
        unit = {
            "unit_id": unit_id,
            "protocol": "zero_calibration_build_once_then_hidden_queries",
            "persona": persona,
            "role_brief": ROLE_BRIEFS[persona],
            "workspace": "workspace",
            "source_task_id": source_id,
            "calibration_episodes": [],
            "hidden_task_count": len(source_tasks),
            "hidden_task_commitment": commitment,
            "build_budget": {"policy": "runner_defined", "must_be_recorded": True},
            "raw_fallback_policy": "runner_defined_and_reported",
            "files": included,
        }
        unit_dir = public / "task_units" / unit_id
        write_json(unit_dir / "unit.json", unit)
        write_jsonl(private / "task_units" / f"{unit_id}.jsonl", source_tasks)
        write_jsonl(private / "serve_questions" / f"{unit_id}.jsonl", map(public_question, source_tasks))
        metadata = cache / source_id / "metadata.json"
        if metadata.exists():
            link_or_copy(metadata, private / "source_metadata" / f"{unit_id}.json")
        task_unit_rows.append({
            "unit_id": unit_id,
            "persona": persona,
            "source_task_id": source_id,
            "workspace": str((unit_dir / "workspace").relative_to(output)),
            "unit_spec": str((unit_dir / "unit.json").relative_to(output)),
            "hidden_task_count": len(source_tasks),
            "hidden_task_commitment": commitment,
        })
    write_jsonl(public / "task_units.jsonl", task_unit_rows)

    persona_unit_rows: list[dict[str, Any]] = []
    persona_split_summary: dict[str, Any] = {}
    for persona in sorted(by_persona_sources):
        slug = persona_slug(persona)
        source_ids = sorted(by_persona_sources[persona], key=int)
        calibration_sources = stable_calibration_sources(source_ids, calibration_ratio, f"{seed}:{persona}")
        hidden_sources = set(source_ids) - calibration_sources
        calibration: list[dict[str, Any]] = []
        hidden: list[dict[str, Any]] = []
        for source_id in source_ids:
            source_tasks = sorted(by_source[source_id], key=lambda item: item["id"])
            if source_id in calibration_sources:
                calibration.append(calibration_episode(source_tasks[0]))
            else:
                hidden.extend(source_tasks)
        hidden.sort(key=lambda item: item["id"])

        unit_dir = public / "persona_units" / slug
        workspace_dir = unit_dir / "workspace"
        workspace_entries: list[dict[str, Any]] = []
        for source_id in source_ids:
            task_unit = public / "task_units" / f"task_{int(source_id):03d}" / "workspace"
            link = workspace_dir / f"source_task_{int(source_id):03d}"
            link.parent.mkdir(parents=True, exist_ok=True)
            if not link.exists():
                relative = os.path.relpath(task_unit, link.parent)
                link.symlink_to(relative, target_is_directory=True)
            workspace_entries.append({"source_task_id": source_id, "path": link.name})

        commitment = task_commitment(hidden)
        unit = {
            "unit_id": f"persona_{slug}",
            "protocol": "cross_source_calibration_build_once_then_hidden_queries",
            "persona": persona,
            "role_brief": ROLE_BRIEFS[persona],
            "workspace": "workspace",
            "workspace_sources": workspace_entries,
            "calibration_episodes": calibration,
            "hidden_task_count": len(hidden),
            "hidden_task_commitment": commitment,
            "build_budget": {"policy": "runner_defined", "must_be_recorded": True},
            "raw_fallback_policy": "runner_defined_and_reported",
        }
        write_json(unit_dir / "unit.json", unit)
        write_jsonl(private / "persona_units" / f"persona_{slug}.jsonl", hidden)
        write_jsonl(private / "persona_serve_questions" / f"persona_{slug}.jsonl", map(public_question, hidden))
        write_json(private / "persona_splits" / f"persona_{slug}.json", {
            "calibration_source_task_ids": sorted(calibration_sources, key=int),
            "hidden_source_task_ids": sorted(hidden_sources, key=int),
        })
        persona_unit_rows.append({
            "unit_id": unit["unit_id"],
            "persona": persona,
            "workspace": str(workspace_dir.relative_to(output)),
            "unit_spec": str((unit_dir / "unit.json").relative_to(output)),
            "hidden_task_count": len(hidden),
            "hidden_task_commitment": commitment,
        })
        persona_split_summary[persona] = {
            "workspace_source_tasks": len(source_ids),
            "calibration_source_tasks": len(calibration_sources),
            "calibration_episodes": len(calibration),
            "hidden_source_tasks": len(hidden_sources),
            "hidden_tasks": len(hidden),
        }
    write_jsonl(public / "persona_units.jsonl", persona_unit_rows)

    manifest = {
        "name": "WorkSurface-Build",
        "version": "0.1.0",
        "construction": "annotation_reuse_only",
        "gold_surface_required": False,
        "source": {
            "worksurface_tasks": str(DEFAULT_TASKS),
            "worksurface_task_count": len(tasks),
            "workspace_bench_repo": lock["wsb_repo"],
            "workspace_bench_commit": lock["wsb_commit"],
            "workspace_tier": tier,
        },
        "task_unit_track": {
            "units": len(task_unit_rows),
            "hidden_tasks": sum(row["hidden_task_count"] for row in task_unit_rows),
            "raw_files": total_public_files,
            "raw_bytes": total_public_bytes,
        },
        "persona_reuse_track": {
            "units": len(persona_unit_rows),
            "calibration_ratio_by_source_task": calibration_ratio,
            "seed": seed,
            "splits": persona_split_summary,
            "hidden_tasks": sum(row["hidden_task_count"] for row in persona_unit_rows),
        },
        "task_type_distribution": dict(sorted(Counter(task["task_type"] for task in tasks).items())),
        "surface_combo_distribution_evaluator_only": dict(sorted(Counter(
            "+".join(sorted(task["required_surfaces"])) for task in tasks
        ).items())),
        "evidence_mapping_audit": evidence_mapping_audit(tasks, lock),
        "security_boundary": {
            "builder_visible": "public/** only",
            "evaluator_only": "private/** and manifest evaluator-only fields",
            "rule": "hidden questions are released only after artifact freeze",
        },
    }
    write_json(output / "manifest.json", manifest)
    return manifest


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--tasks", type=Path, default=DEFAULT_TASKS)
    parser.add_argument("--wsb-lock", type=Path, default=DEFAULT_LOCK)
    parser.add_argument("--cache", type=Path, default=DEFAULT_CACHE)
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument("--tier", choices=("core", "full"), default="core")
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--calibration-ratio", type=float, default=0.2)
    parser.add_argument("--seed", default="worksurface-build-v0.1")
    parser.add_argument("--skip-download", action="store_true")
    args = parser.parse_args()

    tasks = read_jsonl(args.tasks)
    lock = json.loads(args.wsb_lock.read_text(encoding="utf-8"))
    if not args.skip_download:
        download_stats = download_workspace_files(lock, args.cache, args.tier, args.workers)
        print(json.dumps({"download": download_stats}, ensure_ascii=False))
    manifest = build_release(
        tasks, lock, args.cache, args.output, args.tier,
        args.calibration_ratio, args.seed,
    )
    print(json.dumps({
        "output": str(args.output.resolve()),
        "task_units": manifest["task_unit_track"]["units"],
        "task_unit_hidden_tasks": manifest["task_unit_track"]["hidden_tasks"],
        "persona_units": manifest["persona_reuse_track"]["units"],
        "persona_hidden_tasks": manifest["persona_reuse_track"]["hidden_tasks"],
        "raw_files": manifest["task_unit_track"]["raw_files"],
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()