---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Withhold non-additive Layoffs headline totals while preserving their history.\"\"\" from __future__ import annotations import argparse import copy import json import os import shutil import."
resource: "https://layoffs.copecheck.com"
tags: ["copecheck", "layoffs", "source-file", "py"]
timestamp: "2026-08-24T13:34:33Z"
site: "layoffs"
source_path: "copecheck-layoffs/quarantine_unreconciled_aggregates.py"
---

# !/usr/bin/env python3

Source path: `copecheck-layoffs/quarantine_unreconciled_aggregates.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-08-24T13:34:33Z`

```py
#!/usr/bin/env python3
"""Withhold non-additive Layoffs headline totals while preserving their history."""
from __future__ import annotations

import argparse
import copy
import json
import os
import shutil
import tempfile
from datetime import datetime, timezone
from pathlib import Path


def build_report(data: dict) -> dict:
    summary = data.get("summary") if isinstance(data.get("summary"), dict) else {}
    rows = {
        year: len(data.get(f"major_{year}", [])) + len(data.get(f"scanned_{year}", []))
        for year in ("2025", "2026")
    }
    sources = {
        year: sum(
            bool(item.get("source_url"))
            for key in (f"major_{year}", f"scanned_{year}")
            for item in data.get(key, [])
            if isinstance(item, dict)
        )
        for year in ("2025", "2026")
    }
    return {
        "claim_rows": rows,
        "source_linked_rows": sources,
        "legacy_total_2026": (summary.get("2026") or {}).get("total_layoffs"),
        "already_withheld": (summary.get("2026") or {}).get("aggregate_status") == "withheld_non_additive",
    }


def atomic_json_write(path: Path, data: dict) -> None:
    fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump(data, handle, indent=2, ensure_ascii=False)
            handle.write("\n")
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(tmp_name, path)
    finally:
        if os.path.exists(tmp_name):
            os.unlink(tmp_name)


def run(path: Path, apply: bool = False, backup: Path | None = None) -> dict:
    data = json.loads(path.read_text(encoding="utf-8"))
    report = build_report(data)
    report["mode"] = "apply" if apply else "dry-run"
    report["backup"] = None
    if not apply or report["already_withheld"]:
        return report

    if backup is None:
        stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
        backup = path.with_name(f"{path.name}.pre-aggregate-withhold-{stamp}.bak")
    if backup.exists():
        raise FileExistsError(backup)
    shutil.copy2(path, backup)

    audit = data.setdefault("audit", {})
    audit.setdefault("legacy_unreconciled_summary", copy.deepcopy(data.get("summary", {})))
    audit.update({
        "aggregate_status": "withheld_non_additive",
        "aggregate_withheld_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
        "reason": "Source claims may be syndicated, aggregate, planned, aliased or overlapping and cannot be added as distinct people.",
    })
    summary = data.setdefault("summary", {})
    for year in ("2025", "2026"):
        entries = data.get(f"major_{year}", []) + data.get(f"scanned_{year}", [])
        row = summary.setdefault(year, {})
        row.update({
            "total_layoffs": None,
            "avg_per_day": None,
            "ai_attributed": None,
            "total_events": len(entries),
            "source_linked_events": sum(bool(item.get("source_url")) for item in entries),
            "aggregate_status": "withheld_non_additive",
        })
    summary.setdefault("since_2020", {})["total"] = None
    data.setdefault("meta", {})["aggregate_note"] = audit["reason"]
    atomic_json_write(path, data)

    saved = json.loads(path.read_text(encoding="utf-8"))
    final = build_report(saved)
    if not final["already_withheld"] or final["legacy_total_2026"] is not None:
        raise RuntimeError("aggregate totals were not withheld")
    report.update(final)
    report["backup"] = str(backup)
    return report


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("path", type=Path)
    parser.add_argument("--apply", action="store_true")
    parser.add_argument("--backup", type=Path)
    args = parser.parse_args()
    print(json.dumps(run(args.path, args.apply, args.backup), indent=2, sort_keys=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
```
