GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / neural-link-between-agents / FIXES/NL-017/evidence

Priority BBC RSS and 9 more files

A Python command-line tool in Neural Link Between Agents that fetches solar and the Renewable Energy Planning Database (REPD) register, using SHA-256.

651 lines of Python and JavaScript and Shell from neural-link-between-agents, in 10 files. Topic: AI agents and coordination. Section 1641 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. G1 Truncation storage · neural-link-between-agents / FIXES/NL-017/evidence/g1_truncation.py lines 1–84
  2. Rehearse automation · neural-link-between-agents / FIXES/NL-017/evidence/rehearse.sh lines 1–49
  3. Triggers storage · neural-link-between-agents / FIXES/NL-017/evidence/triggers.py lines 1–56
  4. Make Manifest storage · neural-link-between-agents / FIXES/NL-017/served-bytes/make_manifest.py lines 1–24
  5. Served Bytes Check automation · neural-link-between-agents / FIXES/NL-017/served-bytes/served_bytes_check.sh lines 1–37
  6. Priority BBC RSS storage · neural-link-between-agents / FIXES/NL-019/N2/priority/priority_bbc_rss.py lines 1–197
  7. Priority Test BBC RSS test · neural-link-between-agents / FIXES/NL-019/N2/priority/priority_test_bbc_rss.py lines 1–90
  8. Measure Added319 storage · neural-link-between-agents / FIXES/NL-019/N2/scripts/measure-added319.mjs lines 1–18
  9. Measure Binding storage · neural-link-between-agents / FIXES/NL-019/N2/scripts/measure-binding.mjs lines 1–77
  10. Measure DC storage · neural-link-between-agents / FIXES/NL-019/N2/scripts/measure-dc.mjs lines 1–19

G1 Truncation

A Python module in the evidence folder of Neural Link Between Agents that uses SHA-256. It is built from the git step (`git`) and the tree step (`tree`).

storageneural-link-between-agents / FIXES/NL-017/evidence/g1_truncation.py · lines 1–84 of 84 · Entry point

What it does
It loads data. Defines git, tree. Uses libraries subprocess, re, sys, hashlib, csv. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
Gate 1: no-truncation proof for PR #57 head vs main baseline and RUNBOOK pins.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
neural-link-between-agents · FIXES/NL-017/evidence · Python module
Uses
subprocess, re, sys, hashlib, csv, collections
Used by
none found
Produces
git, tree
Defines here
git, tree
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-017/evidence/g1_truncation.py:1-84 · blob 6c06e04659298aab3f5b3e65c0802984c1b9b0f0 · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Gate 1: no-truncation proof for PR #57 head vs main baseline and RUNBOOK pins. Read-only."""
import subprocess, re, sys, hashlib, csv
WT="<workspace>/gg-wt"; BASE="73cbdec10bbd3fe2f8313b60b1acc2d22d31b517"; OUTD="<workspace>/teams/5/g1"
def git(*a, text=True): return subprocess.run(["git","-C",WT,*a],capture_output=True,text=text,check=True).stdout
head=git("rev-parse","HEAD").strip()
def tree(rev):
    d={}
    for line in git("ls-tree","-r","-l","--full-tree",rev).splitlines():
        meta,path=line.split("\t",1); mode,typ,blob,size=meta.split()
        d[path]=(blob,int(size) if size!='-' else -1,mode)
    return d
B=tree(BASE); H=tree(head)
# baseline manifest
M={}
for row in open("<workspace>/monitor/globalgrid2050.blobmanifest.tsv"):
    b,s,p=row.rstrip("\n").split("\t",2); M[p]=(b,int(s))
man_vs_base = sum(1 for p in B if p not in M or M[p][0]!=B[p][0]) + sum(1 for p in M if p not in B)
added=[p for p in H if p not in B]; deleted=[p for p in B if p not in H]
modified=[p for p in H if p in B and H[p][0]!=B[p][0]]
modechg=[p for p in H if p in B and H[p][0]==B[p][0] and H[p][2]!=B[p][2]]
with open(f"{OUTD}/changed-files.tsv","w") as f:
    f.write("status\tpath\tbase_blob\tbase_size\thead_blob\thead_size\thead_sha256\n")
    for st,lst in (("A",added),("M",modified),("D",deleted)):
        for p in sorted(lst):
            bb,bs=(B[p][0],B[p][1]) if p in B else ("","")
            hb,hs=(H[p][0],H[p][1]) if p in H else ("","")
            sha=hashlib.sha256(subprocess.run(["git","-C",WT,"cat-file","blob",hb],capture_output=True,check=True).stdout).hexdigest() if hb else ""
            f.write(f"{st}\t{p}\t{bb}\t{bs}\t{hb}\t{hs}\t{sha}\n")
print(f"head={head} base={BASE}")
print(f"baseline manifest entries={len(M)} base tree entries={len(B)} manifest-vs-base mismatches={man_vs_base}")
print(f"added={len(added)} modified={len(modified)} deleted={len(deleted)} mode-only-changes={len(modechg)}")
for p in sorted(modified): print(f"  M {p}: {B[p][1]} -> {H[p][1]} bytes")
big=[(p,H[p][1]) for p in added+modified if H[p][1]>5242880]
print(f"added/modified files over 5 MiB: {len(big)}"); [print("  ",p,s) for p,s in big]
# RUNBOOK pins
rb=open(f"{WT}/docs/repd/RUNBOOK.md").read().splitlines()
start=next(i for i,l in enumerate(rb) if l.startswith("## 2. Paths"))
end=next(i for i,l in enumerate(rb) if l.startswith("## 3."))
res=[]
for l in rb[start:end]:
    if not l.startswith("| `"): continue
    cells=[c.strip() for c in l.strip("|").split("|")]
    paths=re.findall(r"`([^`]+)`",cells[0])
    hexes=re.findall(r"`([0-9a-f]{7,64})(?:\.\.\.[0-9a-f]+)?`",cells[1]+" "+(cells[2] if len(cells)>2 else ""))
    full_sha=[h for h in re.findall(r"`([0-9a-f]{64})`",cells[1])]
    blobs=re.findall(r"`([0-9a-f]{8,40})`",cells[2]) if len(cells)>2 else []
    treeids=re.findall(r"`([0-9a-f]{8,40})(?:\.\.\.)?`",cells[1])
    is_tree = "Tree" not in cells[1] and rb.index(l) > next(i for i,x in enumerate(rb) if x.startswith("### 2.2"))
    # expand shorthand v9.5 etc relative to first path dir
    exp=[]
    for p in paths:
        if "/" not in p and exp and "/" in exp[0]: p=exp[0].rsplit("/",1)[0]+"/"+p
        exp.append(p)
    if exp and exp[0].startswith("uk_renewables_pipeline/v9.4"): exp=[exp[0]]+["uk_renewables_pipeline/"+x for x in paths[1:]]
    if exp and exp[0].startswith("repd_grid_atlasv3"): exp=["repd_grid_atlasv3","repd_grid_atlasv4","repd_grid_atlasv5","repd_grid_atlasv6","repd_grid_atlasv7","repd_grid_atlasv8","202608300453-atlas-v9","restore_points"]
    if exp and exp[0].startswith("GridAtlas"): continue
    for idx,p in enumerate(exp):
        if is_tree:
            want=treeids[idx] if idx<len(treeids) else None
            try: b=git("rev-parse",f"{BASE}:{p}").strip(); h=git("rev-parse",f"{head}:{p}").strip()
            except subprocess.CalledProcessError: res.append(("TREE",p,want,"MISSING","")); continue
            ok = b==h and (want is None or b.startswith(want))
            res.append(("TREE",p,want,"PASS" if ok else "FAIL",f"base={b[:12]} head={h[:12]}"))
        else:
            if p not in B: res.append(("FILE",p,"","NOT-IN-BASE","")); continue
            hb=H.get(p,("DELETED",))[0]; bb=B[p][0]
            data=subprocess.run(["git","-C",WT,"cat-file","blob",hb],capture_output=True).stdout if hb!="DELETED" else b""
            sha=hashlib.sha256(data).hexdigest()
            wsha=full_sha[idx] if idx<len(full_sha) else None
            wbl=blobs[idx] if idx<len(blobs) else None
            ok = hb==bb and (wsha is None or sha==wsha) and (wbl is None or bb.startswith(wbl))
            note=f"blob={hb[:12]} sha256={sha[:16]}"
            if hb!=bb: note+=f" CHANGED from {bb[:12]}"
            if wsha and sha!=wsha: note+=f" PIN-MISMATCH want {wsha[:16]}"
            if wbl and not bb.startswith(wbl): note+=f" BLOB-PIN-MISMATCH want {wbl}"
            res.append(("FILE",p,wsha or wbl or "","PASS" if ok else "FAIL",note))
with open(f"{OUTD}/runbook-pins.tsv","w") as f:
    f.write("kind\tpath\tpinned\tresult\tnote\n")
    for r in res: f.write("\t".join(str(x) for x in r)+"\n")
from collections import Counter
print("RUNBOOK section 2 pins:",dict(Counter(r[3] for r in res)), "checked",len(res))
for r in res:
    if r[3]!="PASS": print("  ",r)

Rehearse

A shell script in the evidence folder of Neural Link Between Agents covering the Renewable Energy Planning Database (REPD) register, using SHA-256.

automationneural-link-between-agents / FIXES/NL-017/evidence/rehearse.sh · lines 1–49 of 49 · Entry point

What it does
Side effects: starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: the REPD register.
Downstream impact
It is itself an entry point (shell script); no other file was found loading it.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
neural-link-between-agents · FIXES/NL-017/evidence · shell script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-017/evidence/rehearse.sh:1-49 · blob d7638d87ce5fc7d7e8e431ac0a6db11daa27bcb7 · GitHub at these lines
State
achieves: name · context: auto · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/bin/bash
# Rollback rehearsal for globalgrid2050 PR #57, in a throw-away local clone. No network, no push.
set -euo pipefail
cd <workspace>/teams/5/g2/clone
export GIT_AUTHOR_NAME=rehearsal GIT_AUTHOR_EMAIL=rehearsal@invalid GIT_COMMITTER_NAME=rehearsal GIT_COMMITTER_EMAIL=rehearsal@invalid
export GIT_AUTHOR_DATE=2026-11-14T00:00:00Z GIT_COMMITTER_DATE=2026-11-14T00:00:00Z
BASE=73cbdec10bbd3fe2f8313b60b1acc2d22d31b517; HEAD_PR=f9ccd703ca749ad8009274a18516625d9d1e5fa3
t0=$(date +%s.%N)
echo "## 0. Simulated merge of PR #57 into main (merge commit, tree = PR head tree; valid while main is still $BASE)"
M=$(git commit-tree "$HEAD_PR^{tree}" -p $BASE -p $HEAD_PR -m "simulated merge of PR #57")
git update-ref refs/heads/main-sim $M
echo "merge M=$M ; diff vs PR head: $(git diff --name-only $HEAD_PR $M | wc -l) paths"
echo "## A. Full rollback: revert the merge (equivalent of 'git revert -m 1 M')"
TA=$(git merge-tree --write-tree --merge-base=$M $M $BASE)
RA=$(git commit-tree $TA -p $M -m "Revert PR #57 (rehearsal)")
echo "revert commit RA=$RA ; paths differing from main $BASE: $(git diff --name-only $BASE $RA | wc -l) (must be 0)"
echo "## B. Revert only Claude's four commits (f9ccd703, 0c78c8c1, aa83e48a, 01ec01e9), newest first, keeping PR #56's commits"
cur=$M
for c in f9ccd703 0c78c8c1 aa83e48a 01ec01e9; do
  t=$(git merge-tree --write-tree --merge-base=$c $cur $c^1) || { echo "CONFLICT reverting $c"; exit 1; }
  cur=$(git commit-tree $t -p $cur -m "Revert $c (rehearsal)")
  echo "  reverted $c -> $cur"
done
echo "tree after B equals 6e58f280 tree: $( [ "$(git rev-parse $cur^{tree})" = "$(git rev-parse 6e58f280^{tree})" ] && echo YES || echo NO)"
echo "B vs main: $(git diff --name-status $BASE $cur | awk '{print $1}' | sort | uniq -c | tr '\n' ' ')"
echo "## C. Revert only the two data commits (0c78c8c1 release folder, aa83e48a datasets); keep automation and workflow fix"
cur=$M
for c in 0c78c8c1 aa83e48a; do
  t=$(git merge-tree --write-tree --merge-base=$c $cur $c^1) || { echo "CONFLICT reverting $c"; exit 1; }
  cur=$(git commit-tree $t -p $cur -m "Revert $c (rehearsal)"); echo "  reverted $c -> $cur"
done
echo "C: paths still present from 202611132345: $(git ls-tree -r --name-only $cur uk_renewables_pipeline/202611132345 | wc -l); *2026q3* data files left: $(git ls-tree -r --name-only $cur | grep -c -E '(^|/)(repd[^/]*-2026q3\.csv|dist/[^/]*2026q3[^/]*\.json)$' || true)"
echo "## D. Base-tree identity after A: every RUNBOOK pin re-checked by blob"
bad=0; while IFS=$'\t' read -r kind path pinned result note; do
  [ "$kind" = FILE ] || continue
  b1=$(git rev-parse "$BASE:$path"); b2=$(git rev-parse "$RA:$path"); [ "$b1" = "$b2" ] || { echo "  DIFF $path"; bad=1; }
done < <(tail -n +2 <workspace>/teams/5/g1/runbook-pins.tsv); echo "pins identical after A: $([ $bad = 0 ] && echo YES || echo NO)"
echo "## E. Restore single files by blob id (no history needed), verify sha256 against RUNBOOK pins"
mkdir -p <workspace>/teams/5/g2/restored
git cat-file blob e221065a7b144a9e4b691cf282e23a68c5661e45 > <workspace>/teams/5/g2/restored/repd_master.json
git cat-file blob 01fe17ae9531d3504490a1418a68350262b06f86 > <workspace>/teams/5/g2/restored/repd.csv
git cat-file blob cea655d7d0a332509ba11567a6655a00074cde8a > <workspace>/teams/5/g2/restored/large-files-allowlist.txt
( cd <workspace>/teams/5/g2/restored && sha256sum -c <<'S'
ca5da437ddb832f7e4e8d84bba1f2f6d40df6285089a43156452fdda7eebe0fe  repd_master.json
fdb6aec50647a4de88f63d33679b93cb2147417eddc43f3f31cbf12792a38aae  repd.csv
91526b11a4620f149dc674ddeb274a4f74b5123d720984b29348709481799e34  large-files-allowlist.txt
S
)
t1=$(date +%s.%N); echo "elapsed: $(echo "$t1 - $t0" | bc) s"

Triggers

A Python module in the evidence folder of Neural Link Between Agents that reads triggered.

storageneural-link-between-agents / FIXES/NL-017/evidence/triggers.py · lines 1–56 of 56 · Entry point

What it does
It loads triggered. Defines git, glob_to_re, match_paths, branch_ok. Uses libraries subprocess, yaml, fnmatch, re, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: JSON file triggered.json.
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
It matches paths (`match_paths`) and is built from the git step (`git`) and the glob to re helper (`glob_to_re`). Gate 3: which workflows a merge of PR #57 to main would trigger (push to main), evaluated with the HEAD versions of the workflow files (GitHub uses the workflow file at the pushed commit).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
neural-link-between-agents · FIXES/NL-017/evidence · Python module
Uses
subprocess, yaml, fnmatch, re, sys, json
Used by
none found
Produces
git, glob_to_re, match_paths, branch_ok
Defines here
git, glob_to_re, match_paths, branch_ok
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-017/evidence/triggers.py:1-56 · blob e0336eb8c97cac6f2117ebca42e964f9a5cdd808 · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Gate 3: which workflows a merge of PR #57 to main would trigger (push to main), evaluated with the HEAD versions
of the workflow files (GitHub uses the workflow file at the pushed commit). Read-only."""
import subprocess, yaml, fnmatch, re, sys, json
WT="<workspace>/gg-wt"; BASE="73cbdec10bbd3fe2f8313b60b1acc2d22d31b517"
def git(*a): return subprocess.run(["git","-C",WT,*a],capture_output=True,text=True,check=True).stdout
head=git("rev-parse","HEAD").strip()
changed=git("diff","--name-only",BASE,head).splitlines()
def glob_to_re(p):
    # GitHub filter pattern: ** any incl /, * any except /, ? one char except /, leading ! handled by caller
    i=0; out=""
    while i<len(p):
        if p.startswith("**",i): out+=".*"; i+=2
        elif p[i]=="*": out+="[^/]*"; i+=1
        elif p[i]=="?": out+="[^/]"; i+=1
        else: out+=re.escape(p[i]); i+=1
    return re.compile("^"+out+"$")
def match_paths(pats, files):
    hits=set()
    for f in files:
        ok=False
        for p in pats:
            neg=p.startswith("!"); pp=p[1:] if neg else p
            if glob_to_re(pp).match(f): ok = not neg
        if ok: hits.add(f)
    return hits
def branch_ok(spec):
    br=spec.get("branches"); ign=spec.get("branches-ignore")
    if br is not None:
        ok=False
        for b in br:
            neg=b.startswith("!"); bb=b[1:] if neg else b
            if glob_to_re(bb).match("main"): ok=not neg
        return ok
    if ign is not None: return not any(glob_to_re(b).match("main") for b in ign)
    if spec.get("tags") is not None and br is None: return False
    return True
rows=[]
for wf in sorted(git("ls-tree","--name-only",f"{head}:.github/workflows").split()):
    if not wf.endswith((".yml",".yaml")): continue
    txt=git("show",f"{head}:.github/workflows/{wf}")
    try: y=yaml.safe_load(txt)
    except Exception as e: rows.append((wf,"PARSE-ERROR",str(e)[:80])); continue
    on=y.get(True, y.get("on"))
    if isinstance(on,str): on={on:None}
    if isinstance(on,list): on={k:None for k in on}
    if not isinstance(on,dict) or "push" not in on: continue
    spec=on["push"] or {}
    if not branch_ok(spec): continue
    if "paths" in spec: hits=match_paths(spec["paths"],changed)
    elif "paths-ignore" in spec: hits=set(changed)-match_paths(spec["paths-ignore"],changed)
    else: hits=set(changed)
    if hits: rows.append((wf,len(hits),sorted(hits)[:6]))
json.dump(rows,open("<workspace>/teams/5/g3/triggered.json","w"),indent=1)
print(f"head={head} changed={len(changed)} workflows triggered on push to main: {len(rows)}")
for r in rows: print(" ",r[0],r[1],r[2][:3])

Make Manifest

A Python module in the served bytes folder of Neural Link Between Agents that builds the served-byte manifest for main (PR #57 merge), using SHA-256.

storageneural-link-between-agents / FIXES/NL-017/served-bytes/make_manifest.py · lines 1–24 of 24 · Entry point

What it does
It loads data. Defines git. Uses libraries subprocess, hashlib, csv, sys, collections. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
Its name says it makes manifest. Defines `git`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
neural-link-between-agents · FIXES/NL-017/served-bytes · Python module
Uses
subprocess, hashlib, csv, sys, collections
Used by
none found
Produces
git
Defines here
git
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-017/served-bytes/make_manifest.py:1-24 · blob 2f36d864ba2d29ad83a3bff5efd595cf500f54fa · GitHub at these lines
State
achieves: name · context: auto · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Build the served-byte manifest for main 07b6d517 (PR #57 merge). Columns: expect, path, sha256, bytes.
expect = NEW (added by PR #57), MOD (modified by PR #57), PIN (unchanged, hash-pinned by RUNBOOK 2.1),
         JEKYLL (has front matter: Jekyll may transform it, check status only), SKIP (Jekyll excludes _/. paths)."""
import subprocess, hashlib, csv, sys
WT="<workspace>/gg-wt"; BASE="73cbdec10bbd3fe2f8313b60b1acc2d22d31b517"; MERGE_TREE_REV="f9ccd703"
def git(*a): return subprocess.run(["git","-C",WT,*a],capture_output=True,check=True).stdout
rows=[]
for line in git("diff","--name-status","--no-renames",BASE,MERGE_TREE_REV).decode().splitlines():
    st,p=line.split("\t",1); rows.append(("NEW" if st=="A" else "MOD",p))
for r in csv.DictReader(open("<workspace>/teams/5/g1/runbook-pins.tsv"),delimiter="\t"):
    if r["kind"]=="FILE" and r["path"]!=".github/large-files-allowlist.txt": rows.append(("PIN",r["path"]))
rows.append(("PIN","uk_renewables_pipeline/202609082224/index.html"))
out=[]
for exp,p in rows:
    data=git("cat-file","blob",f"{MERGE_TREE_REV}:{p}")
    parts=p.split("/")
    if any(x.startswith(("_",".")) for x in parts): exp2="SKIP"
    elif data[:4] in (b"---\n",b"---\r") or p.endswith(".md"): exp2="JEKYLL"
    else: exp2=exp
    out.append((exp2 if exp2 in ("SKIP","JEKYLL") else exp,p,hashlib.sha256(data).hexdigest(),len(data),exp))
w=csv.writer(open("<workspace>/teams/5/g8/served-manifest.tsv","w"),delimiter="\t",lineterminator="\n")
w.writerow(["expect","path","sha256","bytes","origin"]); w.writerows(out)
from collections import Counter; print(Counter(o[0] for o in out), len(out))

Served Bytes Check

A shell script in Neural Link Between Agents that uses SHA-256.

automationneural-link-between-agents / FIXES/NL-017/served-bytes/served_bytes_check.sh · lines 1–37 of 37 · Entry point

What it does
Side effects: starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
It is itself an entry point (shell script); no other file was found loading it.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
neural-link-between-agents · FIXES/NL-017/served-bytes · shell script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-017/served-bytes/served_bytes_check.sh:1-37 · blob c478e8e47678493c9f67ac51f6e9e381862a8005 · GitHub at these lines
State
achieves: name · context: auto · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env bash
# Served-byte check for globalgrid2050 main after the PR #57 merge (merge commit 07b6d51702a1, tree 683f5b162c34).
# Prepared by Team 5 (NL-017). Read-only: only HTTP GETs. Needs bash, curl, sha256sum (or shasum -a 256), awk.
# Usage:  ./served_bytes_check.sh served-manifest.tsv [after-merge|after-rollback] [base_url]
#   after-merge (default): NEW/MOD/PIN rows must return 200 with the exact sha256; JEKYLL rows 200 only; SKIP rows are reported.
#   after-rollback: NEW rows must return 404; PIN rows must still match.  (MOD rows are scripts; after rollback they return to main's
#   old bytes, which this manifest does not list, so they are reported only.)
# Output: one TSV line per path (result, http status, bytes, sha256, path) and a summary; exit 0 only if every required row passes.
set -uo pipefail
MAN=${1:?manifest}; MODE=${2:-after-merge}; BASE=${3:-https://globalgrid2050.com}
if command -v sha256sum >/dev/null; then H="sha256sum"; else H="shasum -a 256"; fi
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
pass=0; fail=0; info=0; bust="cb=$(date -u +%s)"
printf 'result\tstatus\tbytes\tsha256\tpath\n'
while IFS=$'\t' read -r expect path want bytes origin; do
  [ "$expect" = expect ] && continue
  url="$BASE/$path"; [[ "$MODE" = after-merge && "$path" == */index.html ]] && url="$BASE/${path%index.html}"
  # Jekyll (jekyll-optional-front-matter, as the deploy log of run 43535023721 shows) renders *.md to *.html and does not publish
  # the raw .md; a README.md becomes the folder index only when the folder has no index.html. So check the rendered URL, status only.
  if [ "$expect" = JEKYLL ] && [[ "$path" == *.md ]]; then url="$BASE/${path%.md}.html"; fi
  code=$(curl -sS -L --max-time 60 -o "$tmp/f" -w '%{http_code}' "$url?$bust" 2>/dev/null || echo 000)
  got=$($H "$tmp/f" 2>/dev/null | cut -c1-64); size=$(wc -c < "$tmp/f" 2>/dev/null | tr -d ' ')
  res=INFO
  case "$MODE:$expect" in
    after-merge:NEW|after-merge:MOD|after-merge:PIN|after-rollback:PIN)
      if [ "$code" = 200 ] && [ "$got" = "$want" ]; then res=PASS; else res=FAIL; fi ;;
    after-merge:JEKYLL) [ "$code" = 200 ] && res=PASS || res=FAIL ;;
    after-rollback:NEW) [ "$code" = 404 ] && res=PASS || res=FAIL ;;
  esac
  case $res in PASS) pass=$((pass+1));; FAIL) fail=$((fail+1));; *) info=$((info+1));; esac
  printf '%s\t%s\t%s\t%s\t%s\n' "$res" "$code" "$size" "$got" "$path"
  [ "$res" = FAIL ] && [ "$expect" != JEKYLL ] && [ "$code" = 200 ] && printf '#   want %s (%s bytes)\n' "$want" "$bytes"
done < "$MAN"
echo "# mode=$MODE base=$BASE pass=$pass fail=$fail info=$info  (UTC $(date -u +%FT%TZ))"
echo "# A FAIL with status 200 and a different hash on a PIN row means a pre-existing file changed: stop and roll back."
echo "# Pages CDN may serve old bytes for some minutes after a deploy: re-run after 10 minutes before acting on NEW-row 404s."
[ "$fail" -eq 0 ]

Priority BBC RSS

A Python command-line tool in Neural Link Between Agents that fetches solar and the Renewable Energy Planning Database (REPD) register, using SHA-256.

storageneural-link-between-agents / FIXES/NL-019/N2/priority/priority_bbc_rss.py · lines 1–197 of 197 · Entry point · pattern canonical_article (shared by 2 files)

What it does
It fetches solar and the REPD register. Defines 8 functions or classes, including canonical_article, parse_feed, merge_items, recent, NoRedirect. Uses libraries argparse, datetime, email.utils, hashlib, json. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: solar, the REPD register.
Inputs & outputs
In: JSON file bbc-rss.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It parses feed (`parse_feed`) and is built from the canonical article helper (`canonical_article`) and the merge items helper (`merge_items`). Bounded BBC RSS discovery. Never fetch article pages or infer REPD bindings. Its code works with 1 MW. It accepts `--output`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
neural-link-between-agents · FIXES/NL-019/N2/priority · Python CLI
Uses
argparse, datetime, email.utils, hashlib, json, pathlib, re, urllib.parse
Used by
none found
Produces
canonical_article, parse_feed, merge_items, NoRedirect, collect, main
Defines here
canonical_article, parse_feed, merge_items, recent, NoRedirect, redirect_request, collect, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-019/N2/priority/priority_bbc_rss.py:1-197 · blob 04bf27d800e4b2b46e16984915c8d01ed69e8f3d · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Bounded BBC RSS discovery. Never fetch article pages or infer REPD bindings."""
import argparse
import datetime as dt
import email.utils
import hashlib
import json
import pathlib
import re
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET

SOURCES = {
    1: ('BBC News', None),
    2: ('Solar Power Portal', 'https://www.solarpowerportal.co.uk/feed/'),
    3: ('pv magazine', 'https://www.pv-magazine.com/feed/'),
}
SOURCE_ID_PREFIX = {1: 'bbc', 2: 'spp', 3: 'pvmag'}
UK_SIGNAL = re.compile(r'\b(UK|United Kingdom|Britain|British|England|Scotland|Wales|Northern Ireland|London|GB)\b', re.I)

SECTIONS = ('science_and_environment', 'business', 'england', 'scotland', 'wales',
            'northern_ireland', 'uk',
            # BBC Local: deliberately broad. A failed/retired feed is recorded in health
            # rather than silently shrinking geographic coverage.
            'england/berkshire', 'england/beds_bucks_and_herts', 'england/birmingham_and_black_country',
            'england/bristol', 'england/cambridgeshire', 'england/cornwall', 'england/coventry_and_warwickshire',
            'england/cumbria', 'england/derbyshire', 'england/devon', 'england/dorset', 'england/essex',
            'england/gloucestershire', 'england/hampshire', 'england/hereford_and_worcester', 'england/humberside',
            'england/kent', 'england/lancashire', 'england/leeds_and_west_yorkshire', 'england/leicester',
            'england/lincolnshire', 'england/london', 'england/manchester', 'england/norfolk',
            'england/northamptonshire', 'england/nottingham', 'england/oxford', 'england/shropshire',
            'england/somerset', 'england/south_yorkshire', 'england/stoke_and_staffordshire',
            'england/suffolk', 'england/surrey', 'england/sussex', 'england/tees',
            'england/tyne', 'england/wear', 'england/wiltshire', 'england/north_yorkshire')
MAX_BYTES = 1_048_576
MAX_ITEMS = 500
SOLAR_TOPIC = re.compile(r'\b(solar|photovoltaic|photovoltaics|PV|solar farm|solar park|solar panels?)\b', re.I)
CAPACITY = re.compile(r'(?<![\w.])(\d+(?:\.\d+)?)\s*(GW|MW|kW)(?:p|ac|dc)?\b', re.I)
MIN_SOLAR_MW = 1.0


def canonical_article(value, source_priority=1):
    u = urllib.parse.urlsplit(value)
    allowed = {
        1: ('www.bbc.co.uk', 'www.bbc.com'),
        2: ('www.solarpowerportal.co.uk', 'solarpowerportal.co.uk'),
        3: ('www.pv-magazine.com', 'pv-magazine.com'),
    }[source_priority]
    if u.scheme != 'https' or u.hostname not in allowed or u.username or u.password or u.port:
        raise ValueError('article URL is outside the selected priority source')
    if source_priority == 1:
        if not re.fullmatch(r'/news/articles/[a-z0-9]+', u.path):
            raise ValueError('not a BBC article path')
        return 'https://www.bbc.co.uk' + u.path
    return urllib.parse.urlunsplit(('https', allowed[0], u.path.rstrip('/') + '/', '', ''))


def parse_feed(body, feed_url, observed_at, source_priority=1):
    if len(body) > MAX_BYTES or b'<!DOCTYPE' in body.upper() or b'<!ENTITY' in body.upper():
        raise ValueError('RSS exceeds bound or contains a DTD/entity declaration')
    root = ET.fromstring(body)
    if root.tag != 'rss' or root.find('channel') is None:
        raise ValueError('not an RSS channel')
    result = []
    for item in root.findall('./channel/item')[:MAX_ITEMS]:
        try:
            url = canonical_article(item.findtext('link', '').strip(), source_priority)
        except ValueError:
            continue
        headline = ' '.join(item.findtext('title', '').split())[:300]
        # Description is used only to find relevant links; no article body is retained.
        description = item.findtext('description', '')[:2000]
        text = headline + ' ' + description
        if not headline or not SOLAR_TOPIC.search(text):
            continue
        # BBC local/national feeds are UK by construction. Trade publications
        # are global, so require a UK signal before they enter this lane.
        if source_priority in (2, 3) and not UK_SIGNAL.search(text):
            continue
        capacities_mw = []
        for value, unit in CAPACITY.findall(text):
            scale = {'kw': 0.001, 'mw': 1.0, 'gw': 1000.0}[unit.lower()]
            capacities_mw.append(float(value) * scale)
        # Keep unknown-capacity solar stories: RSS summaries often omit MW even when
        # the underlying project is utility-scale. Explicitly sub-1 MW-only items are
        # outside this lane. Later project matching can resolve unknown capacity.
        if capacities_mw and max(capacities_mw) <= MIN_SOLAR_MW:
            continue
        published = None
        try:
            parsed = email.utils.parsedate_to_datetime(item.findtext('pubDate', ''))
            if parsed.tzinfo is not None:
                published = parsed.astimezone(dt.timezone.utc).isoformat()
        except (ValueError, TypeError, OverflowError):
            pass
        slug = url.rstrip('/').rsplit('/', 1)[1]
        result.append({'id': SOURCE_ID_PREFIX[source_priority] + ':' + slug, 'url': url,
                       'headline': headline, 'publisher': SOURCES[source_priority][0], 'source_priority': source_priority,
                       'topic': 'solar', 'capacity_mw_max': max(capacities_mw) if capacities_mw else None,
                       'capacity_gate': 'ABOVE_1MW' if capacities_mw and max(capacities_mw) > MIN_SOLAR_MW else 'UNKNOWN_RETAIN_FOR_MATCH',
                       'source_published_at': published, 'first_observed_at': observed_at,
                       'last_seen_at': observed_at, 'feed_urls': [feed_url],
                       'repd_ref': None, 'binding_status': 'UNMATCHED_REQUIRES_REVIEW',
                       'eligible_for_project_signal': False})
    return result


def merge_items(previous, incoming, now):
    cutoff = now - dt.timedelta(days=30)
    kept = {}
    for item in previous + incoming:
        identity = item['id']
        if identity in kept:
            old = kept[identity]
            item = dict(item, first_observed_at=old['first_observed_at'],
                        feed_urls=sorted(set(old['feed_urls'] + item['feed_urls'])))
        kept[identity] = item
    def recent(item):
        # Missing dates stay missing; observation is used only for retention.
        try:
            value = dt.datetime.fromisoformat(item['source_published_at'] or item['last_seen_at'])
            return value.tzinfo is not None and value >= cutoff
        except (ValueError, TypeError):
            return False
    return sorted(
        (x for x in kept.values() if recent(x)),
        key=lambda x: (
            -(dt.datetime.fromisoformat(x['source_published_at']).timestamp()
              if x.get('source_published_at') else 0),
            int(x.get('source_priority', 99)),
            x['id'],
        ),
    )[:MAX_ITEMS]


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        raise ValueError('feed redirect rejected')


def collect(previous, now, fetch=None):
    observed = now.isoformat()
    incoming, health = [], []
    opener = urllib.request.build_opener(NoRedirect)
    feed_specs = [(1, f'https://feeds.bbci.co.uk/news/{section}/rss.xml') for section in SECTIONS]
    feed_specs += [(priority, spec[1]) for priority, spec in SOURCES.items() if priority > 1]
    for source_priority, url in feed_specs:
        try:
            if fetch:
                body = fetch(url)
            else:
                req = urllib.request.Request(url, headers={'User-Agent':'PipelineNews-RSS/1.0', 'Accept':'application/rss+xml, application/xml'})
                with opener.open(req, timeout=10) as response:
                    body = response.read(MAX_BYTES + 1)
            items = parse_feed(body, url, observed, source_priority)
            incoming.extend(items)
            health.append({'url':url, 'status':'ok', 'items':len(items), 'sha256':hashlib.sha256(body).hexdigest()})
        except Exception as error:
            health.append({'url':url, 'status':'failed', 'error':type(error).__name__ + ': ' + str(error)[:180]})
    ok = sum(x['status'] == 'ok' for x in health)
    return {'schema':'pipelinenews.priority-solar-news.v1', 'checked_at':observed,
            'last_success_at':observed if ok else previous.get('last_success_at'),
            'status':'ok' if ok == len(feed_specs) else 'partial' if ok else 'failed',
            'items':merge_items(previous.get('items', []), incoming, now), 'feeds':health,
            'limits':{'feeds':len(feed_specs), 'bytes_per_feed':MAX_BYTES, 'retained_items':MAX_ITEMS, 'retention_days':30},
            'source_priority': {'1':'BBC News','2':'Solar Power Portal','3':'pv magazine'},
            'scope':'Priority UK solar discovery: BBC national/local first, Solar Power Portal second, pv magazine third. Explicit <=1 MW-only items excluded; unknown MW retained for project matching/review. No article-page requests; no inferred REPD match.'}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--output', default='discovery/products/bbc-rss.json')
    args = parser.parse_args()
    path = pathlib.Path(args.output)
    previous = json.loads(path.read_text(encoding='utf-8')) if path.exists() else {}
    result = collect(previous, dt.datetime.now(dt.timezone.utc))
    result['submitted_articles'] = []
    for receipt in sorted(pathlib.Path('discovery/inbox').glob('*.json')):
        intake = json.loads(receipt.read_text(encoding='utf-8'))
        if intake.get('schema') != 'pipelinenews.manual-url-intake.v1':
            continue
        url = canonical_article(intake['submitted_url'])
        found = next((item for item in result['items'] if item['url'] == url), None)
        result['submitted_articles'].append({'url':url, 'intake_id':intake['intake_id'],
            'status':'FOUND_IN_RSS' if found else 'NOT_SEEN_IN_FETCHED_RSS',
            'headline':found['headline'] if found else None,
            'note':'Not seen does not mean absent from BBC or REPD; RSS is a rolling feed.'})
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_suffix('.tmp')
    temp.write_text(json.dumps(result, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
    temp.replace(path)
    print(json.dumps({'status':result['status'], 'items':len(result['items']), 'feeds':len(result['feeds']), 'output':str(path)}))
    return 1 if result['status'] == 'failed' else 0


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

Priority Test BBC RSS

A Python command-line tool in Neural Link Between Agents. It is built from the rss tests class (`RssTests`), the fail step (`fail`) and the feed step (`feed`).

testneural-link-between-agents / FIXES/NL-019/N2/priority/priority_test_bbc_rss.py · lines 1–90 of 90 · Entry point · pattern test_feed_failure_retains_last_good_without_freshness_claim (shared by 2 files)

What it does
It tests its inputs. Defines 12 functions or classes, including RssTests, test_feed_item_stays_unmatched, test_unknown_capacity_solar_is_retained_for_later_match, test_explicit_sub_one_mw_solar_is_excluded, test_retry_and_cross_feed_deduplication. Uses libraries datetime, unittest, bbc_rss.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Defines `RssTests`, `test_feed_item_stays_unmatched`, `test_unknown_capacity_solar_is_retained_for_later_match` and 9 more. Its code works with 25 MW, 15 MW and 20 MW.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
neural-link-between-agents · FIXES/NL-019/N2/priority · Python CLI
Uses
datetime, unittest, bbc_rss
Used by
none found
Produces
RssTests
Defines here
RssTests, test_feed_item_stays_unmatched, test_unknown_capacity_solar_is_retained_for_later_match, test_explicit_sub_one_mw_solar_is_excluded, test_retry_and_cross_feed_deduplication, test_missing_date_never_becomes_collection_date, test_unsafe_urls_and_xml_are_rejected, test_feed_failure_retains_last_good_without_freshness_claim, fail, test_trade_sources_require_uk_and_keep_priority, test_all_three_source_feeds_can_report_ok, feed
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-019/N2/priority/priority_test_bbc_rss.py:1-90 · blob 5865f7ad9d8636ea2fe3b14457bfd3770162cdb9 · GitHub at these lines
State
achieves: name · context: auto · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
import datetime as dt
import unittest
from bbc_rss import canonical_article, parse_feed, merge_items, collect, SECTIONS, SOURCES

NOW = dt.datetime(2026, 9, 6, tzinfo=dt.timezone.utc)
RSS = b'''<rss><channel><item><title>New 25 MW solar farm proposed</title><link>https://www.bbc.co.uk/news/articles/c4gmkezn4nlo?at_campaign=rss</link><pubDate>Sat, 05 Sep 2026 10:00:00 GMT</pubDate></item></channel></rss>'''


class RssTests(unittest.TestCase):
    def test_feed_item_stays_unmatched(self):
        item = parse_feed(RSS, 'feed', NOW.isoformat())[0]
        self.assertEqual(item['url'], 'https://www.bbc.co.uk/news/articles/c4gmkezn4nlo')
        self.assertIsNone(item['repd_ref'])
        self.assertFalse(item['eligible_for_project_signal'])
        self.assertEqual(item['source_published_at'], '2026-09-05T10:00:00+00:00')
        self.assertEqual(item['source_priority'], 1)
        self.assertTrue(item['id'].startswith('bbc:'))
        self.assertEqual(item['capacity_mw_max'], 25.0)
        self.assertEqual(item['capacity_gate'], 'ABOVE_1MW')

    def test_unknown_capacity_solar_is_retained_for_later_match(self):
        body = RSS.replace(b'25 MW ', b'')
        item = parse_feed(body, 'feed', NOW.isoformat())[0]
        self.assertIsNone(item['capacity_mw_max'])
        self.assertEqual(item['capacity_gate'], 'UNKNOWN_RETAIN_FOR_MATCH')

    def test_explicit_sub_one_mw_solar_is_excluded(self):
        body = RSS.replace(b'25 MW', b'500 kW')
        self.assertEqual(parse_feed(body, 'feed', NOW.isoformat()), [])

    def test_retry_and_cross_feed_deduplication(self):
        a = parse_feed(RSS, 'feed-a', NOW.isoformat())
        b = parse_feed(RSS, 'feed-b', NOW.isoformat())
        result = merge_items(a, b+b, NOW)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0]['feed_urls'], ['feed-a','feed-b'])

    def test_missing_date_never_becomes_collection_date(self):
        item = parse_feed(RSS.replace(b'<pubDate>Sat, 05 Sep 2026 10:00:00 GMT</pubDate>', b''), 'feed', NOW.isoformat())[0]
        self.assertIsNone(item['source_published_at'])

    def test_unsafe_urls_and_xml_are_rejected(self):
        for value in ['http://www.bbc.co.uk/news/articles/a', 'https://evil.test/news/articles/a', 'https://www.bbc.co.uk@evil.test/news/articles/a']:
            with self.assertRaises(ValueError): canonical_article(value)
        for body in [b'<!DOCTYPE rss><rss><channel/></rss>', b'<html/>', b'x'*1048577]:
            with self.assertRaises(ValueError): parse_feed(body, 'feed', NOW.isoformat())

    def test_feed_failure_retains_last_good_without_freshness_claim(self):
        previous = {'items':parse_feed(RSS,'feed',NOW.isoformat()),'last_success_at':'2026-09-05T10:00:00+00:00'}
        calls=[]
        def fail(url):
            calls.append(url)
            raise OSError('offline')
        result=collect(previous,NOW,fail)
        self.assertEqual(result['status'],'failed')
        self.assertEqual(result['last_success_at'],previous['last_success_at'])
        self.assertEqual(len(result['items']),1)
        self.assertEqual(len(calls), len(SECTIONS) + 2)
        self.assertTrue(all(url.startswith('https://feeds.bbci.co.uk/') for url in calls[:-2]))
        self.assertEqual(calls[-2:], [SOURCES[2][1], SOURCES[3][1]])


    def test_trade_sources_require_uk_and_keep_priority(self):
        spp = b'''<rss><channel><item><title>UK 15MW solar farm approved</title><link>https://www.solarpowerportal.co.uk/solar-projects/example</link><pubDate>Sat, 05 Sep 2026 10:00:00 GMT</pubDate></item></channel></rss>'''
        pvm = b'''<rss><channel><item><title>British 20 MW solar project advances</title><link>https://www.pv-magazine.com/2026/09/05/example/</link><pubDate>Sat, 05 Sep 2026 10:00:00 GMT</pubDate></item></channel></rss>'''
        self.assertEqual(parse_feed(spp, SOURCES[2][1], NOW.isoformat(), 2)[0]['source_priority'], 2)
        self.assertTrue(parse_feed(spp, SOURCES[2][1], NOW.isoformat(), 2)[0]['id'].startswith('spp:'))
        self.assertEqual(parse_feed(pvm, SOURCES[3][1], NOW.isoformat(), 3)[0]['source_priority'], 3)
        self.assertTrue(parse_feed(pvm, SOURCES[3][1], NOW.isoformat(), 3)[0]['id'].startswith('pvmag:'))
        non_uk = pvm.replace(b'British ', b'German ')
        self.assertEqual(parse_feed(non_uk, SOURCES[3][1], NOW.isoformat(), 3), [])


    def test_all_three_source_feeds_can_report_ok(self):
        def feed(url):
            if 'solarpowerportal' in url:
                return b'''<rss><channel><item><title>UK 15 MW solar farm approved</title><link>https://www.solarpowerportal.co.uk/solar-projects/example</link><pubDate>Sat, 05 Sep 2026 11:00:00 GMT</pubDate></item></channel></rss>'''
            if 'pv-magazine' in url:
                return b'''<rss><channel><item><title>British 20 MW solar project advances</title><link>https://www.pv-magazine.com/2026/09/05/example/</link><pubDate>Sat, 05 Sep 2026 09:00:00 GMT</pubDate></item></channel></rss>'''
            return RSS
        result = collect({}, NOW, feed)
        self.assertEqual(result['status'], 'ok')
        self.assertEqual(result['source_priority']['1'], 'BBC News')
        priorities = [item['source_priority'] for item in result['items']]
        self.assertIn(1, priorities)
        self.assertIn(2, priorities)
        self.assertIn(3, priorities)


if __name__ == '__main__': unittest.main()

Measure Added319

A JavaScript module in the scripts folder of Neural Link Between Agents that reads solar and wind, using SHA-256.

storageneural-link-between-agents / FIXES/NL-019/N2/scripts/measure-added319.mjs · lines 1–18 of 18 · Not reached from any entry point (candidate for review)

What it does
It loads solar and wind. Uses libraries node:fs, <workspace>/pipelinenews/cartridges/provisional-identity.mjs. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: solar, wind.
Inputs & outputs
In: command-line arguments.
What it achieves
Bind the article corpus and the provisional register against only the 319 Renewable Energy Planning Database (REPD) refs added Jul->Oct 2026.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-019/N2/scripts · JavaScript module
Uses
node:fs, ./b/discovery/project-binder.mjs, <workspace>/pipelinenews/cartridges/provisional-identity.mjs
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-019/N2/scripts/measure-added319.mjs:1-18 · blob 5846239283e904ebe465bed4efb7c47271611f89 · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// Bind the article corpus and the provisional register against only the 319 REPD refs added Jul->Oct 2026.
import {readFileSync, writeFileSync} from 'node:fs';
import {buildGazetteer, bindAll} from './b/discovery/project-binder.mjs';
import {reconcileProvisional} from '<workspace>/pipelinenews/cartridges/provisional-identity.mjs';
const [diffPath, csvCounty, resultsPath, registerPath, out] = process.argv.slice(2);
const added = JSON.parse(readFileSync(diffPath, 'utf8')).records.added.records_by_mw;
const county = JSON.parse(readFileSync(csvCounty, 'utf8'));
const tech = {'Solar Photovoltaics': 'solar', 'Battery': 'bess', 'Wind Onshore': 'wind_onshore', 'Wind Offshore': 'wind_offshore'};
const projects = added.map(r => ({repd_ref: String(r.ref), name: r.site, operator: r.operator, county: county[r.ref] ?? null, technology: tech[r.technology] ?? r.technology, status: r.status, capacity_mw: r.mw}));
const g = buildGazetteer(projects);
const rows = JSON.parse(readFileSync(resultsPath, 'utf8'));
const r = bindAll(rows.map(x => ({url: x.url, headline: x.headline})), g);
const register = JSON.parse(readFileSync(registerPath, 'utf8'));
const recon = reconcileProvisional(register.projects, projects, {path: diffPath, sha256: 'f'.repeat(64)});
const res = {added_refs: projects.length, gazetteer_aliases: g.alias_count, corpus_items: rows.length, counts: r.counts,
  hits: r.results.filter(x => x.outcome !== 'NO_MATCH').map((x, i) => ({item: x.item_id, outcome: x.outcome, reason: x.reason, candidates: x.candidates.map(c => c.repd_ref + ':' + c.name)})),
  provisional: recon.map(p => ({name: p.name, repd_ref: p.repd_ref, status: p.reconciliation.status, candidate_count: p.reconciliation.candidate_count}))};
writeFileSync(out, JSON.stringify(res, null, 1) + '\n'); console.log(JSON.stringify(res, null, 1));

Measure Binding

A JavaScript module in the scripts folder of Neural Link Between Agents that reads sector intelligence, bbc rss, register delta q2 q3 and binding results, using SHA-256.

storageneural-link-between-agents / FIXES/NL-019/N2/scripts/measure-binding.mjs · lines 1–77 of 77 · Not reached from any entry point (candidate for review)

What it does
It loads sector intelligence, bbc rss, register delta q2 q3 and binding results. Defines read, add, F, S, pick. Uses libraries node:fs, node:path. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file 202608271524-fd2212a8c76d-v8-fast-news.json; JSON file 202608272130-sector-intelligence.json; JSON file bbc-rss.json; command-line arguments. Out: JSON file register-delta-q2-q3.json; JSON file binding-results.json; JSON file binding-summary.json.
What it achieves
It is built from the read step (`read`), the add step (`add`) and the pick step (`pick`). Offline measurement: bind the existing Pipeline News article corpus to the Q2 and Q3 registers.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-019/N2/scripts · JavaScript module
Uses
node:fs, node:path, ./b/tools/intelligence/register-source.mjs, ./b/tools/intelligence/register-delta.mjs, ./b/discovery/project-binder.mjs
Used by
none found
Produces
read, add, F, S, pick
Defines here
read, add, F, S, pick
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-019/N2/scripts/measure-binding.mjs:1-77 · blob fde3d0539b05873896b1eb31ca15a9c7a4f8f1e4 · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// Offline measurement: bind the existing Pipeline News article corpus to the Q2 and Q3 registers.
// usage: node measure-binding.mjs <pipelinenews clone> <october repo copy> <out dir>
import {readFileSync, writeFileSync, mkdirSync} from 'node:fs';
import path from 'node:path';
import {resolveRegister, decodeProjects} from './b/tools/intelligence/register-source.mjs';
import {computeDelta, operatorAliases} from './b/tools/intelligence/register-delta.mjs';
import {buildGazetteer, bindAll} from './b/discovery/project-binder.mjs';

const [pn, oct, out] = process.argv.slice(2);
mkdirSync(out, {recursive: true});
const read = file => JSON.parse(readFileSync(file, 'utf8'));

// Article corpus, deduplicated by URL.
const items = new Map();
const add = (item) => { const key = item.url; if (!key) return; if (!items.has(key)) items.set(key, item); else items.get(key).sources.push(...item.sources); };
const news = read(path.join(pn, 'releases/202609060232-pipelinenews/data/202608271524-fd2212a8c76d-v8-fast-news.json'));
const F = name => news.fields.indexOf(name);
for (const row of news.rows) add({id: row[F('gg_article_id')], url: row[F('url')], headline: row[F('headline')], evidence_snippet: row[F('evidence_snippet')],
  published: row[F('published')], source: row[F('source')], curated: {role: row[F('role')], repd_ref: row[F('repd_ref')] || null, project: row[F('project')] || null}, sources: ['v8-fast-news']});
const sector = read(path.join(pn, 'releases/202609060232-pipelinenews/data/202608272130-sector-intelligence.json'));
const S = name => sector.fields.indexOf(name);
for (const row of sector.rows) add({id: row[S('intelligence_item_id')], url: row[S('canonical_url')], headline: row[S('title')], summary: row[S('summary')],
  published: row[S('source_published_at')], topic: row[S('topic_code')], curated: {role: 'SECTOR_CONTEXT', repd_ref: null}, sources: ['sector-intelligence']});
const rss = read(path.join(pn, 'discovery/products/bbc-rss.json'));
for (const row of rss.items) add({id: row.id, url: row.url, headline: row.headline, published: row.source_published_at, curated: {role: row.binding_status, repd_ref: null}, sources: ['bbc-rss']});
const corpus = [...items.values()];

const q2 = resolveRegister(pn, {release: '202609060232-pipelinenews'});
const q3 = resolveRegister(oct, {release: '202611132345-pipelinenews'});
const q2p = decodeProjects(q2.payload), q3p = decodeProjects(q3.payload);
const delta = computeDelta(q2p, q3p, {previous: q2, next: q3});
writeFileSync(path.join(out, 'register-delta-q2-q3.json'), JSON.stringify(delta, null, 2) + '\n');
const siteAliases = new Map(delta.site_renamed.map(row => [row.repd_ref, [row.from]]));
const g2 = buildGazetteer(q2p);
const g3 = buildGazetteer(q3p, {extraAliases: siteAliases, operatorAliases: operatorAliases(delta)});
const r2 = bindAll(corpus, g2), r3 = bindAll(corpus, g3);

const added = new Set(delta.added);
const summary = {
  corpus: {items: corpus.length, by_source: corpus.reduce((acc, item) => { for (const s of new Set(item.sources)) acc[s] = (acc[s] ?? 0) + 1; return acc; }, {}),
    curated_primary: corpus.filter(item => item.curated.role === 'PRIMARY_MATCH').length},
  registers: {q2: {path: q2.path, sha256: q2.sha256, projects: q2p.length}, q3: {path: q3.path, sha256: q3.sha256, projects: q3p.length}},
  gazetteer: {q2_aliases: g2.alias_count, q3_aliases: g3.alias_count},
  q2_counts: r2.counts, q3_counts: r3.counts,
  delta_counts: delta.counts, delta_gate: delta.gate,
};
// Agreement with curated PRIMARY bindings (hand-approved / v5-v6 builder output).
const agreement = {curated_primary: 0, same_ref: 0, same_development: 0, different_ref: 0, abstained: 0, details: []};
corpus.forEach((item, i) => {
  if (item.curated.role !== 'PRIMARY_MATCH') return;
  agreement.curated_primary++;
  const got = r3.results[i];
  if (got.repd_ref === item.curated.repd_ref) agreement.same_ref++;
  else if (got.outcome === 'PRIMARY_MATCH' && got.related_components.some(c => c.repd_ref === item.curated.repd_ref)) agreement.same_development++;
  else if (got.outcome === 'PRIMARY_MATCH') { agreement.different_ref++; agreement.details.push({headline: item.headline, curated: item.curated, got: got.repd_ref, cand: got.candidates}); }
  else { agreement.abstained++; agreement.details.push({headline: item.headline, curated: item.curated, got: got.outcome, reason: got.reason, cand: got.candidates.map(c => c.repd_ref + ' ' + c.name)}); }
});
summary.agreement_with_curated_primary = {...agreement, details: undefined};
// New bindings that only exist because of Q3 refs.
const newlyBound = [];
corpus.forEach((item, i) => {
  const a = r2.results[i], b = r3.results[i];
  const refs = [b.repd_ref, ...b.candidates.map(c => c.repd_ref)].filter(Boolean);
  if (refs.some(ref => added.has(ref))) newlyBound.push({headline: item.headline, url: item.url, q2: a.outcome, q3: b.outcome, q3_ref: b.repd_ref, candidates: b.candidates});
});
summary.items_touching_refs_added_since_july = newlyBound.length;
summary.changed_outcome_q2_to_q3 = corpus.filter((_, i) => r2.results[i].outcome !== r3.results[i].outcome || r2.results[i].repd_ref !== r3.results[i].repd_ref).length;
// Bound projects whose status changed Q2->Q3: review signal.
const statusMap = new Map(delta.status_changed.map(row => [row.repd_ref, row]));
summary.bound_items_with_status_change = r3.results.filter(r => r.repd_ref && statusMap.has(r.repd_ref)).map(r => ({repd_ref: r.repd_ref, ...statusMap.get(r.repd_ref)}));

const rows = corpus.map((item, i) => ({url: item.url, headline: item.headline, sources: [...new Set(item.sources)], topic: item.topic ?? null,
  curated: item.curated, q2: pick(r2.results[i]), q3: pick(r3.results[i])}));
function pick(r) { return {outcome: r.outcome, reason: r.reason, repd_ref: r.repd_ref, capacity_check: r.capacity_check?.status ?? null, reported_mw: r.capacity_check?.reported_mw, register_mw: r.capacity_check?.register_mw, candidates: r.candidates.map(c => `${c.repd_ref}:${c.name}`), related: r.related_components.map(c => c.repd_ref)}; }
writeFileSync(path.join(out, 'binding-results.json'), JSON.stringify(rows, null, 1) + '\n');
writeFileSync(path.join(out, 'binding-summary.json'), JSON.stringify({...summary, disagreements: agreement.details, newly_bound: newlyBound}, null, 1) + '\n');
console.log(JSON.stringify(summary, null, 1));

Measure DC

A JavaScript module in the scripts folder of Neural Link Between Agents that reads sector intelligence.

storageneural-link-between-agents / FIXES/NL-019/N2/scripts/measure-dc.mjs · lines 1–19 of 19 · Not reached from any entry point (candidate for review)

What it does
It loads sector intelligence. Defines S, F. Uses libraries node:fs. 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: JSON file 202608272130-sector-intelligence.json; JSON file 202608271524-fd2212a8c76d-v8-fast-news.json; command-line arguments.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-019/N2/scripts · JavaScript module
Uses
node:fs, ./b/discovery/datacentre-binder.mjs
Used by
none found
Produces
S, F
Defines here
S, F
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-019/N2/scripts/measure-dc.mjs:1-19 · blob dd066d0bb1982e35e42613fd2cecfb775db58a5c · GitHub at these lines
State
achieves: name · context: auto · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer, ai_agent · canonical: unreached_review
import {readFileSync, writeFileSync} from 'node:fs';
import {verifyRegisterBytes, buildSites, bindDataCentres} from './b/discovery/datacentre-binder.mjs';
const [geo, pn, out] = process.argv.slice(2);
const reg = buildSites(verifyRegisterBytes(readFileSync(geo)));
const sector = JSON.parse(readFileSync(`${pn}/releases/202609060232-pipelinenews/data/202608272130-sector-intelligence.json`, 'utf8'));
const S = n => sector.fields.indexOf(n);
const news = JSON.parse(readFileSync(`${pn}/releases/202609060232-pipelinenews/data/202608271524-fd2212a8c76d-v8-fast-news.json`, 'utf8'));
const F = n => news.fields.indexOf(n);
const items = new Map();
for (const r of sector.rows) items.set(r[S('canonical_url')], {id: r[S('intelligence_item_id')], url: r[S('canonical_url')], headline: r[S('title')], summary: r[S('summary')], frozen_topic: r[S('topic_code')]});
for (const r of news.rows) if (!items.has(r[F('url')])) items.set(r[F('url')], {id: r[F('gg_article_id')], url: r[F('url')], headline: r[F('headline')], evidence_snippet: r[F('evidence_snippet')], frozen_topic: null});
const list = [...items.values()];
const res = bindDataCentres(list, reg);
const named = reg.sites.filter(s => s.identities.length).length;
const summary = {register_sites: reg.sites.length, sites_with_name_identity: named, alias_count: reg.aliases.length,
  map_status: reg.sites.reduce((a, s) => (a[s.map_status] = (a[s.map_status] ?? 0) + 1, a), {}),
  items: list.length, frozen_data_centre_topic_items: list.filter(i => i.frozen_topic === 'DATA_CENTRES').length, counts: res.counts,
  rows: res.results.filter(r => r.outcome !== 'NOT_DATA_CENTRE_TOPIC').map((r, i) => ({headline: list.find(x => (x.id ?? x.url) === r.item_id).headline, outcome: r.outcome, reason: r.reason, dc_site_id: r.dc_site_id, site: r.site_name ?? null, map: r.map_status, candidates: r.candidates.slice(0, 5).map(c => `${c.dc_site_id}:${c.name}`)}))};
writeFileSync(out, JSON.stringify(summary, null, 1) + '\n'); console.log(JSON.stringify(summary, null, 1));