GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/news

Grid and 2 more files (part 1)

A Python command-line tool in the dc context folder of GlobalGrid2050 that uses SHA-256. It is built from the dumps step (`dumps`) and the build step (`build`).

547 lines of Python from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 781 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Datacentre Feed energy-data · globalgrid2050 / automation/news/datacentre_feed.py lines 470–504
  2. Grid ingest · globalgrid2050 / automation/news/dc_context/grid.py lines 1–265
  3. Engine ingest · globalgrid2050 / automation/news/engine.py lines 1–247

Datacentre Feed

A Python command-line tool in the news folder of GlobalGrid2050 that fetches datacentre news, datacentre proximity, datacentre pinned and the Renewable Energy Planning Database (REPD) register, using SHA-256.

energy-dataglobalgrid2050 / automation/news/datacentre_feed.py · lines 470–504 of 504 (continued from section 780) · Entry point · pattern fetch_url (shared by 2 files)

What it does
It fetches datacentre news, datacentre proximity, datacentre pinned and the REPD register. Defines 25 functions or classes, including _compile, clean_text, canonical_link, parse_date, parse_calendar_day. Uses libraries __future__, argparse, datetime, email.utils, hashlib. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'datacentre'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file datacentre_news.json; JSON file datacentre_proximity.json; JSON file datacentre_pinned.json; command-line arguments.
Downstream impact
Used directly by 7 files: Pipeline Headlines (globalgrid2050); Research Indexes (globalgrid2050); Official (globalgrid2050); Trade (globalgrid2050); and 3 more. Reached from 20 other entry points, including GlobalGrid2050 Agent7 V922 CI Workflow (globalgrid2050); GlobalGrid2050 Pipeline Headlines Workflow (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050).
What it achieves
It cleans text (`clean_text`), parses date (`parse_date`) and parses calendar day (`parse_calendar_day`). Data-centre capex and politics headlines for Pipeline News (owner line 11, 14 Nov 2026). It accepts `--out`, `--proximity` and `--register`.
Why it matters
Imported by 4 files, including Pipeline Headlines, Research Indexes and Official. Run by GlobalGrid2050 Datacentre News Workflow. Checked by 2 tests, including Test Datacentre Feed.
Application
globalgrid2050 · automation/news · Python CLI
Uses
Dates (import), __future__, argparse, datetime, email.utils, hashlib, html, json, re
Used by
imported by Pipeline Headlines (import), imported by Research Indexes (import), imported by Official (sys.path import), imported by Trade (sys.path import), imported by Test Datacentre Feed (sys.path import), imported by Test Pipeline Headlines (sys.path import), run by GlobalGrid2050 Datacentre News Workflow (workflow run)
Produces
clean_text, canonical_link, parse_date, parse_calendar_day, parse_feed, capex_basis, matches, classify, repd_context, Register, fetch_url, collect
Defines here
fetch, fixture_name
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/datacentre_feed.py:470-504 · blob 98caaa3afa2f3712b56cf4b027fda48f2b40653d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
        except ValueError:
            previous = {}
    register = Register.load(args.proximity, args.register)

    if args.fixtures:
        fixture_dir = Path(args.fixtures)

        def fetch(url):
            path = fixture_dir / (fixture_name(url))
            if not path.exists():
                raise OSError("no fixture for %s" % url)
            return path.read_bytes()
    else:
        fetch = fetch_url

    items, health = collect(FEEDS, fetch, register, now_iso)
    items.extend(load_pinned(args.pinned, now_iso))
    result = build(previous, items, health, now_iso, args.max_items)
    out.parent.mkdir(parents=True, exist_ok=True)
    tmp = out.with_suffix(".tmp")
    tmp.write_text(json.dumps(result, ensure_ascii=False, indent=1, sort_keys=False) + "\n", encoding="utf-8")
    tmp.replace(out)
    print(json.dumps({"status": result["status"], **result["counts"], "register_records": len(register.records),
                      "out": str(out)}))
    if result["status"] == "failed" and not previous:
        return 1
    return 0


def fixture_name(url):
    return hashlib.sha256(url.encode()).hexdigest()[:16] + ".xml"


if __name__ == "__main__":
    sys.exit(main())

Grid

A Python command-line tool in the dc context folder of GlobalGrid2050 that uses SHA-256. It is built from the dumps step (`dumps`) and the build step (`build`).

ingestglobalgrid2050 / automation/news/dc_context/grid.py · lines 1–265 of 265 · Entry point · pattern _identifier (shared by 2 files)

What it does
It loads data. Defines 11 functions or classes, including _require, _object, _text, _identifier, _day. Uses libraries __future__, argparse, copy, datetime, hashlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'dc'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 3 files: Build Transition Context (globalgrid2050); Test Grid DC Context (globalgrid2050); Test Transition Context (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Offline, provisional grid/data-centre context; no network or inference. It accepts `--input`, `--as-of` and `--output`.
Why it matters
Imported by Build Transition Context. Checked by 2 tests, including Test Grid DC Context.
Application
globalgrid2050 · automation/news/dc_context · Python CLI
Uses
Contracts (import), __future__, argparse, copy, datetime, hashlib, json, pathlib, re
Used by
imported by Build Transition Context (import), imported by Test Grid DC Context (import), imported by Test Transition Context (import)
Produces
dumps, build, main
Defines here
_require, _object, _text, _identifier, _day, _time, dumps, _source, _figures, build, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/dc_context/grid.py:1-265 · blob 79d7d06ec96727cc1e939965cafa0ea5909744e6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
"""Offline, provisional grid/data-centre context; no network or inference.

The public ``build(bundle, *, as_of)`` API preserves dated source states and
uses the shared filings FIGURES validator for optional quantitative claims.
Context identifiers are local document-context keys, never official site IDs.
There is no geospatial matching, scoring, current-status or connection inference.
"""
from __future__ import annotations

import argparse
from copy import deepcopy
from datetime import date, datetime
import hashlib
import json
from pathlib import Path
import re
from urllib.parse import urlsplit

INPUT_SCHEMA = "globalgrid2050.grid-dc-context-input.v1"
SCHEMA = "globalgrid2050.grid-dc-context.v1"
_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}\Z")
_SHA = re.compile(r"[a-f0-9]{64}\Z")
_SOURCE_KEYS = {
    "id", "document_id", "url", "publisher", "authority", "title",
    "published_date", "retrieved_at", "http_status", "sha256", "bytes",
    "access_state", "output_policy",
}
_CONTEXT_KEYS = {
    "id", "name", "country", "entity_scope", "source_entity_reference",
    "source_id", "section", "page", "kind", "source_state",
    "numeric_claims", "figures_omitted_reason",
}
_PRIMARY_HOSTS = {"www.gov.uk": "GOVERNMENT", "www.ferc.gov": "REGULATOR"}
# Values are separate dimensions: source state, permitted numeric kind/basis,
# and a research action. No rule awards investment value or available power.
_RULES = {
    ("development_proposal", "PROPOSED"): (
        {"project_demand", "it_load"}, {"forecast"},
        "Seek a named development scheme, planning record and dated connection evidence."),
    ("connection_amendment_decision", "REJECTED"): (
        {"project_demand"}, {"forecast"},
        "Check later docket decisions; rejection of this amendment does not reject every existing arrangement."),
    ("connection_offer", "OFFER_REPORTED"): (
        {"secured_connection"}, {"reported"},
        "Check the offer's conditions, validity and subsequent delivery; an offer is not energisation."),
    ("energisation_report", "ENERGISED_REPORTED"): (
        {"energised_load"}, {"reported"},
        "Check the reported date and exact energised phase; do not extend it to an entire campus."),
    ("grid_upgrade", "PLANNED"): (
        {"grid_upgrade"}, {"forecast"},
        "Check the named upgrade, consent and delivery evidence; planned network work is not available capacity."),
    ("grid_upgrade", "COMMISSIONED_REPORTED"): (
        {"grid_upgrade"}, {"reported"},
        "Check the commissioned asset scope; its rating is not a data-centre connection allocation."),
    ("funding", "ANNOUNCED"): (
        {"finance"}, {"reported", "forecast"},
        "Check committed and disbursed funding separately; announced funding is not expenditure."),
    ("funding", "COMMITTED"): (
        {"finance"}, {"reported"},
        "Check funding conditions and disbursement; a commitment is not paid project CAPEX."),
    ("funding", "DISBURSED"): (
        {"finance"}, {"reported"},
        "Keep the disclosed payment scope; do not allocate portfolio totals to an individual site."),
}


def _require(condition, message):
    if not condition:
        raise ValueError(message)


def _object(value, keys, field):
    _require(isinstance(value, dict) and set(value) == keys, f"{field}: unexpected fields")


def _text(value, field, *, limit=250):
    _require(isinstance(value, str) and 0 < len(value) <= limit
             and value == value.strip()
             and not any(ord(c) < 32 or ord(c) == 127 or 0xD800 <= ord(c) <= 0xDFFF for c in value)
             and not any(c in value for c in "<>"), f"{field}: invalid plain text")


def _identifier(value, field):
    _require(isinstance(value, str) and bool(_ID.fullmatch(value)), f"{field}: invalid identifier")


def _day(value, field):
    _require(isinstance(value, str) and bool(re.fullmatch(r"\d{4}-\d{2}-\d{2}", value)),
             f"{field}: explicit calendar day required")
    try:
        return date.fromisoformat(value)
    except ValueError as exc:
        raise ValueError(f"{field}: invalid day") from exc


def _time(value, field):
    _require(isinstance(value, str) and bool(re.fullmatch(
        r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z", value)),
        f"{field}: explicit UTC timestamp required")
    try:
        return datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError as exc:
        raise ValueError(f"{field}: invalid timestamp") from exc


def dumps(value):
    """Stable JSON bytes for hashing/replay; preserves exact decimal strings."""
    return json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False) + "\n"


def _source(source, as_of):
    _object(source, _SOURCE_KEYS, "source")
    for key in ("id", "document_id"):
        _identifier(source[key], f"source.{key}")
    for key in ("publisher", "title"):
        _text(source[key], f"source.{key}")
    url = source["url"]
    _text(url, "source.url", limit=2048)
    _require(url.isascii() and "\\" not in url and not any(c.isspace() for c in url), "source.url: unsafe syntax")
    parsed = urlsplit(url)
    _require(parsed.scheme == "https" and parsed.netloc in _PRIMARY_HOSTS
             and parsed.path.startswith("/") and not parsed.query and not parsed.fragment,
             "source.url: unsupported primary-source URL")
    _require(source["authority"] == _PRIMARY_HOSTS[parsed.netloc], "source.authority: host mismatch")
    _require(type(source["http_status"]) is int and source["http_status"] == 200,
             "source: successful source receipt required")
    _require(isinstance(source["sha256"], str) and bool(_SHA.fullmatch(source["sha256"])), "source: invalid digest")
    _require(type(source["bytes"]) is int and 0 < source["bytes"] <= 4 * 1024 * 1024,
             "source: invalid bounded response size")
    _require(source["access_state"] == "OPEN_OBSERVED" and source["output_policy"] == "FACT_METADATA_ONLY",
             "source: unsupported access/display policy")
    retrieved = _time(source["retrieved_at"], "source.retrieved_at")
    published = _day(source["published_date"], "source.published_date")
    _require(published <= retrieved.date() and retrieved <= as_of, "source: inconsistent or future clocks")


def _figures(context, source, kinds, bases):
    figures = context["numeric_claims"]
    _require(isinstance(figures, list) and len(figures) <= 20, "context: bounded numeric_claims required")
    if not figures:
        return []
    # The FIGURES producer owns this dependency; no duplicated numeric schema.
    from automation.news.filings.contracts import validate_claim
    result, seen = [], set()
    for raw in figures:
        claim = validate_claim(raw)
        _require(claim["claim_id"] not in seen, "context: duplicate numeric claim")
        seen.add(claim["claim_id"])
        _require(claim["quantity_kind"] in kinds and claim["basis"] in bases,
                 "context: numeric kind/basis contradicts source state")
        entity = claim["entity"]
        _require(entity["id"] == context["id"] and entity["scope"] == context["entity_scope"]
                 and entity["consolidation_group_id"] is None
                 and entity["identity_evidence_url"] == source["url"],
                 "context: numeric entity/scope mismatch")
        provenance = claim["provenance"]
        for claim_key, source_key in (("document_id", "document_id"), ("document_url", "url"),
                                      ("sha256", "sha256"), ("published_date", "published_date"),
                                      ("retrieved_at", "retrieved_at")):
            _require(provenance[claim_key] == source[source_key], "context: numeric provenance mismatch")
        _require(provenance["page"] == context["page"] and provenance["section"] == context["section"],
                 "context: numeric locator mismatch")
        if claim["quantity_kind"] == "finance":
            _require(claim["finance_stage"] == context["source_state"].lower(),
                     "context: finance stage mismatch")
        result.append(claim)
    return sorted(result, key=lambda c: c["claim_id"])


def build(bundle, *, as_of):
    """Validate the whole input and return deterministic, unlinked context.

    Every supplied source and context is checked before output. Source hashes
    are receipts, not independent verification of the source or extraction.
    The result never turns its internal context key into an official DC ID.
    """
    _object(bundle, {"schema", "sources", "contexts"}, "bundle")
    _require(bundle["schema"] == INPUT_SCHEMA, "bundle: unsupported schema")
    clock = _time(as_of, "as_of")
    sources, contexts = bundle["sources"], bundle["contexts"]
    _require(isinstance(sources, list) and 0 < len(sources) <= 100, "bundle: source bound")
    _require(isinstance(contexts, list) and 0 < len(contexts) <= 1000, "bundle: context bound")
    by_source, source_documents = {}, set()
    for source in sources:
        _source(source, clock)
        _require(source["id"] not in by_source and source["document_id"] not in source_documents,
                 "bundle: duplicate source/document")
        by_source[source["id"]] = source
        source_documents.add(source["document_id"])
    records, seen_ids, figure_ids = [], set(), set()
    for context in contexts:
        _object(context, _CONTEXT_KEYS, "context")
        _identifier(context["id"], "context.id")
        _identifier(context["source_id"], "context.source_id")
        _require(context["id"] not in seen_ids, "bundle: duplicate context")
        seen_ids.add(context["id"])
        _require(context["source_id"] in by_source, "context: unknown source")
        source = by_source[context["source_id"]]
        for key in ("name", "source_entity_reference"):
            _text(context[key], f"context.{key}")
        for key in ("section", "page", "figures_omitted_reason"):
            if context[key] is not None:
                _text(context[key], f"context.{key}", limit=400)
        _require(context["section"] is not None or context["page"] is not None, "context: locator required")
        _require(isinstance(context["country"], str) and context["country"] in {"GB", "US"},
                 "context: unsupported source country")
        _require(isinstance(context["entity_scope"], str)
                 and context["entity_scope"] in {"project", "site", "campus", "phase", "zone"},
                 "context: unsupported entity scope")
        _require(isinstance(context["kind"], str) and isinstance(context["source_state"], str),
                 "context: kind/state must be text")
        key = (context["kind"], context["source_state"])
        _require(key in _RULES, "context: unsupported kind/source-state combination")
        kinds, bases, action = _RULES[key]
        figures = _figures(context, source, kinds, bases)
        _require(not figures or context["figures_omitted_reason"] is None,
                 "context: figures and omission reason conflict")
        _require(not figure_ids.intersection(c["claim_id"] for c in figures), "bundle: repeated numeric claim")
        figure_ids.update(c["claim_id"] for c in figures)
        record = deepcopy(context)
        record["numeric_claims"] = figures
        record.update({
            "status": "PROVISIONAL", "current_project_state": "UNKNOWN",
            "canonical_project_id": None, "binding_basis": "DOCUMENT_CONTEXT_ONLY",
            "source": deepcopy(source),
            "source_document_age_days": (clock.date() - _day(source["published_date"], "source.published_date")).days,
            "retrieval_age_days": (clock - _time(source["retrieved_at"], "source.retrieved_at")).days,
            "research_action": action,
            "current_secured_connection": None, "current_energised_load": None,
            "available_grid_capacity": None, "site_capex": None,
        })
        records.append(record)
    normalized_input = {"schema": INPUT_SCHEMA,
                        "sources": sorted(deepcopy(sources), key=lambda s: s["id"]),
                        "contexts": sorted(deepcopy(contexts), key=lambda c: c["id"])}
    return {
        "schema": SCHEMA, "as_of": as_of,
        "input_sha256": hashlib.sha256(dumps(normalized_input).encode("utf-8")).hexdigest(),
        "context_count": len(records), "numeric_claim_count": len(figure_ids),
        "linked_project_count": 0, "records": sorted(records, key=lambda c: c["id"]),
        "limitations": ["Dated document context; current delivery and ownership are not established.",
                        "No site crosswalk, proximity inference, aggregation, ranking or publication approval.",
                        "Successful source retrieval is not independent factual or numerical verification."],
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input", type=Path, required=True)
    parser.add_argument("--as-of", required=True)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()
    _require(args.input.stat().st_size <= 4 * 1024 * 1024, "input: maximum size exceeded")
    result = dumps(build(json.loads(args.input.read_text(encoding="utf-8")), as_of=args.as_of))
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        # A new artifact is required; no overwrite or pointer update.
        with args.output.open("x", encoding="utf-8", newline="\n") as handle:
            handle.write(result)
    else:
        print(result, end="")


if __name__ == "__main__":
    main()

Engine

A Python command-line tool in the news folder of GlobalGrid2050 that reads the Renewable Energy Planning Database (REPD) register, using SHA-256.

ingestglobalgrid2050 / automation/news/engine.py · lines 1–247 of 247 · Entry point · pattern canonical_url (shared by 2 files)

What it does
It loads the REPD register. Defines 8 functions or classes, including _required, canonical_url, _checked_timestamp, _sources, _projects. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 2 files: Test Engine (globalgrid2050); Test Engine Independent (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It builds intelligence (`build_intelligence`) and is built from the canonical URL helper (`canonical_url`) and the read step (`read`). Ventus News Engine: read-only, deterministic intelligence adapter. It accepts `--articles`, `--sources` and `--projects`.
Why it matters
Checked by 2 tests, including Test Engine.
Application
globalgrid2050 · automation/news · Python CLI
Uses
Match (relative import), __future__, argparse, datetime, hashlib, json, pathlib, re, urllib.parse
Used by
imported by Test Engine (import), imported by Test Engine Independent (import)
Produces
canonical_url, build_intelligence, main
Defines here
_required, canonical_url, _checked_timestamp, _sources, _projects, build_intelligence, main, read
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/engine.py:1-247 · blob 06474b955a63fcd2bc36ecaf9571ee8e3412d460 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Ventus News Engine: read-only, deterministic intelligence adapter.

Consumes existing collector output; never fetches, schedules, approves rights,
verifies identities, or publishes. Uses acquisition.match.match_articles.
"""
from __future__ import annotations

import argparse
from datetime import date, datetime
import hashlib
import json
from pathlib import Path
import re
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

from .acquisition.match import match_articles

SCHEMA = "globalgrid2050.ventus-news-intelligence.v1"
VERTICALS = frozenset(("solar", "bess", "wind", "grid", "datacentre"))
_SHA = re.compile(r"[0-9a-f]{64}\Z")
_DNS = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z")
_TRACKING = frozenset(("fbclid", "gclid", "mc_cid", "mc_eid"))


def _required(value, field):
    if not isinstance(value, str) or not value.strip():
        raise ValueError(field + " must be nonempty text")
    return value


def canonical_url(value):
    """Validate public HTTPS metadata, strip fragment/known tracking; never fetch."""
    _required(value, "article URL")
    if any(ord(c) < 33 for c in value) or "\\" in value:
        raise ValueError("unsafe article URL")
    try:
        p = urlsplit(value)
        host = (p.hostname or "").lower().rstrip(".")
        labels = host.split(".")
        if (p.scheme != "https" or p.username or p.password or p.port not in (None, 443)
                or len(labels) < 2 or any(not _DNS.fullmatch(label) for label in labels)
                or labels[-1].isdigit() or labels[-1].startswith("0x")
                or host.endswith((".localhost", ".local", ".internal"))):
            raise ValueError("unsafe public HTTPS URL")
    except ValueError as exc:
        raise ValueError("unsafe public HTTPS URL") from exc
    query = urlencode([(k, v) for k, v in parse_qsl(p.query, keep_blank_values=True)
                       if not (k.lower().startswith("utm_") or k.lower() in _TRACKING)])
    return urlunsplit(("https", host, p.path or "/", query, ""))


def _checked_timestamp(value, field):
    """Keep original ISO date text but reject impossible or malformed clocks.

    These are metadata validation checks only; not independent publisher evidence.
    """
    if value is None:
        return None
    if not isinstance(value, str):
        raise ValueError(field + " timestamp must be text or null")
    try:
        if re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value):
            date.fromisoformat(value)
        elif re.fullmatch(
            r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}"
            r"(?::[0-9]{2}(?:\.[0-9]{1,6})?)?(?:Z|[+-][0-9]{2}:[0-9]{2})?",
            value,
        ):
            datetime.fromisoformat(value.replace("Z", "+00:00"))
        else:
            raise ValueError("bad timestamp format")
    except ValueError as exc:
        raise ValueError(field + " invalid timestamp") from exc
    return value


def _sources(rows):
    if not isinstance(rows, list):
        raise ValueError("sources must be an array")
    result = {}
    for raw in rows:
        if not isinstance(raw, dict):
            raise ValueError("invalid source")
        sid = _required(raw.get("id"), "source.id")
        if sid in result:
            raise ValueError("duplicate source id")
        publisher = _required(raw.get("publisher"), "source.publisher")
        status = raw.get("rights_status", "unknown")
        if status not in ("unknown", "accepted", "rejected"):
            raise ValueError("unrecognised source rights_status")
        review = raw.get("rights_review_url")
        if review is not None:
            canonical_url(review)
        if status == "accepted" and not review:
            raise ValueError("accepted rights require a review URL")
        policy = raw.get("output_policy", "headline_link_only")
        if policy != "headline_link_only":
            raise ValueError("engine can only process headline_link_only sources")
        enabled = raw.get("enabled", False)
        if type(enabled) is not bool:
            raise ValueError("source.enabled must be boolean")
        if enabled and status != "accepted":
            raise ValueError("unreviewed source cannot be enabled")
        result[sid] = {"id": sid, "publisher": publisher,
                       "kind": raw.get("kind"), "enabled": enabled,
                       "rights_status": status, "rights_review_url": review,
                       "output_policy": policy}
    return result


def _projects(rows):
    if not isinstance(rows, list):
        raise ValueError("projects must be an array")
    projects, seen = [], set()
    for p in rows:
        if not isinstance(p, dict):
            raise ValueError("invalid project")
        namespace = p.get("namespace", "repd")
        pid = str(p.get("id", ""))
        if namespace != "repd":
            # Future DC/grid adapters must use their own stable identities.
            continue
        if not re.fullmatch(r"[1-9][0-9]*", pid) or pid in seen:
            raise ValueError("invalid or duplicate REPD identifier")
        seen.add(pid)
        projects.append({"id": pid, "name": _required(p.get("name"), "project.name"),
                         "name_ambiguous": p.get("name_ambiguous", False),
                         "technology": p.get("technology")})
    return projects


def build_intelligence(articles, sources, projects=()):
    """Return offline metadata candidates; zero VERIFIED matches by construction."""
    if isinstance(articles, dict):
        articles = articles.get("items")
    if not isinstance(articles, list):
        raise ValueError("articles must be an array or a document with items")
    policies = _sources(sources)
    repd = _projects(list(projects))
    by_publisher = {}
    for sid, source in policies.items():
        by_publisher.setdefault(source["publisher"], []).append(sid)
    by_url = {}
    for a in articles:
        if not isinstance(a, dict):
            raise ValueError("invalid article")
        original = _required(a.get("url") or a.get("link"), "article.url")
        url = canonical_url(original)
        title = _required(a.get("title"), "article.title")
        sid = a.get("source_id")
        if sid is None:
            labels = by_publisher.get(a.get("source"), [])
            if len(labels) != 1:
                raise ValueError("article needs unambiguous source_id")
            sid = labels[0]
        if sid not in policies:
            raise ValueError("article references missing source")
        src = policies[sid]
        if a.get("publisher", src["publisher"]) != src["publisher"]:
            raise ValueError("publisher attribution conflicts with source")
        if a.get("source") is not None and a["source"] != src["publisher"]:
            raise ValueError("publisher attribution conflicts with source label")
        published = _checked_timestamp(a.get("pub_date", a.get("date")), "publication")
        first_seen = _checked_timestamp(a.get("first_seen"), "first_seen")
        fetched = _checked_timestamp(a.get("fetched_at"), "fetched_at")
        receipt = a.get("source_receipt_sha256")
        if receipt is not None and (not isinstance(receipt, str) or not _SHA.fullmatch(receipt)):
            raise ValueError("invalid source receipt hash")
        vertical = a.get("vertical")
        if vertical is not None and vertical not in VERTICALS:
            raise ValueError("unknown vertical")
        row = {"article_id": hashlib.sha256(url.encode("utf-8")).hexdigest(),
               "original_article_url": original, "observed_article_urls": [original],
               "canonical_article_url": url,
               "title": title, "publisher": src["publisher"], "source_id": sid,
               "published_at": published, "first_seen": first_seen,
               "fetched_at": fetched, "source_receipt_sha256": receipt,
               "vertical": vertical, "source_kind": src["kind"],
               "usage_rights": {"status": src["rights_status"],
                                "review_url": src["rights_review_url"],
                                "source_enabled": src["enabled"]},
               "headline_link_scope_only": src["output_policy"] == "headline_link_only",
               "publisher_independence": "UNASSESSED",
               "verification_status": "NOT_VERIFIED",
               "publication_eligibility": "WITHHELD_INDEPENDENT_REVIEW_REQUIRED",
               "project_candidates": []}
        if url in by_url:
            previous = by_url[url]
            comparable = dict(row)
            comparable["original_article_url"] = previous["original_article_url"]
            comparable["observed_article_urls"] = previous["observed_article_urls"]
            if previous != comparable:
                raise ValueError("canonical URL collision requires attribution review")
            variants = sorted(set(previous["observed_article_urls"] + [original]))
            previous["observed_article_urls"] = variants
            previous["original_article_url"] = variants[0]
            continue
        by_url[url] = row
    match_input = [{"title": row["title"], "url": url} for url, row in by_url.items()]
    candidates = match_articles(match_input, repd)
    for edge in candidates:
        row = by_url[edge["article_url"]]
        row["project_candidates"].append({"namespace": "repd", "id": edge["project_id"],
                                          "method": edge["match_method"],
                                          "status": "PROVISIONAL", "evidence_scope": "TITLE_ONLY",
                                          "independent_review": "REQUIRED"})
    for row in by_url.values():
        edges = row["project_candidates"]
        edges.sort(key=lambda e: (int(e["id"]), e["method"]))
        if len(edges) > 1:
            for edge in edges:
                edge["ambiguous_multi_project"] = True
    return {"schema": SCHEMA,
            "scope": "offline headline/link metadata; no source fetch or inferred verified claims",
            "counts": {"articles": len(by_url),
                       "provisional_project_edges": len(candidates),
                       "verified_project_edges": 0,
                       "rights_unresolved_articles": sum(
                           r["usage_rights"]["status"] != "accepted" for r in by_url.values())},
            "articles": sorted(by_url.values(), key=lambda r: (
                r["canonical_article_url"], r["source_id"]))}


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--articles", type=Path, required=True)
    parser.add_argument("--sources", type=Path, required=True)
    parser.add_argument("--projects", type=Path, help="optional exact REPD project JSON list")
    parser.add_argument("--output", type=Path, help="new JSON path; never overwrite")
    args = parser.parse_args(argv)

    def read(path):
        return json.loads(path.read_text(encoding="utf-8"))

    result = build_intelligence(read(args.articles), read(args.sources),
                                read(args.projects) if args.projects else ())
    encoded = json.dumps(result, ensure_ascii=False, sort_keys=True, indent=2) + "\n"
    if args.output:
        with args.output.open("x", encoding="utf-8") as handle:
            handle.write(encoded)
    else:
        print(encoded, end="")
    return 0


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