---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Canonicalise Codex story jobs and archive duplicate jobs behind aliases.\"\"\" from __future__ import annotations import argparse import copy import json import shutil import sys from collections."
resource: "https://codex.copecheck.com/tools/migrate_story_identities.py"
tags: ["copecheck", "codex", "source-file", "py"]
timestamp: "2026-08-25T12:19:38Z"
site: "codex"
source_path: "copecheck-codex/tools/migrate_story_identities.py"
---

# !/usr/bin/env python3

Source path: `copecheck-codex/tools/migrate_story_identities.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-08-25T12:19:38Z`

```py
#!/usr/bin/env python3
"""Canonicalise Codex story jobs and archive duplicate jobs behind aliases."""
from __future__ import annotations

import argparse
import copy
import json
import shutil
import sys
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from canonical_identity import canonical_url, normalise_text  # noqa: E402
from story_state import (  # noqa: E402
    archive_duplicate_job,
    atomic_write_json,
    canonical_job_id,
    ensure_job_identity,
    job_story_key,
    rebuild_story_aliases,
    register_story_aliases,
    resolve_job_id,
    state_file_lock,
    story_key,
)


TERMINAL_RANK = {
    "complete": 6,
    "needs_review": 5,
    "discarded": 4,
    "failed": 3,
    "claimed": 2,
    "queued": 1,
}


def _timestamp(value: object) -> float:
    try:
        return datetime.fromisoformat(str(value or "").replace("Z", "+00:00")).timestamp()
    except ValueError:
        return 0.0


def _title(job: dict) -> str:
    result = job.get("result") if isinstance(job.get("result"), dict) else {}
    source = result.get("source") if isinstance(result.get("source"), dict) else {}
    extracted = str(source.get("title") or "")
    feed_title = str(job.get("story_title") or "")
    return extracted if _usable_title(extracted) else feed_title


def _usable_title(value: str) -> bool:
    title = normalise_text(value)
    if len(title) < 24:
        return False
    blockers = (
        "before you continue", "wait for verification", "verify you are human",
        "access denied", "just a moment", "enable javascript", "page not found",
        "request blocked", "attention required", "captcha",
    )
    return not any(blocker in title for blocker in blockers)


def _summary(job: dict) -> str:
    result = job.get("result") if isinstance(job.get("result"), dict) else {}
    claims = result.get("claims") if isinstance(result.get("claims"), list) else []
    claim = claims[0] if claims and isinstance(claims[0], dict) else {}
    return str(claim.get("relevant_excerpt") or job.get("story_summary") or "")


def _confidence(job: dict) -> float:
    result = job.get("result") if isinstance(job.get("result"), dict) else {}
    claims = result.get("claims") if isinstance(result.get("claims"), list) else []
    claim = claims[0] if claims and isinstance(claims[0], dict) else {}
    try:
        return float(claim.get("confidence") or 0)
    except (TypeError, ValueError):
        return 0.0


def _primary_rank(item: tuple[str, dict]) -> tuple:
    job_id, job = item
    title_text = f"{job.get('url') or ''} {_title(job)}".lower()
    looks_layoff = any(word in title_text for word in ("layoff", "laid off", "job cut", "redundan"))
    route = str(job.get("route_target") or job.get("channel") or "")
    route_fit = int(not looks_layoff or route == "layoffs")
    return (
        int(job.get("publication_status") == "published"),
        route_fit,
        TERMINAL_RANK.get(str(job.get("status")), 0),
        _confidence(job),
        -_timestamp(job.get("submitted_at")),
        job_id,
    )


class UnionFind:
    def __init__(self, keys):
        self.parent = {key: key for key in keys}

    def find(self, key):
        while self.parent[key] != key:
            self.parent[key] = self.parent[self.parent[key]]
            key = self.parent[key]
        return key

    def union(self, left, right):
        a, b = self.find(left), self.find(right)
        if a != b:
            self.parent[max(a, b)] = min(a, b)


def duplicate_groups(jobs: dict[str, dict]) -> list[list[tuple[str, dict]]]:
    uf = UnionFind(jobs)
    by_canonical: dict[str, list[str]] = defaultdict(list)
    for job_id, job in jobs.items():
        canonical = canonical_url(job.get("url"))
        if canonical:
            by_canonical[canonical].append(job_id)
    for ids in by_canonical.values():
        for job_id in ids[1:]:
            uf.union(ids[0], job_id)
    groups: dict[str, list[tuple[str, dict]]] = defaultdict(list)
    for job_id, job in jobs.items():
        groups[uf.find(job_id)].append((job_id, job))
    return [group for group in groups.values() if len(group) > 1]


def migrate_state(original: dict) -> tuple[dict, dict]:
    state = copy.deepcopy(original)
    jobs = state.setdefault("jobs", {})
    aliases = state.setdefault("job_aliases", {})
    archive = state.setdefault("duplicate_jobs", {})
    identity_updates = 0
    for job_id, job in jobs.items():
        if not isinstance(job, dict):
            continue
        updated = ensure_job_identity(job, job_id)
        before_aliases = dict(state.get("story_aliases") or {})
        register_story_aliases(state, job_id, job)
        updated = before_aliases != state.get("story_aliases") or updated
        if updated:
            identity_updates += 1

    groups = duplicate_groups({key: value for key, value in jobs.items() if isinstance(value, dict)})
    archived = 0
    published_archived = 0
    canonical_groups = 0
    syndicated_groups = 0
    for group in groups:
        primary_id, primary = max(group, key=_primary_rank)
        canonicals = {canonical_url(job.get("url")) for _, job in group}
        if len(canonicals) != 1:
            raise RuntimeError("URL-only migration produced a cross-resource group")
        canonical_groups += 1
        for loser_id, loser in group:
            if loser_id == primary_id:
                continue
            reason = (
                "canonical_url" if canonical_url(loser.get("url")) == canonical_url(primary.get("url"))
                else "syndicated_event"
            )
            archive_duplicate_job(state, primary_id, loser_id, reason)
            if loser.get("publication_status") == "published":
                published_archived += 1
            archived += 1
        register_story_aliases(state, primary_id, jobs[primary_id])

    rebuild_story_aliases(state)

    legacy_tag_reconciliations = reconcile_within_job_legacy_tags(jobs)
    uninserted_runtime_tag_reconciliations = reconcile_uninserted_runtime_tags(state)

    invariants = validate_state(original, state, archived)
    changed = state != original
    if changed:
        state["story_identity_migration"] = {
            "version": 1,
            "applied_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
            "identity": "shared-channel-neutral-v1",
        }
    report = {
        "jobs_before": len(original.get("jobs", {})),
        "jobs_after": len(jobs),
        "identity_updates": identity_updates,
        "legacy_tag_reconciliations": legacy_tag_reconciliations,
        "uninserted_runtime_tag_reconciliations": uninserted_runtime_tag_reconciliations,
        "duplicate_groups": len(groups),
        "canonical_duplicate_groups": canonical_groups,
        "syndicated_event_groups": syndicated_groups,
        "duplicate_jobs_archived": archived,
        "published_duplicates_archived": published_archived,
        "aliases": len(aliases),
        "archive_rows": len(archive),
        "changed": changed,
        "invariants": invariants,
    }
    return state, report


def reconcile_within_job_legacy_tags(jobs: dict[str, dict]) -> int:
    """Give every historic job ID exactly one provenance owner.

    An earlier result callback appended a second, richer observation with the
    same legacy ID as the job's discovery observation.  The observation is
    still useful audit evidence, so retain it while removing only its duplicate
    ownership tag.  A legacy ID appearing under different live jobs is a real
    conservation conflict and must never be repaired implicitly.
    """
    owners: dict[str, str] = {}
    reconciled = 0
    for job_id in sorted(jobs):
        job = jobs[job_id]
        if not isinstance(job, dict):
            continue
        for observation in job.get("provenance") or []:
            if not isinstance(observation, dict):
                continue
            legacy_id = str(observation.get("legacy_job_id") or "")
            if not legacy_id:
                continue
            owner = owners.get(legacy_id)
            if owner is None:
                owners[legacy_id] = str(job_id)
                continue
            if owner != str(job_id):
                raise RuntimeError(
                    f"legacy provenance ID {legacy_id} belongs to multiple live jobs"
                )
            # Keep the first list entry as the historic owner.  Later rows
            # remain intact as unowned result/discovery observations.
            observation.pop("legacy_job_id", None)
            reconciled += 1
    return reconciled


def reconcile_uninserted_runtime_tags(state: dict) -> int:
    """Remove ownership tags accidentally assigned to never-inserted RSS jobs.

    The affected observation remains as publisher provenance.  Repair is
    intentionally narrow: the unknown tag must be the deterministic job ID of
    that RSS observation URL, and the rebuilt story alias must resolve the URL
    to the live owner containing the observation.  Any other unknown ownership
    tag remains a hard validation failure.
    """
    jobs = state.get("jobs") if isinstance(state.get("jobs"), dict) else {}
    archive = state.get("duplicate_jobs") if isinstance(state.get("duplicate_jobs"), dict) else {}
    known_ids = {str(job_id) for job_id in jobs} | {str(job_id) for job_id in archive}
    aliases = state.get("story_aliases") if isinstance(state.get("story_aliases"), dict) else {}
    reconciled = 0
    for owner_id in sorted(jobs):
        job = jobs[owner_id]
        if not isinstance(job, dict):
            continue
        for observation in job.get("provenance") or []:
            if not isinstance(observation, dict):
                continue
            legacy_id = str(observation.get("legacy_job_id") or "")
            if not legacy_id or legacy_id in known_ids:
                continue
            observation_url = observation.get("canonical_url") or observation.get("raw_url")
            observation_key = story_key(observation_url)
            safe_runtime_capture = all([
                str(observation.get("source") or "") == "rss",
                legacy_id == canonical_job_id(observation_url),
                bool(observation_key),
                str(aliases.get(observation_key) or "") == str(owner_id),
            ])
            if safe_runtime_capture:
                observation.pop("legacy_job_id", None)
                reconciled += 1
    return reconciled


def validate_state(original: dict, state: dict, newly_archived: int) -> dict:
    jobs = state.get("jobs")
    if not isinstance(jobs, dict) or any(not isinstance(job, dict) for job in jobs.values()):
        raise RuntimeError("jobs must be an object containing only job objects")
    if len(jobs) != len(original.get("jobs", {})) - newly_archived:
        raise RuntimeError("live job count does not reconcile with archived duplicates")

    aliases = state.get("job_aliases") or {}
    archive = state.get("duplicate_jobs") or {}
    story_aliases = state.get("story_aliases") or {}
    if not all(isinstance(item, dict) for item in (aliases, archive, story_aliases)):
        raise RuntimeError("alias/archive structures must be objects")

    live_keys: dict[str, str] = {}
    # Every live state row and every archived loser is a historic observation
    # that must remain represented on every migration pass, not only pass one.
    required_ids = {str(job_id) for job_id in jobs} | {
        str(job_id) for job_id in archive
    }
    represented: dict[str, int] = {job_id: 0 for job_id in required_ids}
    unknown_legacy_ids: set[str] = set()
    misowned_legacy_ids: set[str] = set()
    provenance_rows = 0
    for job_id, job in jobs.items():
        key = job_story_key(job)
        if not key:
            raise RuntimeError(f"job {job_id} has an empty story key")
        if key in live_keys and live_keys[key] != job_id:
            raise RuntimeError(f"story key is not unique: {key}")
        live_keys[key] = job_id
        if not job.get("event_fingerprint"):
            raise RuntimeError(f"job {job_id} has an empty event fingerprint")
        observations = job.get("provenance") or []
        observation_keys: set[str] = set()
        for observation in observations:
            if not isinstance(observation, dict) or not observation.get("observation_key"):
                raise RuntimeError(f"job {job_id} has invalid provenance")
            observation_key = str(observation["observation_key"])
            if observation_key in observation_keys:
                raise RuntimeError(f"job {job_id} has duplicate provenance keys")
            observation_keys.add(observation_key)
            provenance_rows += 1
            legacy_id = str(observation.get("legacy_job_id") or "")
            if not legacy_id:
                continue
            if legacy_id not in represented:
                unknown_legacy_ids.add(legacy_id)
                continue
            represented[legacy_id] += 1
            if resolve_job_id(state, legacy_id) != str(job_id):
                misowned_legacy_ids.add(legacy_id)
        if int(job.get("provenance_count") or 0) != len(observations):
            raise RuntimeError(f"job {job_id} provenance count is stale")

    missing = sorted(job_id for job_id, count in represented.items() if count == 0)
    repeated = sorted(job_id for job_id, count in represented.items() if count > 1)
    if missing or repeated or unknown_legacy_ids or misowned_legacy_ids:
        raise RuntimeError(
            "legacy provenance reconciliation failed: "
            f"missing={len(missing)} nonunique={len(repeated)} "
            f"unknown={len(unknown_legacy_ids)} misowned={len(misowned_legacy_ids)}"
        )

    alias_orphans = []
    alias_loops = []
    for alias_id in aliases:
        resolved = resolve_job_id(state, str(alias_id))
        if resolved == str(alias_id):
            alias_loops.append(str(alias_id))
        if resolved not in jobs:
            alias_orphans.append(str(alias_id))
        if str(alias_id) not in archive:
            alias_orphans.append(f"{alias_id}:missing-archive")
    story_alias_orphans = [
        key for key, target in story_aliases.items()
        if resolve_job_id(state, str(target)) not in jobs
    ]
    if alias_orphans or alias_loops or story_alias_orphans:
        raise RuntimeError(
            "alias integrity failed: "
            f"orphans={len(alias_orphans)} loops={len(alias_loops)} "
            f"story_orphans={len(story_alias_orphans)}"
        )
    remaining_groups = duplicate_groups(jobs)
    if remaining_groups:
        raise RuntimeError(f"{len(remaining_groups)} duplicate groups remain")
    return {
        "passed": True,
        "required_legacy_jobs": len(required_ids),
        "missing_legacy_jobs": 0,
        "nonunique_legacy_jobs": 0,
        "unknown_legacy_jobs": 0,
        "misowned_legacy_jobs": 0,
        "live_story_keys": len(live_keys),
        "provenance_rows": provenance_rows,
        "remaining_duplicate_groups": 0,
        "alias_orphans": 0,
        "alias_loops": 0,
        "story_alias_orphans": 0,
    }


def run(state_path: Path, apply: bool = False, backup_path: Path | None = None) -> dict:
    def load():
        return json.loads(state_path.read_text(encoding="utf-8"))

    if not apply:
        with state_file_lock(state_path, exclusive=False):
            _state, report = migrate_state(load())
            return {"mode": "dry-run", "backup": None, **report}

    with state_file_lock(state_path):
        original = load()
        state, report = migrate_state(original)
        backup = None
        if report["changed"]:
            if backup_path is None:
                stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
                backup_path = state_path.with_name(f"{state_path.name}.pre-story-dedupe-{stamp}.bak")
            if backup_path.exists():
                raise FileExistsError(backup_path)
            shutil.copy2(state_path, backup_path)
            atomic_write_json(state_path, state)
            backup = str(backup_path)
        return {"mode": "apply", "backup": backup, **report}


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


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