In this section
- Claude Audit B5db0b35 test · neural-link-between-agents / FIXES/NL-012/tests/claude-audit-b5db0b35.py lines 1–41
- Anomalies storage · neural-link-between-agents / FIXES/NL-013/scripts/anomalies.py lines 1–94
- Check Identity Fields ingest · neural-link-between-agents / FIXES/NL-013/scripts/check_identity_fields.py lines 1–88
- Check Subsets ingest · neural-link-between-agents / FIXES/NL-013/scripts/check_subsets.py lines 1–79
- Cmp Identity ingest · neural-link-between-agents / FIXES/NL-013/scripts/cmp_identity.py lines 1–22
- Make Patches storage · neural-link-between-agents / FIXES/NL-013/scripts/make_patches.py lines 1–91
- Rederive storage · neural-link-between-agents / FIXES/NL-013/scripts/rederive.py lines 1–142
- Textdiff CSV Xlsx ingest · neural-link-between-agents / FIXES/NL-013/scripts/textdiff_csv_xlsx.py lines 1–40
- Xlsx Lookup other · neural-link-between-agents / FIXES/NL-013/scripts/xlsx_lookup.py lines 1–8
- Indep Diff storage · neural-link-between-agents / FIXES/NL-014/scripts/indep_diff.py lines 1–77
Claude Audit B5db0b35
A Python module in the tests folder of Neural Link Between Agents that tests the Renewable Energy Planning Database (REPD) register.
testneural-link-between-agents / FIXES/NL-012/tests/claude-audit-b5db0b35.py · lines 1–41 of 41 · Not reached from any entry point (candidate for review)
- What it does
- It tests the REPD register. Uses libraries sys, io, re, json, pandas. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'claude'): 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.
- Inputs & outputs
- In: CSV file repd.csv.
- 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-012/tests · Python module
- Uses
- sys, io, re, json, pandas, repd_sources_v6, datetime
- 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-012/tests/claude-audit-b5db0b35.py:1-41 · blob 84f6dddcbd5116b5c2e1dd11291185a13f2b8e39 · GitHub at these lines
- State
- achieves: name · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import sys, io, re, json
sys.path.insert(0, '../globalgrid2050/scripts')
import pandas as pd
import repd_sources_v6 as q2
from datetime import datetime
print("== 1 norm_date edge cases")
for v in ["07/03/2026","2026-03-07","03/25/2026","31/02/2026","7 March 2026","07/03/26","n/a","", pd.Timestamp("2026-07-03"), 46000]:
print(" %r -> %r" % (v, q2.norm_date(v)))
print(" unparseable pair equal?", q2.norm_date("7 March 2026")==q2.norm_date("9 May 2025"), "| unparseable vs blank equal?", q2.norm_date("07/03/26")==q2.norm_date(""))
print("== 2 Excel round trip")
buf=io.BytesIO()
df=pd.DataFrame({"Ref ID":[1,2,3],"Site Name":["a","b","c"],"Technology Type":["x"]*3,"Installed Capacity (MWelec)":[1.005,2,3],
"Planning Application Submitted":[pd.Timestamp("2026-07-03"),"07/03/2026","03/25/2026"]})
df.to_excel(buf,index=False); fr,_=q2.read_xlsx(buf.getvalue())
for r,v in zip(fr["Ref ID"],fr["Planning Application Submitted"]): print(" ref",r,type(v).__name__,repr(v),"->",q2.norm_date(v))
print(" csv '07/03/2026' ->",q2.norm_date("07/03/2026"),"vs true-date cell 3 Jul 2026 ->",q2.norm_date(pd.Timestamp("2026-07-03")),"(day/month swap shows as a conflict)")
print("== 3 historical repd.csv through the same reader")
raw=open('../globalgrid2050/repd.csv','rb').read()
f=q2.read_csv(raw); print(" rows",len(f),"cols",len(f.columns),"unique refs",f["Ref ID"].map(q2.clean_ref).nunique(), "ends with newline",raw.endswith(b"\n"))
print(" last row ref",f["Ref ID"].iloc[-1],"| non-empty cells in last row",int((f.iloc[-1]!="").sum()))
lead=0; ex=[]
for c in f.columns:
m=f[c].astype(str).str.match(r'^[=+\-@\t\r]')
# ignore plain negative/positive numbers
m&=~f[c].astype(str).str.match(r'^[+\-]?\d+(\.\d+)?$')
if m.any():
lead+=int(m.sum()); ex.append((c,int(m.sum()),f.loc[m,c].iloc[0][:40]))
print(" cells starting with = + - @ (formula risk if opened in Excel):",lead); [print(" ",e) for e in ex[:8]]
nl=sum(int(f[c].astype(str).str.contains(r'[\r\n]').sum()) for c in f.columns); print(" cells containing line breaks (collapse() flattens these in the canonical):",nl)
bad={}
for c in q2.OFFICIAL_DATE_FIELDS:
if c in f.columns:
s=f[c].astype(str); nb=s[(s.str.strip()!="")]; u=nb[nb.map(q2.norm_date)==""]
us=nb[nb.map(lambda t: bool(re.fullmatch(r'\d{1,2}/\d{1,2}/\d{4}',t.strip())) and int(t.split('/')[1])>12)]
if len(u) or len(us): bad[c]=(len(u),list(u[:3]),len(us))
print(" date fields with non-blank values norm_date turns into '' (count, examples, mm/dd-only count):",bad or "none")
print("== 4 truncation guard: cut the file at a row boundary")
lines=raw.split(b"\n"); cut=b"\n".join(lines[:12600])+b"\n"
try:
g=q2.read_csv(cut); print(" truncated copy parses cleanly:",len(g),"rows; passes the >=12,000 floor:",len(g)>=12000,"; below last validated 14,657:",len(g)<14657)
except Exception as e: print(" truncated copy rejected:",str(e)[:120])Anomalies
A Python module in the scripts folder of Neural Link Between Agents that reads the Renewable Energy Planning Database (REPD) register. It is built from the add step (`add`).
storageneural-link-between-agents / FIXES/NL-013/scripts/anomalies.py · lines 1–94 of 94 · Entry point
- What it does
- It loads the REPD register. Defines add. Uses libraries csv, json, re, sys, collections. 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: the REPD register.
- Inputs & outputs
- In: command-line arguments. Out: JSON file.
- Downstream impact
- It is itself an entry point (Python module); no other file was found loading it.
- What it achieves
- Task 8: hunt source anomalies in the cleaned October file (report only).
- 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-013/scripts · Python module
- Uses
- csv, json, re, sys, collections, datetime
- Used by
- none found
- Produces
- add
- Defines here
- add
- 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-013/scripts/anomalies.py:1-94 · blob 063b71e0dc76feaba7f9479b08159d3f511e3e99 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Task 8: hunt source anomalies in the cleaned October file (report only).
usage: anomalies.py CLEANED.csv KNOWN.json PREV_IDENTITY_V6.json OUT.json"""
import csv, json, re, sys
from collections import Counter, defaultdict
from datetime import date, datetime
cl, kn, prev, out = sys.argv[1:5]
rows = list(csv.DictReader(open(cl, encoding="utf-8", newline="")))
rows = [{" ".join(k.split()): v for k, v in r.items()} for r in rows]
known = json.load(open(kn))["known"]
P = {r["repd_ref"]: r for r in json.load(open(prev))["records"]}
refs = {r["Ref ID"] for r in rows}
D = lambda s: datetime.strptime(s, "%d/%m/%Y").date() if s else None
AS_OF = date(2026, 11, 13)
A = defaultdict(list)
def add(kind, r, detail):
A[kind].append({"ref": r["Ref ID"], "site": r["Site Name"][:60], "detail": detail, "known": r["Ref ID"] in known})
for r in rows:
sub, gr, ref_, ex = D(r["Planning Application Submitted"]), D(r["Planning Permission Granted"]), D(r["Planning Permission Refused"]), D(r["Planning Permission Expired"])
uc, op, upd = D(r["Under Construction"]), D(r["Operational"]), D(r["Record Last Updated (dd/mm/yyyy)"])
st = r["Development Status (short)"].strip()
for name in ("Planning Application Submitted", "Planning Permission Granted", "Under Construction", "Operational",
"Record Last Updated (dd/mm/yyyy)", "Appeal Lodged", "Appeal Granted", "Planning Permission Refused"):
d = D(r[name])
if d and d > AS_OF:
add("FUTURE_EVENT_DATE", r, f"{name} {r[name]}")
if d and d.year < 1980:
add("VERY_OLD_DATE", r, f"{name} {r[name]}")
if upd and upd > AS_OF:
pass
if gr and sub and gr < sub:
add("GRANTED_BEFORE_SUBMITTED", r, f"submitted {sub} granted {gr}")
if ex and gr and ex < gr:
add("EXPIRED_BEFORE_GRANTED", r, f"granted {gr} expired {ex}")
if op and uc and op < uc:
add("OPERATIONAL_BEFORE_CONSTRUCTION", r, f"uc {uc} op {op}")
if op and sub and op < sub and (sub - op).days > 365:
add("OPERATIONAL_LONG_BEFORE_SUBMISSION", r, f"sub {sub} op {op}")
if st == "Operational" and not op:
add("STATUS_OPERATIONAL_NO_DATE", r, "")
if st in ("Application Submitted", "Awaiting Construction") and op:
add("PRE_OPERATIONAL_STATUS_WITH_OPERATIONAL_DATE", r, f"{st} op {op}")
cap = r["Installed Capacity (MWelec)"].strip().replace(",", "")
if cap:
try:
c = float(cap)
if c <= 0:
add("CAPACITY_NON_POSITIVE", r, cap)
if c > 4000:
add("CAPACITY_VERY_LARGE", r, cap)
except ValueError:
add("CAPACITY_NON_NUMERIC", r, cap)
for col in ("Storage Co-location REPD Ref ID", "Are they re-applying (New REPD Ref)", "Are they re-applying (Old REPD Ref)"):
v = r[col].strip()
for tok in re.findall(r"\d+", v):
if tok not in refs and col != "Are they re-applying (Old REPD Ref)":
add("DANGLING_CROSS_REFERENCE", r, f"{col}={v!r} -> {tok} not in release")
if v and v == r["Ref ID"]:
add("SELF_REFERENCE", r, f"{col}={v}")
for col in ("Site Name", "Address", "Operator (or Applicant)"):
v = r[col]
if re.search(r"Ã.|â€", v):
add("MOJIBAKE_IN_SOURCE", r, f"{col}: {v[:70]!r}")
if re.search(r"\w\?\w|\s\?\w", v):
add("QUESTION_MARK_REPLACEMENT_CHAR", r, f"{col}: {v[:70]!r}")
if r["Technology Type"].strip() == "Solar Photovoltaics" and r["No. of Turbines"].strip() not in ("", "0"):
add("SOLAR_WITH_TURBINES", r, r["No. of Turbines"])
# status regressions vs July
p = P.get(r["Ref ID"])
if p:
order = {"Application Submitted": 1, "Awaiting Construction": 2, "Under Construction": 3, "Operational": 4}
a, b = order.get(p["status"]), order.get(st)
if a and b and b < a:
add("STATUS_REGRESSION_VS_JULY", r, f"{p['status']} -> {st}")
if p.get("planning_authority") and r["Planning Authority"].strip() and p["planning_authority"] != r["Planning Authority"].strip():
add("PLANNING_AUTHORITY_TEXT_CHANGED_VS_JULY", r, f"{p['planning_authority']!r} -> {r['Planning Authority'].strip()!r}")
if p.get("site_name") and p["site_name"] != " ".join(r["Site Name"].split()):
add("SITE_NAME_CHANGED_VS_JULY", r, f"{p['site_name'][:40]!r} -> {r['Site Name'][:40]!r}")
if p.get("repd_record_updated") and upd and D(p["repd_record_updated_raw"]) and upd < D(p["repd_record_updated_raw"]):
add("RECORD_LAST_UPDATED_WENT_BACKWARDS", r, f"{p['repd_record_updated_raw']} -> {r['Record Last Updated (dd/mm/yyyy)']}")
# duplicate site name + coordinates across refs
key = defaultdict(list)
for r in rows:
if r["X-coordinate"].strip() and r["Site Name"].strip():
key[(r["Site Name"].strip().lower(), r["X-coordinate"].strip(), r["Y-coordinate"].strip(), r["Technology Type"], r["Development Status (short)"])].append(r["Ref ID"])
dups = {"|".join(k[:1] + k[3:]): v for k, v in key.items() if len(v) > 1}
summary = {k: {"count": len(v), "unknown": sum(not x["known"] for x in v)} for k, v in sorted(A.items())}
json.dump({"summary": summary, "same_name_coords_tech_status_groups": len(dups),
"same_name_examples": dict(list(dups.items())[:15]), "anomalies": A}, open(out, "w"), indent=1, ensure_ascii=False)
print(json.dumps(summary, indent=1)); print("same name+coords+tech+status groups:", len(dups))Check Identity Fields
A Python module in the scripts folder of Neural Link Between Agents.
ingestneural-link-between-agents / FIXES/NL-013/scripts/check_identity_fields.py · lines 1–88 of 88 · Entry point
- What it does
- It loads data. Uses libraries csv, json, sys, collections, datetime. 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: command-line arguments.
- Downstream impact
- It is itself an entry point (Python module); no other file was found loading it.
- What it achieves
- Task 5: identity + major projects, field by field against the cleaned CSV; stability vs July.
- 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-013/scripts · Python module
- Uses
- csv, json, sys, collections, datetime
- 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-013/scripts/check_identity_fields.py:1-88 · blob fc99f422d914a894b7a06d15aa6e1c6da024a697 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""Task 5: identity + major projects, field by field against the cleaned CSV; stability vs July.
usage: check_identity_fields.py CLEANED.csv IDENTITY_Q3.json MAJOR_Q3.json IDENTITY_JUL.json MAJOR_JUL.json"""
import csv, json, sys
from collections import Counter
from datetime import datetime
cl, idq, mpq, idj, mpj = sys.argv[1:6]
rows = list(csv.DictReader(open(cl, encoding="utf-8", newline="")))
norm = lambda h: " ".join(h.split())
rows = [{norm(k): v for k, v in r.items()} for r in rows]
by = {r["Ref ID"]: r for r in rows}
iso = lambda s: datetime.strptime(s, "%d/%m/%Y").date().isoformat() if s.strip() else None
txt = lambda s: (" ".join(s.split()) or None)
MAP = {"site_name": "Site Name", "technology": "Technology Type", "status": "Development Status (short)",
"operator": "Operator (or Applicant)", "county": "County", "region": "Region", "country": "Country",
"planning_authority": "Planning Authority", "planning_application_reference": "Planning Application Reference"}
DATES = {"planning_application_submitted": "Planning Application Submitted",
"planning_application_withdrawn": "Planning Application Withdrawn",
"planning_permission_refused": "Planning Permission Refused",
"planning_permission_granted": "Planning Permission Granted",
"planning_permission_expired": "Planning Permission Expired",
"under_construction": "Under Construction", "operational": "Operational",
"repd_record_updated": "Record Last Updated (dd/mm/yyyy)"}
I = json.load(open(idq))
mism = Counter(); ex = {}
cap_diff = Counter()
for r in I["records"]:
c = by.get(r["repd_ref"])
if c is None:
mism["ref_missing_in_cleaned"] += 1; continue
for f, col in MAP.items():
if (r.get(f) or None) != txt(c[col]) and (r.get(f) or "").strip() != c[col].strip():
mism[f] += 1; ex.setdefault(f, (r["repd_ref"], r.get(f), c[col]))
for f, col in DATES.items():
if r.get(f) != iso(c[col]):
mism[f] += 1; ex.setdefault(f, (r["repd_ref"], r.get(f), c[col]))
raw = c["Installed Capacity (MWelec)"].strip().replace(",", "")
try:
cv = float(raw) if raw else None
except ValueError:
cv = "NONNUM"
if cv is None or cv == "NONNUM":
if r["capacity_known"] or r["capacity_mw"] not in (None,):
mism["capacity_blank_but_known"] += 1; ex.setdefault("capacity_blank_but_known", (r["repd_ref"], r["capacity_mw"], raw))
else:
d = abs((r["capacity_mw"] or 0) - cv)
cap_diff["exact" if d == 0 else ("<=0.005" if d <= 0.0050001 else ">0.005")] += 1
if d > 0.0050001:
ex.setdefault("capacity_gt_tol", (r["repd_ref"], r["capacity_mw"], raw))
if (r.get("repd_old_ref") or None) != (c["Old Ref ID"].strip() or None):
mism["repd_old_ref"] += 1; ex.setdefault("repd_old_ref", (r["repd_ref"], r.get("repd_old_ref"), c["Old Ref ID"]))
print("identity records", len(I["records"]), "cleaned rows", len(rows), "refs equal", {r["repd_ref"] for r in I["records"]} == set(by))
print("identity field mismatches:", dict(mism) or "none"); [print(" e.g.", k, v) for k, v in ex.items()]
print("capacity vs cleaned CSV text:", dict(cap_diff))
# major projects selection from first principles (identity capacity, all statuses?)
M = json.load(open(mpq))
sel = {r["repd_ref"] for r in I["records"] if r["capacity_known"] and (
(r["technology"] == "Solar Photovoltaics" and r["capacity_mw"] > 1.0) or
(r["technology"] == "Battery" and r["capacity_mw"] > 100.0))}
got = {p["repd_ref"] for p in M["projects"]}
print("major projects", len(got), "first-principles", len(sel), "missing", sorted(sel - got)[:10], "extra", sorted(got - sel)[:10])
idx = {r["repd_ref"]: r for r in I["records"]}
pm = Counter()
for p in M["projects"]:
r = idx[p["repd_ref"]]
for f in set(p) & set(r):
if p[f] != r[f]:
pm[f] += 1
print("major vs identity shared-field mismatches:", dict(pm) or "none")
# stability vs July
J = json.load(open(idj))
jj = {r["repd_ref"]: r for r in J["records"]}
qq = idx
both = set(jj) & set(qq)
pid = sum(jj[k]["gg_project_id"] != qq[k]["gg_project_id"] for k in both)
dev = sum(jj[k]["gg_development_id"] != qq[k]["gg_development_id"] for k in both)
print(f"stability: July {len(jj)} Oct {len(qq)} shared {len(both)} removed {len(set(jj)-set(qq))} added {len(set(qq)-set(jj))}; "
f"gg_project_id changed {pid}; gg_development_id changed {dev}")
devchg = [k for k in both if jj[k]["gg_development_id"] != qq[k]["gg_development_id"]]
print(" development id changes e.g.", sorted(devchg, key=int)[:15])
MJ = json.load(open(mpj))
print("major July", len(MJ["projects"]), "Oct", len(M["projects"]), "dropped refs", len({p['repd_ref'] for p in MJ['projects']} - got),
"added", len(got - {p['repd_ref'] for p in MJ['projects']}))Check Subsets
A Python module in the scripts folder of Neural Link Between Agents covering the Renewable Energy Planning Database (REPD) register and solar.
ingestneural-link-between-agents / FIXES/NL-013/scripts/check_subsets.py · lines 1–79 of 79 · Entry point · pattern analyse (shared by 8 files)
- What it does
- Defines read, cap, analyse. Uses libraries csv, io, json, sys, collections. 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: the REPD register, solar.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- It is itself an entry point (Python module); no other file was found loading it.
- What it achieves
- It is built from the read step (`read`), the cap step (`cap`) and the analyse step (`analyse`). Task 4: first-principles subset filters, validated against January (main) and applied to October.
- 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-013/scripts · Python module
- Uses
- csv, io, json, sys, collections, pathlib
- Used by
- none found
- Produces
- read, cap, analyse
- Defines here
- read, cap, analyse
- 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-013/scripts/check_subsets.py:1-79 · blob 08fb3434a07ddfa58ea9bdc667d0c7869724598a · GitHub at these lines
- State
- achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""Task 4: first-principles subset filters, validated against January (main) and applied to October.
usage: check_subsets.py JAN_ROOT OCT_ROOT"""
import csv, io, json, sys
from collections import Counter
from pathlib import Path
jan, octo = Path(sys.argv[1]), Path(sys.argv[2])
norm = lambda h: " ".join(h.replace("", "").split())
def read(p):
raw = p.read_bytes()
for enc in ("utf-8-sig", "cp1252"):
try:
t = raw.decode(enc); break
except UnicodeDecodeError:
continue
rows = list(csv.reader(io.StringIO(t, newline="")))
return rows[0], rows[1:], enc, raw
def cap(s):
try:
return float(s.replace(",", "").strip())
except ValueError:
return None
def analyse(root, suffix):
out = {}
h, body, enc, raw = read(root / f"repd{suffix}.csv")
n = [norm(x) for x in h]
I = {k: i for i, k in enumerate(n)}
out["full"] = {"rows": len(body), "cols": len(h), "enc": enc, "bom": raw.startswith(b"\xef\xbb\xbf"),
"crlf": raw.count(b"\r\n")}
refs = [r[I["Ref ID"]].strip() for r in body]
tech, stat, capc, mnt = I["Technology Type"], I["Development Status (short)"], I["Installed Capacity (MWelec)"], I["Mounting Type for Solar"]
for name, fn, hdr in (
("repd-grid-batteries", lambda r: r[tech].strip() == "Battery", None),
("repd-solar-operational", lambda r: r[tech].strip() == "Solar Photovoltaics" and r[stat].strip() == "Operational"
and (cap(r[capc]) or 0) > 1 and r[mnt].strip() in ("Ground", "Roof"), None),
("repd-solar-operational-over-4mw", lambda r: r[tech].strip() == "Solar Photovoltaics" and r[stat].strip() == "Operational"
and (cap(r[capc]) or 0) > 4, None)):
sh, sb, senc, sraw = read(root / f"{name}{suffix}.csv")
ragged = sum(len(r) != len(sh) for r in sb)
sb = [r for r in sb if len(r) == len(sh)]
sn = [norm(x) for x in sh]
sref = [r[sn.index("Ref ID")].strip() for r in sb]
cand = [r for r in body if fn(r)]
info = {"ragged_records_dropped_for_check": ragged, "rows": len(sb), "cols": len(sh), "enc": senc, "bom": sraw.startswith(b"\xef\xbb\xbf"),
"crlf": sraw.count(b"\r\n"), "dup_refs": len(sref) - len(set(sref)),
"header_is_subset_of_full_in_order": [x for x in n if x in set(sn)] == sn}
if name == "repd-grid-batteries":
st = Counter(r[stat].strip() for r in cand)
kept = Counter(r[sn.index("Development Status (short)")].strip() for r in sb)
info["battery_status_all"] = dict(st)
info["battery_status_kept"] = dict(kept)
keepset = set(kept)
cand = [r for r in cand if r[stat].strip() in keepset]
cref = [r[I["Ref ID"]].strip() for r in cand]
info["first_principles_rows"] = len(cand)
info["refs_missing_from_subset"] = sorted(set(cref) - set(sref), key=int)[:20]
info["refs_extra_in_subset"] = sorted(set(sref) - set(cref), key=lambda x: int(x) if x.isdigit() else 0)[:20]
info["order_equal"] = cref == sref
# every cell equal to the full file's cell (by column name)
byref = {r[I["Ref ID"]].strip(): r for r in body}
bad = 0
for r in sb:
f = byref.get(r[sn.index("Ref ID")].strip())
if f is None or any(r[j] != f[I[c]] for j, c in enumerate(sn)):
bad += 1
info["rows_not_equal_to_full"] = bad
out[name] = info
return out
res = {"january_main": analyse(jan, ""), "october_pr": analyse(octo, "-2026q3")}
print(json.dumps(res, indent=1))Cmp Identity
A Python module in the scripts folder of Neural Link Between Agents that compares `project_identity` JSON files record by record (ignores `validated_at`).
ingestneural-link-between-agents / FIXES/NL-013/scripts/cmp_identity.py · lines 1–22 of 22 · Entry point
- What it does
- It loads data. Uses libraries json, sys, collections. 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: command-line arguments.
- Downstream impact
- It is itself an entry point (Python module); 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-013/scripts · Python module
- Uses
- json, sys, collections
- 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-013/scripts/cmp_identity.py:1-22 · blob 2159697229f6aeba7f44e074211552b43bde2866 · GitHub at these lines
- State
- achieves: name · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""Compare project_identity JSON files record by record (ignores validated_at). usage: cmp_identity.py A B [label]"""
import json, sys
from collections import Counter
a, b = (json.load(open(p)) for p in sys.argv[1:3])
top = sorted(k for k in set(a) | set(b) if k != "records" and a.get(k) != b.get(k))
print("top-level keys differing:", {k: (a.get(k), b.get(k)) for k in top if k != "validated_at"} or "none (validated_at only)" if top else "none")
ka = {r["gg_project_id"]: r for r in a["records"]}
kb = {r["gg_project_id"]: r for r in b["records"]}
print("records", len(ka), len(kb), "only_a", len(set(ka) - set(kb)), "only_b", len(set(kb) - set(ka)))
fields = Counter()
ex = {}
for k in set(ka) & set(kb):
for f in set(ka[k]) | set(kb[k]):
if ka[k].get(f) != kb[k].get(f):
fields[f] += 1
ex.setdefault(f, (k, ka[k].get(f), kb[k].get(f)))
print("field differences:", dict(fields))
for f, e in ex.items():
print(" e.g.", f, e)
print("order equal:", [r["gg_project_id"] for r in a["records"]] == [r["gg_project_id"] for r in b["records"]])Make Patches
A Python module in the scripts folder of Neural Link Between Agents that reads diff and the Renewable Energy Planning Database (REPD) register.
storageneural-link-between-agents / FIXES/NL-013/scripts/make_patches.py · lines 1–91 of 91 · Entry point · pattern lines (shared by 10 files)
- What it does
- It loads diff and the REPD register. Defines lines, udiff. Uses libraries difflib, collections, pathlib. 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: the REPD register.
- Inputs & outputs
- In: JSON file 2026q3_known_anomalies.json; JSON file manifest_v4_2026q3.json; JSON file diff.json.
- Downstream impact
- It is itself an entry point (Python module); no other file was found loading it.
- What it achieves
- It is built from the lines step (`lines`) and the udiff step (`udiff`). Split the Team 1 patch tree (`pt/`) into one unified diff per fix, each against /gg-wt (`wt/` copy).
- 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-013/scripts · Python module
- Uses
- difflib, collections, pathlib
- Used by
- none found
- Produces
- lines, udiff
- Defines here
- lines, udiff
- 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-013/scripts/make_patches.py:1-91 · blob 40d447b2b5fe9dd4501c1ca0a47c2838eb91d00e · GitHub at these lines
- State
- achieves: comment · context: auto · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Split the Team 1 patch tree (pt/) into one unified diff per fix, each against <workspace>/gg-wt (wt/ copy).
Every change block (difflib opcode) is assigned to exactly one fix by keyword; unassigned blocks abort."""
import difflib
from collections import defaultdict
from pathlib import Path
T = Path("<workspace>/teams/1")
WT, PT, OUT = T / "wt", T / "pt", T / "patches"
OUT.mkdir(exist_ok=True)
RULES = {
"automation/repd/run.py": [
("0001", ["SystemExit"]),
("0004", ["acceptance_waivers", "waive", "waived_cells", "acceptance_waive_cells"]),
("0006", ["known_coordinates", "kcoord", "**kw"]),
],
"automation/repd/validate.py": [
("0005", ["_MDY_ANY", "_csv_text_is_date", "swap", "different date", "typed XLSX date", "invalid.append", "continue", "resolved.append", "dt = xd"]),
("0006", ["known_scope", "known_coordinates", "load_known_coordinates", "coord_anoms"]),
],
"automation/repd/build_root.py": [
("0002", ["tempfile", "scratch", "registry", "resolve()", "import os", "chdir"]),
("0009", ["normalise_descriptor", "release_id"]),
],
}
WHOLE = { # file -> fix (all changes of the file)
".github/workflows/repd-release-candidate.yml": "0003",
"automation/repd/hashguard.py": "0007",
"automation/repd/baselines/2026q3_known_anomalies.json": "0008",
"dist/manifest_v4_2026q3.json": "0010",
"docs/repd/2026q3/changes-jan-to-oct/changelog.md": "0011",
"docs/repd/2026q3/changes-jan-to-oct/diff.json": "0011",
"automation/repd/tests/test_hardening_nl013.py": "0012",
}
NAMES = {
"0001": "run-stage-catches-systemexit",
"0002": "build-root-master-in-scratch-dir-no-config-needed",
"0003": "workflow-sparse-config-and-hidden-path-check",
"0004": "run-acceptance-waivers-from-known-anomalies",
"0005": "validate-date-gate-rejects-different-or-unparseable-dates",
"0006": "validate-coordinate-waivers-scoped-to-known-coordinates",
"0007": "hashguard-rehash-skip-worktree-and-assume-unchanged",
"0008": "baseline-known-anomalies-2026q3-coordinates-waiver-observations",
"0009": "build-root-accepts-v1-descriptor-shape",
"0010": "data-manifest-v4-2026q3-source-hashes",
"0011": "data-jan-to-oct-change-report-regenerated-from-shipped-csv",
"0012": "tests-hardening-nl013",
}
def lines(p):
return p.read_text(encoding="utf-8").splitlines(keepends=True) if p.exists() else []
def udiff(rel, a, b):
out = list(difflib.unified_diff(a, b, fromfile=f"a/{rel}" if a else "/dev/null", tofile=f"b/{rel}", n=3))
fixed = []
for ln in out:
fixed.append(ln if ln.endswith("\n") else ln + "\n\\ No newline at end of file\n")
return "".join(fixed)
per_fix = defaultdict(str)
for rel, rules in RULES.items():
a, b = lines(WT / rel), lines(PT / rel)
sm = difflib.SequenceMatcher(None, a, b, autojunk=False)
variants = defaultdict(list) # fix -> list of opcodes
for op in sm.get_opcodes():
tag, i1, i2, j1, j2 = op
if tag == "equal":
continue
text = "".join(a[i1:i2] + b[j1:j2])
hits = [fix for fix, kws in rules if any(k in text for k in kws)]
if len(hits) != 1:
raise SystemExit(f"{rel}: block {op} matched {hits}:\n{text[:400]}")
variants[hits[0]].append(op)
for fix, ops in variants.items():
new, pos = [], 0
for tag, i1, i2, j1, j2 in ops:
new += a[pos:i1] + b[j1:j2]
pos = i2
new += a[pos:]
per_fix[fix] += udiff(rel, a, new)
for rel, fix in WHOLE.items():
per_fix[fix] += udiff(rel, lines(WT / rel), lines(PT / rel))
for fix, text in sorted(per_fix.items()):
path = OUT / f"{fix}-{NAMES[fix]}.patch"
path.write_text(text, encoding="utf-8")
print(path.name, text.count("\n@@"), "hunks", len(text), "bytes")Rederive
A Python module in the scripts folder of Neural Link Between Agents covering rederive report, rederive changes and the Renewable Energy Planning Database (REPD) register, using SHA-256.
storageneural-link-between-agents / FIXES/NL-013/scripts/rederive.py · lines 1–142 of 142 · Entry point · pattern serial (shared by 3 files)
- What it does
- It lists and searches rederive report, rederive changes and the REPD register. Defines clean_text, serial. Uses libraries csv, hashlib, io, json, re. 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: the REPD register.
- Inputs & outputs
- In: command-line arguments. Out: CSV file rederived-repd-2026q3.csv; JSON file rederive-report.json; JSON file rederive-changes.json.
- Downstream impact
- It is itself an entry point (Python module); no other file was found loading it.
- What it achieves
- It cleans text (`clean_text`) and is built from the serial step (`serial`). Independent re-derivation of `repd-2026q3.csv` from the official CSV + XLSX (Team 1, task 1).
- 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-013/scripts · Python module
- Uses
- csv, hashlib, io, json, re, sys, collections, datetime
- Used by
- none found
- Produces
- clean_text, serial
- Defines here
- clean_text, serial
- 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-013/scripts/rederive.py:1-142 · blob 7f4b3b0a1a29cb2b91d3387ea48d8dc6a55e79cd · GitHub at these lines
- State
- achieves: comment · context: auto · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Independent re-derivation of repd-2026q3.csv from the official CSV + XLSX (Team 1, task 1).
Written from the stated policy only (docs/repd/2026q3/CLEANING-LOG.txt header), not from clean.py:
* drop byte-identical duplicate records (keep first)
* the 16 date columns: value = Excel typed date as dd/mm/yyyy; blank where Excel is blank
* non-date cells whose workbook value is a number < 61 shown with a date format: workbook number
* other cells: strip an edge whitespace run only if it contains TAB/CR/LF; inner line-break runs -> ' '
Then compare with the official CSV (count and classify every changed cell) and with the PR's file.
usage: rederive.py OFFICIAL.csv OFFICIAL.xlsx PR_repd-2026q3.csv OUTDIR
"""
import csv, hashlib, io, json, re, sys
from collections import Counter
from datetime import datetime, date
from pathlib import Path
import openpyxl
csv_p, xlsx_p, pr_p, out = map(Path, sys.argv[1:5])
out.mkdir(parents=True, exist_ok=True)
DATE_COLS = {"Record Last Updated (dd/mm/yyyy)", "Judicial Review", "Planning Application Submitted",
"Planning Application Withdrawn", "Planning Permission Refused", "Appeal Lodged", "Appeal Withdrawn",
"Appeal Refused", "Appeal Granted", "Planning Permission Granted", "Secretary of State - Intervened",
"Secretary of State - Refusal", "Secretary of State - Granted", "Planning Permission Expired",
"Under Construction", "Operational"}
norm = lambda h: " ".join(str(h).split())
raw = csv_p.read_bytes()
text = raw.decode("cp1252") # official encoding per log; fail loudly otherwise
rows = list(csv.reader(io.StringIO(text, newline="")))
header, body = rows[0], rows[1:]
assert all(len(r) == len(header) for r in body), "field count"
names = [norm(h) for h in header]
ri = names.index("Ref ID")
wb = openpyxl.load_workbook(xlsx_p, read_only=True, data_only=True)
ws = wb["REPD"] if "REPD" in wb.sheetnames else wb.worksheets[0]
xit = ws.iter_rows()
xh = [norm(c.value) for c in next(xit) if c.value is not None]
assert xh == names, "header mismatch"
xrows = {}
xdup = Counter()
for r in xit:
vals = [(c.value, getattr(c, "number_format", "General"), getattr(c, "is_date", False)) for c in r[:len(xh)]]
vals += [(None, "General", False)] * (len(xh) - len(vals))
if all(v[0] is None for v in vals):
continue
ref = vals[ri][0]
ref = str(int(ref)) if isinstance(ref, (int, float)) else str(ref).strip()
xdup[ref] += 1
xrows.setdefault(ref, vals)
EDGE_L, EDGE_R = re.compile(r"^[ \t\r\n]+"), re.compile(r"[ \t\r\n]+$")
BRK = re.compile(r"[ \t]*[\r\n]+[ \t]*")
def clean_text(s):
m = EDGE_L.match(s)
if m and re.search(r"[\t\r\n]", m.group()):
s = s[m.end():]
m = EDGE_R.search(s)
if m and re.search(r"[\t\r\n]", m.group()):
s = s[:m.start()]
return BRK.sub(" ", s)
def serial(d):
# Excel 1900 system: before 1 Mar 1900 serial 1 = 1900-01-01 (phantom 29 Feb 1900 comes later)
return (d - datetime(1899, 12, 31)).total_seconds() / 86400.0
seen, outrows, changes, removed = {}, [], [], []
kinds = Counter()
date_csv_agree = Counter()
for n, r in enumerate(body, 1):
ref = r[ri].strip()
if ref in seen:
assert seen[ref] == r, f"conflicting duplicate {ref}"
removed.append((ref, n)); continue
seen[ref] = r
x = xrows[ref]
new = []
for i, (name, before) in enumerate(zip(names, r)):
xv, fmt, isd = x[i]
if name in DATE_COLS:
if isinstance(xv, (datetime, date)):
d = xv.date() if isinstance(xv, datetime) else xv
assert not (isinstance(xv, datetime) and xv.time() != datetime.min.time())
after = d.strftime("%d/%m/%Y")
cs = before.strip()
if cs == after: k = "date_same"
elif cs == d.strftime("%m/%d/%Y") or cs == f"{d.month}/{d.day}/{d.year}": k = "date_month_first"
else: k = "date_other!"
else:
assert xv is None or (isinstance(xv, str) and xv.strip().casefold() in ("", "na", "n/a")), (ref, name, xv)
after = ""
cs = before.strip()
k = "blank_same" if before == "" else ("date_na" if cs.casefold() in ("na", "n/a") else
("date_ws" if cs == "" else "csv_date_excel_blank!"))
date_csv_agree[k] += 1
if after != before:
kinds[k] += 1
elif isinstance(xv, datetime) and xv < datetime(1900, 3, 1):
s = serial(xv)
after = str(int(s)) if s == int(s) else repr(s)
assert before.strip() == xv.strftime("%d/%m/%Y"), (ref, name, before, xv)
kinds["num_as_date"] += 1
else:
after = clean_text(before)
if after != before:
kinds["edge_control" if after == before.strip(" \t\r\n") and not BRK.search(before.strip(" \t\r\n")) else "linebreak_or_mixed"] += 1
if after != before:
changes.append({"ref": ref, "column": header[i], "before": before, "after": after})
new.append(after)
outrows.append(new)
buf = io.StringIO(newline="")
w = csv.writer(buf, lineterminator="\n")
w.writerow(header); w.writerows(outrows)
mine = buf.getvalue().encode("utf-8")
(out / "rederived-repd-2026q3.csv").write_bytes(mine)
pr = pr_p.read_bytes()
# cell-level comparison with the PR file
prrows = list(csv.reader(io.StringIO(pr.decode("utf-8"), newline="")))
cell_diffs = []
for a, b in zip(outrows, prrows[1:]):
for i, (u, v) in enumerate(zip(a, b)):
if u != v:
cell_diffs.append({"ref": a[ri], "column": header[i], "mine": u, "pr": v})
rep = {
"official_csv_sha256": hashlib.sha256(raw).hexdigest(),
"official_xlsx_sha256": hashlib.sha256(xlsx_p.read_bytes()).hexdigest(),
"official_records": len(body), "xlsx_records": sum(xdup.values()),
"xlsx_duplicates": {k: v for k, v in xdup.items() if v > 1},
"removed_duplicates": removed,
"rows_out": len(outrows), "distinct_cells_changed": len(changes),
"kinds": dict(kinds), "date_cells_by_class": dict(date_csv_agree),
"mine_sha256": hashlib.sha256(mine).hexdigest(), "mine_bytes": len(mine),
"pr_sha256": hashlib.sha256(pr).hexdigest(), "pr_bytes": len(pr),
"byte_identical": mine == pr, "pr_rows": len(prrows) - 1, "cell_diffs_vs_pr": cell_diffs[:50],
"cell_diff_count_vs_pr": len(cell_diffs),
}
(out / "rederive-report.json").write_text(json.dumps(rep, indent=1, ensure_ascii=False))
(out / "rederive-changes.json").write_text(json.dumps(changes, indent=0, ensure_ascii=False))
print(json.dumps({k: v for k, v in rep.items() if k != "cell_diffs_vs_pr"}, indent=1))Textdiff CSV Xlsx
A Python module in the scripts folder of Neural Link Between Agents. It is built from the num step (`num`).
ingestneural-link-between-agents / FIXES/NL-013/scripts/textdiff_csv_xlsx.py · lines 1–40 of 40 · Entry point
- What it does
- It loads data. Defines num. Uses libraries csv, io, re, sys, collections. 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: command-line arguments.
- Downstream impact
- It is itself an entry point (Python module); no other file was found loading it.
- What it achieves
- Independent: every non-date cell, official CSV text vs XLSX value (Team 1).
- 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-013/scripts · Python module
- Uses
- csv, io, re, sys, collections, datetime, openpyxl
- Used by
- none found
- Produces
- num
- Defines here
- num
- 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-013/scripts/textdiff_csv_xlsx.py:1-40 · blob b2de0c789355e48a2750fa500ada7607015b4ddd · GitHub at these lines
- State
- achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""Independent: every non-date cell, official CSV text vs XLSX value (Team 1). usage: textdiff_csv_xlsx.py CSV XLSX"""
import csv, io, re, sys
from collections import Counter
from datetime import datetime
import openpyxl
DATE = {"Record Last Updated (dd/mm/yyyy)","Judicial Review","Planning Application Submitted","Planning Application Withdrawn","Planning Permission Refused","Appeal Lodged","Appeal Withdrawn","Appeal Refused","Appeal Granted","Planning Permission Granted","Secretary of State - Intervened","Secretary of State - Refusal","Secretary of State - Granted","Planning Permission Expired","Under Constructio … [line shortened here: 417 characters; full line on GitHub]
n = lambda h: " ".join(str(h).split())
rows = list(csv.reader(io.StringIO(open(sys.argv[1], "rb").read().decode("cp1252"), newline="")))
H = [n(h) for h in rows[0]]; ri = H.index("Ref ID")
c = {}
for r in rows[1:]: c.setdefault(r[ri].strip(), r)
ws = openpyxl.load_workbook(sys.argv[2], read_only=True, data_only=True)["REPD"]
it = ws.iter_rows(values_only=True); next(it)
cat = Counter(); text = []; cap = Counter(); capcells = []
norm = lambda s: re.sub(r"[\s-]+", " ", s).strip()
def num(s):
try: return float(str(s).replace(",", "").strip())
except ValueError: return None
for x in it:
if all(v is None for v in x): continue
ref = str(int(x[ri])) if isinstance(x[ri], (int, float)) else str(x[ri]).strip()
r = c[ref]
for i, h in enumerate(H):
if h in DATE: continue
xv = x[i] if i < len(x) else None
cv = r[i]
if isinstance(xv, datetime) and xv < datetime(1900, 3, 1): continue # numbers stored as dates
xs = "" if xv is None else (str(int(xv)) if isinstance(xv, float) and xv.is_integer() else str(xv))
if norm(cv) == norm(xs): continue
a, b = num(cv), num(xv) if not isinstance(xv, str) else num(xv)
if a is not None and b is not None:
k = "numeric_equal" if a == b else ("numeric_rounded<=0.005" if abs(a - b) <= 0.0050001 else "NUMERIC_DIFFERENT")
else:
k = "TEXT_DIFFERENT"; text.append((ref, h, cv, xs))
cat[(h, k)] += 1
if h == "Installed Capacity (MWelec)" and a is not None and b is not None and a != b:
if a >= 1 > b: capcells.append((ref, r[H.index("Technology Type")], r[H.index("Development Status (short)")], cv, b))
print(dict(cat)); print("TEXT_DIFFERENT cells:", [(r_, h, repr(a_), repr(b_)) for r_, h, a_, b_ in text])
print("capacity: CSV >= 1 but XLSX < 1:", len(capcells), Counter((t, s) for _, t, s, _, _ in capcells).most_common(6))Xlsx Lookup
A Python module in the scripts folder of Neural Link Between Agents.
otherneural-link-between-agents / FIXES/NL-013/scripts/xlsx_lookup.py · lines 1–8 of 8 · Not reached from any entry point (candidate for review)
- What it does
- Uses libraries sys, openpyxl.
- 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: command-line arguments.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · FIXES/NL-013/scripts · Python module
- Uses
- sys, openpyxl
- 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-013/scripts/xlsx_lookup.py:1-8 · blob ec4b69d93aa9cb34fe69c6d2c9dd600ce0e888b2 · GitHub at these lines
- State
- achieves: name · context: auto · stage: unknown · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import sys, openpyxl
wb=openpyxl.load_workbook(sys.argv[1],read_only=True,data_only=True); ws=wb['REPD']
it=ws.iter_rows(values_only=True); h=[str(x).strip() if x else x for x in next(it)]
want=set(sys.argv[3:]); cols=sys.argv[2].split('|')
ri=h.index('Ref ID')
for r in it:
if r[ri] is not None and str(int(r[ri]) if isinstance(r[ri],(int,float)) else r[ri]) in want:
print(r[ri], {c: r[i] for i,c in enumerate(h) if c and any(c.startswith(k) for k in cols)})Indep Diff
A Python module in the scripts folder of Neural Link Between Agents that reads the Renewable Energy Planning Database (REPD) register.
storageneural-link-between-agents / FIXES/NL-014/scripts/indep_diff.py · lines 1–77 of 77 · Not reached from any entry point (candidate for review) · pattern classify (shared by 27 files)
- What it does
- It loads the REPD register. Defines load, ws, num, dt, classify. Uses libraries csv, io, json, re, sys. 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: the REPD register. README: "automation/repd/diff.py and the independent scripts/indep_diff.py agree on every column."
- Inputs & outputs
- In: command-line arguments. Out: JSON file.
- What it achieves
- It is built from the load step (`load`), the num step (`num`) and the classify step (`classify`). Independent 53-column Ref-ID diff of two official-layout REPD CSVs (no automation/REPD code).
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · FIXES/NL-014/scripts · Python module
- Uses
- csv, io, json, re, sys, collections, datetime
- Used by
- none found
- Produces
- load, ws, num, dt, classify
- Defines here
- load, ws, num, dt, classify
- 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-014/scripts/indep_diff.py:1-77 · blob 1ab90972efc6d015381f31b0dd7473491f586ae6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Independent 53-column Ref-ID diff of two official-layout REPD CSVs (no automation/repd code).
usage: indep_diff.py PREV.csv NEW.csv OUT.json
Each changed cell on a retained ref is classified:
whitespace equal after collapsing whitespace (incl. NBSP, CR/LF, zero-width)
case equal after whitespace collapse + casefold
spacing equal after deleting all whitespace (line-break removal such as 'Road\n, Town' -> 'Road, Town')
separator_slash_to_ampersand equal after mapping '/' to '&' (October joint-operator style)
numeric both parse as numbers and are equal within 0.0051
date both parse as dd/mm/yyyy (or d/m/yyyy, ISO) to the same date
material anything else (blank<->value counts here, split out as filled/blanked)"""
import csv, io, json, re, sys, collections, datetime
def load(p):
raw = open(p, 'rb').read()
for enc in ('utf-8-sig', 'cp1252'):
try: txt = raw.decode(enc); break
except UnicodeDecodeError: pass
rows = list(csv.reader(io.StringIO(txt, newline='')))
hdr = [' '.join(h.split()) for h in rows[0]]
recs, dups = {}, []
for r in rows[1:]:
if not any(c.strip() for c in r): continue
ref = r[1].strip()
if ref in recs:
dups.append([ref, recs[ref] == r]); continue
recs[ref] = r
return hdr, recs, dups, enc
WS = re.compile(r'[\s ]+')
def ws(s): return WS.sub(' ', s).strip()
def num(s):
try: return float(ws(s).replace(',', ''))
except ValueError: return None
def dt(s):
s = ws(s)
for f in ('%d/%m/%Y', '%Y-%m-%d', '%Y-%m-%d %H:%M:%S'):
try: return datetime.datetime.strptime(s, f).date()
except ValueError: pass
return None
def classify(a, b):
if ws(a) == ws(b): return 'whitespace'
if ws(a).casefold() == ws(b).casefold(): return 'case'
if WS.sub('', a).casefold() == WS.sub('', b).casefold(): return 'spacing'
if WS.sub('', a.replace('/', '&')).casefold() == WS.sub('', b.replace('/', '&')).casefold(): return 'separator_slash_to_ampersand'
if not ws(a): return 'material_filled'
if not ws(b): return 'material_blanked'
na, nb = num(a), num(b)
if na is not None and nb is not None and abs(na - nb) <= 0.0051: return 'numeric'
da, db = dt(a), dt(b)
if da and db and da == db: return 'date'
return 'material_changed'
ph, P, pd_, pe = load(sys.argv[1]); nh, N, nd, ne = load(sys.argv[2])
assert ph == nh, 'headers differ'
added = sorted(set(N) - set(P), key=int); removed = sorted(set(P) - set(N), key=int)
kept = sorted(set(P) & set(N), key=int)
cols = collections.OrderedDict((h, collections.Counter()) for h in ph)
examples = collections.defaultdict(list)
refs_material = set()
for ref in kept:
a, b = P[ref], N[ref]
for i, h in enumerate(ph):
if a[i] == b[i]: continue
c = classify(a[i], b[i])
cols[h][c] += 1
if c.startswith('material'):
refs_material.add(ref)
if len(examples[h]) < 5: examples[h].append([ref, a[i], b[i]])
out = {'previous': {'file': sys.argv[1].split('/')[-1], 'encoding': pe, 'refs': len(P), 'duplicate_rows': pd_},
'new': {'file': sys.argv[2].split('/')[-1], 'encoding': ne, 'refs': len(N), 'duplicate_rows': nd},
'added': len(added), 'removed': len(removed), 'retained': len(kept),
'removed_refs': removed, 'added_refs': added,
'retained_refs_with_material_change': len(refs_material),
'columns': {h: dict(c) for h, c in cols.items()},
'material_by_column': {h: sum(v for k, v in c.items() if k.startswith('material')) for h, c in cols.items()},
'examples': examples}
json.dump(out, open(sys.argv[3], 'w'), indent=1, ensure_ascii=False)
print('added', len(added), 'removed', len(removed), 'retained', len(kept), 'refs w/ material change', len(refs_material))
for h, c in cols.items():
if c: print(f' {h:45s} {dict(c)}')