---
type: "Source File"
title: "\"\"\"Cross-process-safe, channel-neutral identity helpers for Codex story state.\"\"\""
description: "\"\"\"Cross-process-safe, channel-neutral identity helpers for Codex story state.\"\"\" from __future__ import annotations import fcntl import copy import json import math import os import tempfile from collections import."
resource: "https://codex.copecheck.com/story_state.py"
tags: ["copecheck", "codex", "source-file", "py"]
timestamp: "2026-09-08T19:21:43Z"
site: "codex"
source_path: "copecheck-codex/story_state.py"
---

# """Cross-process-safe, channel-neutral identity helpers for Codex story state."""

Source path: `copecheck-codex/story_state.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-08T19:21:43Z`

```py
"""Cross-process-safe, channel-neutral identity helpers for Codex story state."""
from __future__ import annotations

import fcntl
import copy
import json
import math
import os
import tempfile
from collections import defaultdict
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterator

from canonical_identity import (
    canonical_url,
    canonical_url_hash,
    exact_statement_match,
    new_event_fingerprint,
    normalise_text,
    provenance_key,
    same_event,
)


EVENT_WINDOW_DAYS = 7
STATE_MAPPING_KEYS = ("jobs", "job_aliases", "duplicate_jobs", "story_aliases")
PUBLIC_JOB_ERROR = "Scoring failed. Internal diagnostics are retained for review."
PUBLIC_DIAGNOSTIC_KEYS = frozenset({
    "debug",
    "diagnostic",
    "diagnostics",
    "discard_reason",
    "error",
    "errors",
    "exception",
    "internal_diagnostics",
    "raw_error",
    "raw_output",
    "stack",
    "stack_trace",
    "traceback",
    "validation_error",
    "validation_errors",
    "worker_error",
})
_DROP_PUBLIC_VALUE = object()


def ensure_state_schema(state: dict[str, Any]) -> dict[str, Any]:
    """Initialize all state mappings and reject corrupt container types."""
    if not isinstance(state, dict):
        raise ValueError("Codex state must be a JSON object")
    for key in STATE_MAPPING_KEYS:
        value = state.setdefault(key, {})
        if not isinstance(value, dict):
            raise ValueError(f"Codex state field {key} must be an object")
    return state


def public_job_error(value: Any) -> str | None:
    """Expose failure state without leaking private worker diagnostics."""
    return PUBLIC_JOB_ERROR if str(value or "").strip() else None


def valid_public_score(value: Any) -> bool:
    """Return whether a value satisfies the public finite 0–100 contract."""
    if isinstance(value, bool):
        return False
    if isinstance(value, int):
        return 0 <= value <= 100
    if not isinstance(value, float):
        return False
    return math.isfinite(value) and 0 <= value <= 100


def _public_value(value: Any, key: str | None = None) -> Any:
    """Deep-copy a value while removing private diagnostics and invalid JSON."""
    normalized_key = str(key or "").strip().lower().replace("-", "_")
    if normalized_key in PUBLIC_DIAGNOSTIC_KEYS:
        return _DROP_PUBLIC_VALUE
    if isinstance(value, float) and not math.isfinite(value):
        return _DROP_PUBLIC_VALUE
    if isinstance(value, dict):
        clean: dict[str, Any] = {}
        for child_key, child_value in value.items():
            public_child = _public_value(child_value, str(child_key))
            if public_child is not _DROP_PUBLIC_VALUE:
                clean[str(child_key)] = public_child
        return clean
    if isinstance(value, list):
        clean_list = []
        for child_value in value:
            public_child = _public_value(child_value)
            if public_child is not _DROP_PUBLIC_VALUE:
                clean_list.append(public_child)
        return clean_list
    if isinstance(value, tuple):
        return _public_value(list(value))
    return copy.deepcopy(value)


def public_result_payload(result: Any) -> dict[str, Any] | None:
    """Build a JSON-safe public result without exposing worker diagnostics."""
    if not isinstance(result, dict):
        return None
    clean = _public_value(result)
    if not isinstance(clean, dict):
        return None
    if isinstance(clean.get("result"), dict):
        clean = clean["result"]
    source = clean.get("source")
    if isinstance(source, dict):
        source.pop("text", None)
        source.pop("canonical_url", None)
    claims = clean.get("claims")
    if isinstance(claims, list):
        for claim in claims:
            if (
                isinstance(claim, dict)
                and "cope_score" in claim
                and not valid_public_score(claim.get("cope_score"))
            ):
                claim.pop("cope_score", None)
    return clean


@contextmanager
def state_file_lock(state_path: Path, exclusive: bool = True) -> Iterator[None]:
    """Coordinate server and timer read/modify/write cycles across processes."""
    lock_path = state_path.with_suffix(state_path.suffix + ".lock")
    lock_path.parent.mkdir(parents=True, exist_ok=True)
    with lock_path.open("a+") as handle:
        fcntl.flock(handle.fileno(), fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
        try:
            yield
        finally:
            fcntl.flock(handle.fileno(), fcntl.LOCK_UN)


def story_key(url: str | None) -> str:
    return canonical_url_hash(url)


def canonical_job_id(url: str | None) -> str:
    key = story_key(url)
    return "cc_" + key[:16] if key else ""


def job_story_key(job: dict[str, Any]) -> str:
    return str(job.get("story_key") or story_key(job.get("canonical_url") or job.get("url")))


def resolve_job_id(state: dict[str, Any], job_id: str) -> str:
    """Follow migration/runtime aliases without permitting alias loops."""
    aliases = state.get("job_aliases") if isinstance(state.get("job_aliases"), dict) else {}
    current = str(job_id)
    seen: set[str] = set()
    while current in aliases and current not in seen:
        seen.add(current)
        current = str(aliases[current])
    return current


def resolve_job(state: dict[str, Any], job_id: str) -> tuple[str, dict[str, Any] | None]:
    resolved = resolve_job_id(state, job_id)
    job = state.get("jobs", {}).get(resolved)
    return resolved, job if isinstance(job, dict) else None


def find_job_by_story_key(state: dict[str, Any], key: str) -> tuple[str, dict[str, Any]] | tuple[None, None]:
    if not key:
        return None, None
    story_aliases = state.get("story_aliases") if isinstance(state.get("story_aliases"), dict) else {}
    aliased_id = story_aliases.get(key)
    if aliased_id:
        resolved, job = resolve_job(state, str(aliased_id))
        if job:
            return resolved, job
    for job_id, job in state.get("jobs", {}).items():
        if not isinstance(job, dict):
            continue
        if job_story_key(job) == key:
            return str(job_id), job
        for observation in job.get("provenance") or []:
            if not isinstance(observation, dict):
                continue
            if story_key(observation.get("canonical_url") or observation.get("raw_url")) == key:
                return str(job_id), job
    return None, None


def _as_datetime(value: Any) -> datetime | None:
    try:
        parsed = datetime.fromisoformat(str(value or "").replace("Z", "+00:00"))
    except (TypeError, ValueError):
        return None
    if parsed.tzinfo is None:
        parsed = parsed.replace(tzinfo=timezone.utc)
    return parsed.astimezone(timezone.utc)


def event_parts(job: dict[str, Any]) -> tuple[str, str, str]:
    result = job.get("result") if isinstance(job.get("result"), dict) else {}
    source = result.get("source") if isinstance(result.get("source"), dict) else {}
    claims = result.get("claims") if isinstance(result.get("claims"), list) else []
    claim = claims[0] if claims and isinstance(claims[0], dict) else {}
    title = str(source.get("title") or job.get("story_title") or "")
    quote = str(
        claim.get("relevant_excerpt")
        or claim.get("claim_summary")
        or job.get("story_summary")
        or ""
    )
    observed = str(
        source.get("date_published")
        or job.get("story_published")
        or job.get("submitted_at")
        or ""
    )
    return title, quote, observed


def event_fingerprint(job: dict[str, Any]) -> str:
    title, quote, observed = event_parts(job)
    if normalise_text(quote) or normalise_text(title):
        return new_event_fingerprint("codex", title, quote, observed)
    return job_story_key(job)


def same_job_event(left: dict[str, Any], right: dict[str, Any], window_days: int = EVENT_WINDOW_DAYS) -> bool:
    left_canonical = canonical_url(left.get("canonical_url") or left.get("url"))
    right_canonical = canonical_url(right.get("canonical_url") or right.get("url"))
    if left_canonical and left_canonical == right_canonical:
        return True
    left_title, left_quote, left_observed = event_parts(left)
    right_title, right_quote, right_observed = event_parts(right)
    if exact_statement_match(left_title, left_quote, right_title, right_quote):
        return True
    left_at, right_at = _as_datetime(left_observed), _as_datetime(right_observed)
    within_window = bool(
        left_at and right_at
        and abs((left_at - right_at).total_seconds()) <= window_days * 86400
    )
    return within_window and same_event(
        canonical_a=left_canonical,
        title_a=left_title,
        quote_a=left_quote,
        canonical_b=right_canonical,
        title_b=right_title,
        quote_b=right_quote,
    )


def find_job_by_event(
    state: dict[str, Any], candidate: dict[str, Any], exclude_job_id: str | None = None,
) -> tuple[str, dict[str, Any]] | tuple[None, None]:
    key = job_story_key(candidate)
    existing_id, existing = find_job_by_story_key(state, key)
    if existing and existing_id != exclude_job_id:
        return existing_id, existing
    for job_id, job in state.get("jobs", {}).items():
        if str(job_id) == str(exclude_job_id) or not isinstance(job, dict):
            continue
        if same_job_event(candidate, job):
            return str(job_id), job
    return None, None


class JobEventIndex:
    """Run-local index for bounded story/event lookups.

    The RSS timer evaluates dozens of candidates against a large historic job
    ledger.  Re-scanning and normalising every historic result per candidate is
    quadratic and can hold the state lock for minutes.  This index preserves
    the same exact-resource, exact-statement, and seven-day fuzzy semantics
    while limiting fuzzy comparisons to nearby observation dates.
    """

    def __init__(self, state: dict[str, Any], window_days: int = EVENT_WINDOW_DAYS):
        self.state = state
        self.jobs = state.get("jobs") if isinstance(state.get("jobs"), dict) else {}
        self.window_days = window_days
        self.story_keys: dict[str, str] = {}
        self.exact_quotes: dict[str, str] = {}
        self.containment_quotes: list[tuple[str, str]] = []
        self.by_day: dict[int, list[str]] = defaultdict(list)

        # A live resource owns its key before publisher-provenance aliases.
        for job_id in sorted(self.jobs):
            job = self.jobs[job_id]
            if isinstance(job, dict):
                key = job_story_key(job)
                if key:
                    self.story_keys[key] = str(job_id)
        for job_id in sorted(self.jobs):
            job = self.jobs[job_id]
            if isinstance(job, dict):
                self._add_event_fields(str(job_id), job)
                for observation in job.get("provenance") or []:
                    if not isinstance(observation, dict):
                        continue
                    key = story_key(observation.get("canonical_url") or observation.get("raw_url"))
                    if key:
                        self.story_keys.setdefault(key, str(job_id))

    def _add_event_fields(self, job_id: str, job: dict[str, Any]) -> None:
        title, quote, observed = event_parts(job)
        title_n, quote_n = normalise_text(title), normalise_text(quote)
        if len(quote_n) >= 40:
            self.exact_quotes.setdefault(quote_n, job_id)
        if len(quote_n) >= 60 and len(quote_n.split()) >= 10:
            self.containment_quotes.append((job_id, quote_n))
        parsed = _as_datetime(observed)
        if parsed:
            self.by_day[parsed.date().toordinal()].append(job_id)

    def add(self, job_id: str, job: dict[str, Any]) -> None:
        key = job_story_key(job)
        if key:
            self.story_keys[key] = str(job_id)
        self._add_event_fields(str(job_id), job)
        for observation in job.get("provenance") or []:
            if isinstance(observation, dict):
                key = story_key(observation.get("canonical_url") or observation.get("raw_url"))
                if key:
                    self.story_keys.setdefault(key, str(job_id))

    def register_story_key(self, key: str, job_id: str) -> None:
        if key:
            self.story_keys[key] = str(job_id)

    def find(
        self, candidate: dict[str, Any], exclude_job_id: str | None = None,
    ) -> tuple[str, dict[str, Any]] | tuple[None, None]:
        key = job_story_key(candidate)
        direct_id = self.story_keys.get(key)
        if direct_id and direct_id != exclude_job_id:
            job = self.jobs.get(direct_id)
            if isinstance(job, dict):
                return direct_id, job

        title, quote, observed = event_parts(candidate)
        title_n, quote_n = normalise_text(title), normalise_text(quote)
        exact_ids = []
        if len(quote_n) >= 40 and quote_n in self.exact_quotes:
            exact_ids.append(self.exact_quotes[quote_n])
        for job_id in exact_ids:
            if job_id == exclude_job_id:
                continue
            job = self.jobs.get(job_id)
            if isinstance(job, dict):
                return job_id, job

        # Preserve exact_statement_match's timeless contained-quote rule.  A
        # pre-normalised linear substring check is cheap at this corpus size
        # and avoids the old quadratic normalisation/SequenceMatcher cost.
        if len(quote_n) >= 60 and len(quote_n.split()) >= 10:
            for job_id, existing_quote in self.containment_quotes:
                if job_id == exclude_job_id:
                    continue
                shorter, longer = sorted((quote_n, existing_quote), key=len)
                if len(shorter) >= 60 and len(shorter.split()) >= 10 and shorter in longer:
                    job = self.jobs.get(job_id)
                    if isinstance(job, dict):
                        return job_id, job

        parsed = _as_datetime(observed)
        if not parsed:
            return None, None
        ordinal = parsed.date().toordinal()
        seen: set[str] = set()
        for day in range(ordinal - self.window_days, ordinal + self.window_days + 1):
            for job_id in self.by_day.get(day, []):
                if job_id in seen or job_id == exclude_job_id:
                    continue
                seen.add(job_id)
                job = self.jobs.get(job_id)
                if isinstance(job, dict) and same_job_event(candidate, job, self.window_days):
                    return job_id, job
        return None, None


def provenance_observation(
    job: dict[str, Any],
    legacy_job_id: str | None = None,
    *,
    include_legacy_id: bool = True,
) -> dict[str, Any]:
    result = job.get("result") if isinstance(job.get("result"), dict) else {}
    source_result = result.get("source") if isinstance(result.get("source"), dict) else {}
    claims = result.get("claims") if isinstance(result.get("claims"), list) else []
    first_claim = claims[0] if claims and isinstance(claims[0], dict) else {}
    raw_url = str(source_result.get("url") or job.get("url") or "")
    canonical = canonical_url(source_result.get("canonical_url") or raw_url)
    title = str(source_result.get("title") or job.get("story_title") or "")
    quote = str(first_claim.get("relevant_excerpt") or job.get("story_summary") or "")
    channel = str(job.get("route_target") or job.get("channel") or "")
    feed = str(job.get("feed") or "")
    source = str(job.get("source") or "")
    legacy_id = (legacy_job_id or job.get("job_id")) if include_legacy_id else None
    # Historic jobs are individual observations even when two state rows are
    # byte-for-byte equal.  Including the legacy ID keeps every removed row
    # independently auditable; runtime feed captures use story_observation's
    # source/feed/channel key and remain idempotent across repeated scans.
    key_title = (
        f"{title}\nsource:{source}\nfeed:{feed}\nchannel:{channel}"
        f"\nlegacy-job:{legacy_id or ''}"
    )
    observation = {
        "observation_key": provenance_key(canonical, key_title, quote),
        "raw_url": raw_url,
        "canonical_url": canonical,
        "source_title": title or None,
        "publisher": source_result.get("publisher"),
        "source": source or None,
        "feed": feed or None,
        "channel": channel or None,
        "observed_at": job.get("story_published") or job.get("submitted_at"),
        "legacy_status": job.get("status"),
    }
    if legacy_id:
        observation["legacy_job_id"] = legacy_id
    return observation


def add_job_provenance(job: dict[str, Any], observation: dict[str, Any]) -> bool:
    provenance = job.setdefault("provenance", [])
    key = observation.get("observation_key")
    if any(isinstance(item, dict) and item.get("observation_key") == key for item in provenance):
        return False
    provenance.append({key: value for key, value in observation.items() if value is not None})
    job["provenance_count"] = len(provenance)
    job["channels"] = sorted({
        str(item.get("channel"))
        for item in provenance
        if isinstance(item, dict) and item.get("channel")
    })
    return True


def _has_legacy_observation(job: dict[str, Any], legacy_job_id: str | None) -> bool:
    if not legacy_job_id:
        return False
    return any(
        isinstance(item, dict) and str(item.get("legacy_job_id") or "") == str(legacy_job_id)
        for item in job.get("provenance") or []
    )


def ensure_job_identity(job: dict[str, Any], legacy_job_id: str | None = None) -> bool:
    raw_url = str(job.get("url") or "")
    canonical = canonical_url(raw_url)
    key = canonical_url_hash(canonical)
    changed = False
    if job.get("canonical_url") != canonical:
        job["canonical_url"] = canonical
        changed = True
    if job.get("story_key") != key:
        job["story_key"] = key
        changed = True
    fingerprint = event_fingerprint(job)
    if fingerprint and job.get("event_fingerprint") != fingerprint:
        job["event_fingerprint"] = fingerprint
        changed = True
    _title, _quote, observed = event_parts(job)
    if observed and job.get("event_observed_at") != observed:
        job["event_observed_at"] = observed
        changed = True
    provenance = job.get("provenance")
    if not isinstance(provenance, list) or not provenance:
        changed = add_job_provenance(job, provenance_observation(job, legacy_job_id)) or changed
        provenance = job.get("provenance") or []
    elif legacy_job_id and not _has_legacy_observation(job, legacy_job_id):
        unclaimed = next(
            (
                item for item in provenance
                if isinstance(item, dict) and not item.get("legacy_job_id")
            ),
            None,
        )
        if unclaimed is not None:
            unclaimed["legacy_job_id"] = legacy_job_id
            changed = True
        else:
            changed = add_job_provenance(
                job, provenance_observation(job, legacy_job_id)
            ) or changed
            provenance = job.get("provenance") or []
    if job.get("provenance_count") != len(provenance):
        job["provenance_count"] = len(provenance)
        changed = True
    channels = sorted({
        str(item.get("channel"))
        for item in provenance
        if isinstance(item, dict) and item.get("channel")
    })
    if job.get("channels") != channels:
        job["channels"] = channels
        changed = True
    return changed


def register_story_aliases(state: dict[str, Any], job_id: str, job: dict[str, Any]) -> None:
    aliases = state.setdefault("story_aliases", {})
    own_key = job_story_key(job)
    if own_key:
        # A live job's own canonical URL always outranks a URL that merely
        # appears in another job's publisher provenance.
        aliases[own_key] = job_id
    for observation in job.get("provenance") or []:
        if isinstance(observation, dict):
            key = story_key(observation.get("canonical_url") or observation.get("raw_url"))
            if key:
                aliases.setdefault(key, job_id)


def rebuild_story_aliases(state: dict[str, Any]) -> None:
    """Build stable aliases with live resource ownership taking precedence."""
    jobs = state.get("jobs") if isinstance(state.get("jobs"), dict) else {}
    aliases: dict[str, str] = {}
    for job_id in sorted(jobs):
        job = jobs[job_id]
        if not isinstance(job, dict):
            continue
        key = job_story_key(job)
        if key:
            aliases[key] = job_id
    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
            key = story_key(observation.get("canonical_url") or observation.get("raw_url"))
            if key:
                aliases.setdefault(key, job_id)
    state["story_aliases"] = aliases


def archive_duplicate_job(
    state: dict[str, Any], primary_id: str, duplicate_id: str, reason: str,
) -> dict[str, Any]:
    jobs = state.setdefault("jobs", {})
    primary = jobs[primary_id]
    duplicate = jobs[duplicate_id]
    ensure_job_identity(primary, primary_id)
    ensure_job_identity(duplicate, duplicate_id)
    for observation in duplicate.get("provenance") or []:
        if isinstance(observation, dict):
            add_job_provenance(primary, observation)
    if not _has_legacy_observation(primary, duplicate_id):
        add_job_provenance(primary, provenance_observation(duplicate, duplicate_id))
    archived = copy.deepcopy(duplicate)
    archived["duplicate_of"] = primary_id
    archived["duplicate_reason"] = reason
    state.setdefault("duplicate_jobs", {})[duplicate_id] = archived
    state.setdefault("job_aliases", {})[duplicate_id] = primary_id
    register_story_aliases(state, primary_id, primary)
    register_story_aliases(state, primary_id, duplicate)
    del jobs[duplicate_id]
    return primary


def atomic_write_json(path: Path, data: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    old_stat = path.stat() if path.exists() else None
    with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as handle:
        json.dump(data, handle, ensure_ascii=False, separators=(",", ":"))
        handle.write("\n")
        tmp_path = Path(handle.name)
    if old_stat:
        os.chmod(tmp_path, old_stat.st_mode & 0o777)
        try:
            os.chown(tmp_path, old_stat.st_uid, old_stat.st_gid)
        except PermissionError:
            pass
    os.replace(tmp_path, path)
```
