In this section
- Furnace Pilot storage · neural-link-between-agents / SESSIONS/AGENT-13/FURNACE-RD/experiments/prospecting/furnace_pilot.py lines 1–219
- Verify Pilot ingest · neural-link-between-agents / SESSIONS/AGENT-13/FURNACE-RD/experiments/prospecting/verify_pilot.py lines 1–69
- Test Validate test · neural-link-between-agents / SESSIONS/AGENT-13/NEURAL-MEMORIES/test_validate.py lines 1–77
- Validate ingest · neural-link-between-agents / SESSIONS/AGENT-13/NEURAL-MEMORIES/validate.py lines 1–126
- Audit storage · neural-link-between-agents / automation/v923-recovery/audit.py lines 1–160
- Validate Operations ingest · neural-link-between-agents / automation/validate_operations.py lines 1–29
Furnace Pilot
A Python command-line tool in the prospecting folder of Neural Link Between Agents that writes receipt (`write_receipt`) (units: MW), covering the Renewable Energy Planning Database (REPD) register, using SHA-256.
storageneural-link-between-agents / SESSIONS/AGENT-13/FURNACE-RD/experiments/prospecting/furnace_pilot.py · lines 1–219 of 219 · Entry point · pattern write_receipt (shared by 6 files)
- What it does
- It lists and searches the REPD register. Defines 6 functions or classes, including require, producer, write_receipt, main, gpu. Uses libraries argparse, ast, datetime, hashlib, json. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the require step (`require`), the producer step (`producer`) and the gpu step (`gpu`). Offline bounded synthetic-input replay of pinned prospecting score arithmetic. It accepts `--output`, `--cases` and `--repeats`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- neural-link-between-agents · SESSIONS/AGENT-13/FURNACE-RD/experiments/prospecting · Python CLI
- Uses
- argparse, ast, datetime, hashlib, json, math, os, pathlib
- Used by
- none found
- Produces
- require, producer, write_receipt, main
- Defines here
- require, producer, write_receipt, main, gpu, cpu
- 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 SESSIONS/AGENT-13/FURNACE-RD/experiments/prospecting/furnace_pilot.py:1-219 · blob 982eef59a6024bfccf4462965c0b032231c1e9c7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: ai_agent · canonical: supporting_data
"""Offline bounded synthetic-input replay of pinned prospecting score arithmetic.
CPU performs producer feature extraction. GPU adds integer hundredths and sorts.
No source acquisition, real-corpus parity, news parser or publication certification.
"""
import argparse
import ast
import datetime
import hashlib
import json
import math
import os
from pathlib import Path
import re
import statistics
import time
import types
import warnings
PINS = {'relevance': '8be79d5e5048b79eae425f14f749cfa439a03774c2c27fb0b1309aca3b953f43',
'prospecting': '23c2c054a1d55b07e60af513709071476bdc6202dbf0e8b4ec87b23cf59ddf73'}
SOURCE_COMMIT = '0cb4f71e948df23e2985f189a5a1d77e88d332b2'
KERNEL = r'''
extern "C" __global__ void score(const int* x, int n, int* out) {
int i=blockDim.x*blockIdx.x+threadIdx.x;
if(i>=n) return;
int s=x[i*4]+x[i*4+1]+1500;
if(x[i*4+2]) s+=800;
if(x[i*4+3]) s+=500;
out[i]=s;
}
'''
def require(ok):
if not ok:
raise ValueError('verification_failed')
def producer():
"""Run only an explicit AST subset from SHA-pinned local producer sources."""
env = {'math': math, 're': re, 'date': datetime.date}
selected = {
'relevance': {'_c', 'capacity_component', 'technology_component',
'national_route_component', 'evidence_component'},
'prospecting': {'official_candidate', 'capacity', 'require', 'component',
'text', 'research_policy_fields', 'freshness'}}
for name in ('relevance', 'prospecting'):
raw = Path(__file__).with_name(name + '.source').read_bytes()
require(hashlib.sha256(raw).hexdigest() == PINS[name])
tree = ast.parse(raw)
nodes = []
for node in tree.body:
if name == 'relevance' and isinstance(node, ast.Assign):
if any(isinstance(t, ast.Name) and t.id in {'PROFILE_ID', 'DEFAULT_PROFILE'} for t in node.targets):
nodes.append(node)
if isinstance(node, ast.FunctionDef) and node.name in selected[name]:
nodes.append(node)
local = dict(env)
exec(compile(ast.Module(body=nodes, type_ignores=[]), '<pinned-producer-subset>', 'exec'), local)
if name == 'relevance':
env['relevance'] = types.SimpleNamespace(**{k: local[k] for k in selected[name]})
else:
return local['official_candidate'], env['relevance']
def write_receipt(path, receipt):
path.parent.mkdir(parents=True, exist_ok=True)
temp = path.with_suffix(path.suffix + '.tmp')
temp.write_text(json.dumps(receipt, indent=2, sort_keys=True, allow_nan=False) + '\n', encoding='utf-8')
os.replace(temp, path)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--cases', type=int, default=65536)
parser.add_argument('--repeats', type=int, default=3)
parser.add_argument('--seed', type=int, default=20261116)
parser.add_argument('--inject-failure', action='store_true', help='Deliberately corrupt GPU score; must exit 1 with rejected receipt')
args = parser.parse_args()
receipt = dict(schema='furnace.prospecting-numeric-pilot.v1', accepted=False,
status='running', source_commit=SOURCE_COMMIT, source_sha256=PINS,
script_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
production_enabled=False, synthetic_inputs=True,
scope='Pinned official_candidate score and ID ordering on synthetic rows; CPU feature extraction; no real-corpus, news, provenance, rights, browser or publication acceptance',
seed=args.seed, requested_cases=args.cases, repeats=args.repeats,
deliberate_failure_requested=args.inject_failure, tolerance_hundredths=0,
ordering_validation='Both GPU scoring channels share CuPy lexsort; independent Python string-key oracle witnesses every rank')
write_receipt(args.output, receipt)
started = time.perf_counter()
phase = 'input_validation'
try:
require(32 <= args.cases <= 262144 and 1 <= args.repeats <= 10 and 0 <= args.seed <= 2**32-1)
import numpy as np
oracle, relevance = producer()
rng = np.random.default_rng(args.seed)
n = args.cases
# Independent synthetic records, not copies of any live/source project.
mw = rng.uniform(0, 2000, n)
known = rng.integers(0, 2, n, dtype=np.int32)
tech_idx = rng.integers(0, 6, n, dtype=np.int32)
route = rng.integers(0, 2, n, dtype=np.int32)
age = rng.integers(-1, 60, (n, 2), dtype=np.int32)
# Explicit zero/unknown/cap boundary + inclusive freshness windows + tied IDs.
caps = [None, 0., 999., 998.999999, 999.000001, 1e-12, 1e9, 0., 0., 0., 0., 0.]
for i, v in enumerate(caps):
mw[i] = v or 0.; known[i] = int(v is not None)
tech_idx[:12] = 0; route[:12] = 0
age[:12] = [[-1,-1],[-1,-1],[30,14],[31,14],[30,15],[0,0],[-1,0],[30,14],[30,15],[-1,-1],[0,-1],[31,15]]
techs = [None, 'Solar Photovoltaics', 'Battery', 'Wind Onshore', 'Hydrogen', 'Unknown technology']
features = np.empty((n,4), np.int32)
expected = np.empty(n, np.int32)
extraction_start = time.perf_counter()
for i in range(n):
capacity = float(mw[i]) if known[i] else None
tech = techs[int(tech_idx[i])]
authority = 'Scottish Government (S36)' if route[i] else None
a, b = (int(v) for v in age[i])
fresh = a >= 0 and b >= 0 and a <= 30 and b <= 14
article = {'freshness': {'state': 'WITHIN_WINDOW' if 0 <= a <= 30 else 'UNKNOWN' if a < 0 else 'STALE'},
'retrieval_freshness': {'state': 'WITHIN_WINDOW' if 0 <= b <= 14 else 'UNKNOWN' if b < 0 else 'STALE'}}
row = dict(capacity_mw=capacity, capacity_known=bool(known[i]), repd_ref=str(i+1),
repd_technology=tech, planning_authority=authority, name=None, country=None,
technology=tech, status=None, repd_record_updated=None)
actual = oracle(row, {}, {'articles':[article]}, None)
expected[i] = round(actual['score']*100)
features[i] = [round(relevance.capacity_component(capacity)['points']*100),
round(relevance.technology_component(tech)['points']*100), int(route[i]), int(fresh)]
require(actual['heat']['state'] == 'UNKNOWN' and actual['heat']['score'] == 0)
extraction_seconds = time.perf_counter()-extraction_start
# Rank IDs exactly as producer string ordering (e.g. REPD-10 before REPD-2).
ids = ['REPD-'+str(i+1) for i in range(n)]
string_order = sorted(range(n), key=ids.__getitem__)
id_key = np.empty(n, np.int32)
id_key[string_order] = np.arange(n, dtype=np.int32)
oracle_order = np.asarray(sorted(range(n), key=lambda i: (-int(expected[i]), ids[i])), dtype=np.int64)
require(expected[0] == expected[1] == 1500 and known[0] != known[1])
require(expected[2] == 5000 and expected[3] == 4500 and expected[4] == 4500)
require(expected[7] == 2000 and expected[8] == 1500)
input_hash = hashlib.sha256()
for x in (mw,known,tech_idx,route,age,features,id_key):
input_hash.update(str(x.dtype).encode()); input_hash.update(str(x.shape).encode()); input_hash.update(x.tobytes())
receipt.update(input_sha256=input_hash.hexdigest(), processed_rows=n,
unique_source_feature_cases=int(np.unique(np.column_stack((np.where(known,mw,-1),known,tech_idx,route,age)),axis=0).shape[0]),
unique_numeric_feature_cases=int(np.unique(features,axis=0).shape[0]),
boundary_fixture_rows=12, cpu_oracle_rows=n,
cpu_feature_extraction_and_producer_oracle_seconds=extraction_seconds,
unknown_capacity_rows=int((known==0).sum()), known_zero_capacity_rows=int(((known==1)&(mw==0)).sum()),
array_memory_conservative_bound_bytes=512*n, array_memory_limit_bytes=256*1024*1024,
maximum_cases=262144, channels=['raw CUDA integer branches','CuPy independent expression graph'],
cpu_oracle='SHA-pinned official_candidate AST subset', integer_score_unit='hundredth point')
phase = 'gpu_initialization'
warnings.filterwarnings('ignore', message='CUDA path could not be detected.*', category=UserWarning)
import cupy as cp
cp.get_default_memory_pool().set_limit(size=128*1024*1024)
require(cp.cuda.runtime.getDeviceCount() > 0)
kernel = cp.RawKernel(KERNEL, 'score')
def gpu(channel):
x=cp.asarray(features); key=cp.asarray(id_key)
if channel == 'raw':
score=cp.empty(n, dtype=cp.int32)
kernel(((n+255)//256,), (256,), (x,np.int32(n),score))
else:
score = cp.sum(cp.stack((x[:,0], x[:,1], cp.full(n,1500,dtype=cp.int32), x[:,2]*800, x[:,3]*500)),axis=0,dtype=cp.int32)
if args.inject_failure:
score[0] += 1
order=cp.lexsort(cp.stack((key,-score)))
result=(cp.asnumpy(score),cp.asnumpy(order))
cp.cuda.Stream.null.synchronize()
return result
def cpu():
x=features
s=x[:,0]+x[:,1]+1500+800*x[:,2]+500*x[:,3]
return s,np.lexsort((id_key,-s))
warm_start=time.perf_counter()
phase='gpu_compilation_and_warmup'
for ch in ('raw','graph'):
s,o=gpu(ch)
receipt['mismatches']=int(np.count_nonzero(s!=expected))
receipt['maximum_absolute_error_hundredths']=int(np.max(np.abs(s-expected)))
require(np.array_equal(s,expected) and np.array_equal(o,oracle_order))
receipt['gpu_warmup_compile_seconds']=time.perf_counter()-warm_start
phase='paired_verification'
timings={'cpu_numpy':[],'raw':[],'graph':[]}
max_error=0
for _ in range(args.repeats):
for ch in timings:
cp.cuda.Stream.null.synchronize()
tick=time.perf_counter(); s,o=cpu() if ch=='cpu_numpy' else gpu(ch)
elapsed=time.perf_counter()-tick
timings[ch].append(elapsed)
max_error=max(max_error,int(np.max(np.abs(s-expected))))
require(np.array_equal(s,expected) and np.array_equal(o,oracle_order))
broken_device=cp.asarray(s); broken_device[0]+=1
broken=cp.asnumpy(broken_device)
witness=np.flatnonzero(broken!=expected)
require(witness.tolist()==[0])
broken_order=oracle_order.copy(); broken_order[:2]=broken_order[:2][::-1]
require(not np.array_equal(broken_order,oracle_order))
receipt.update(accepted=True,status='passed', device=cp.cuda.runtime.getDeviceProperties(0)['name'].decode(),
cupy_version=cp.__version__,numpy_version=np.__version__,
cuda_runtime=cp.cuda.runtime.runtimeGetVersion(),
maximum_absolute_error_hundredths=max_error,mismatches=0,
injected_score_error_detected=True,injected_score_error_witness_row=0,
injected_error_channel='CuPy graph output copied to GPU then incremented by one hundredth',
injected_order_error_detected=True,
gpu_warmup_executions=2, repeated_gpu_executions=2*args.repeats,
repeated_gpu_row_evaluations=n*2*args.repeats,
timings_seconds=timings,median_seconds={k:statistics.median(v) for k,v in timings.items()},
timing_scope='Warm scoring+full ordering; GPU synchronized H2D+D2H included; extraction/oracle and compilation excluded and separately reported',
gpu_pool_reserved_bytes=cp.get_default_memory_pool().total_bytes(),
actual_producer_parity_scope='Synthetic official_candidate scores only; CPU pre-extracted rounded capacity, technology, route/freshness; full producer validation and real inputs not tested')
except Exception as exc:
receipt.update(accepted=False,status='gpu_unavailable' if phase=='gpu_initialization' else 'failed',
failure_phase=phase,error_type=type(exc).__name__)
receipt['whole_seconds']=time.perf_counter()-started
write_receipt(args.output,receipt)
print(json.dumps({'accepted':receipt['accepted'],'status':receipt['status']}))
return 0 if receipt['accepted'] else 1
if __name__=='__main__':
raise SystemExit(main())Verify Pilot
A Python command-line tool in the prospecting folder of Neural Link Between Agents that works with negative controls (`NegativeControls`) and no gpu (`no_gpu`), using SHA-256.
ingestneural-link-between-agents / SESSIONS/AGENT-13/FURNACE-RD/experiments/prospecting/verify_pilot.py · lines 1–69 of 69 · Entry point · pattern invoke (shared by 5 files)
- What it does
- It loads data. Defines 10 functions or classes, including NegativeControls, invoke, test_cases_over_cap_fail_closed, test_zero_repeats_rejected, test_source_mutation_rejected_before_execution. Uses libraries builtins, contextlib, hashlib, importlib.util, io. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: JSON file receipt.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the negative controls class (`NegativeControls`), the invoke step (`invoke`) and the mutated step (`mutated`). Bounded negative controls, using only this pilot directory.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- neural-link-between-agents · SESSIONS/AGENT-13/FURNACE-RD/experiments/prospecting · Python CLI
- Uses
- builtins, contextlib, hashlib, importlib.util, io, json, pathlib, sys
- Used by
- none found
- Produces
- NegativeControls
- Defines here
- NegativeControls, invoke, test_cases_over_cap_fail_closed, test_zero_repeats_rejected, test_source_mutation_rejected_before_execution, mutated, test_missing_gpu_never_passes, no_gpu, test_deterministic_seed_and_inputs, test_injected_gpu_failure_rejects_receipt
- 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 SESSIONS/AGENT-13/FURNACE-RD/experiments/prospecting/verify_pilot.py:1-69 · blob c2f8fd97662391697766a483ea298862c443b97c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: ai_agent · canonical: unknown
"""Bounded negative controls, using only this pilot directory."""
import builtins
import contextlib
import hashlib
import importlib.util
import io
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
HERE=Path(__file__).resolve().parent
spec=importlib.util.spec_from_file_location('pilot',HERE/'furnace_pilot.py')
pilot=importlib.util.module_from_spec(spec); spec.loader.exec_module(pilot)
class NegativeControls(unittest.TestCase):
def invoke(self, *args):
with tempfile.TemporaryDirectory(dir=HERE) as work:
path=Path(work)/'receipt.json'
with patch.object(sys,'argv',['pilot','--output',str(path),*args]),contextlib.redirect_stdout(io.StringIO()):
code=pilot.main()
raw=path.read_text(); receipt=json.loads(raw)
self.assertNotIn(str(HERE),raw)
self.assertNotIn('C:\\',raw)
self.assertEqual(receipt['script_sha256'],hashlib.sha256((HERE/'furnace_pilot.py').read_bytes()).hexdigest())
return code,receipt
def test_cases_over_cap_fail_closed(self):
code,r=self.invoke('--cases','262145')
self.assertEqual(code,1); self.assertFalse(r['accepted'])
def test_zero_repeats_rejected(self):
code,r=self.invoke('--repeats','0')
self.assertEqual(code,1); self.assertFalse(r['accepted'])
def test_source_mutation_rejected_before_execution(self):
original=Path.read_bytes
def mutated(path):
raw=original(path)
return raw+b'\nraise Exception("must never execute")\n' if path.name=='prospecting.source' else raw
with patch.object(Path,'read_bytes',mutated):
with self.assertRaisesRegex(ValueError,'verification_failed'):
pilot.producer()
def test_missing_gpu_never_passes(self):
original=builtins.__import__
def no_gpu(name,*args,**kwargs):
if name=='cupy': raise ImportError('synthetic_unavailable')
return original(name,*args,**kwargs)
with patch('builtins.__import__',no_gpu):
code,r=self.invoke('--cases','32')
self.assertEqual(code,1); self.assertFalse(r['accepted']); self.assertEqual(r['status'],'gpu_unavailable')
def test_deterministic_seed_and_inputs(self):
code,a=self.invoke('--cases','69','--repeats','1')
other,b=self.invoke('--cases','69','--repeats','1')
self.assertEqual((code,other),(0,0))
self.assertEqual(a['input_sha256'],b['input_sha256'])
self.assertEqual(a['unique_numeric_feature_cases'],b['unique_numeric_feature_cases'])
def test_injected_gpu_failure_rejects_receipt(self):
code,r=self.invoke('--cases','32','--inject-failure')
self.assertEqual(code,1); self.assertFalse(r['accepted']); self.assertEqual(r['status'],'failed')
self.assertEqual(r['mismatches'],1); self.assertEqual(r['maximum_absolute_error_hundredths'],1)
if __name__=='__main__':
unittest.main()Test Validate
A test in Neural Link Between Agents that checks Validate. It sets up (`setUp`) and is built from the ledger tests class (`LedgerTests`) and the passing candidate ci helper (`passing_candidate_ci`).
testneural-link-between-agents / SESSIONS/AGENT-13/NEURAL-MEMORIES/test_validate.py · lines 1–77 of 77 · Entry point · pattern test_cycle (shared by 2 files)
- What it does
- It tests its inputs. Defines 18 functions or classes, including LedgerTests, setUp, reject, test_actual_handoff_has_ordered_dependencies_and_no_public_claim, test_missing_dependency. Uses libraries copy, json, pathlib, unittest. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'agent'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file 20261116-build-ledger.json.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Defines `LedgerTests`, `setUp`, `reject` and 15 more.
- Why it matters
- Guards the behaviour of Validate.
- Application
- neural-link-between-agents · SESSIONS/AGENT-13/NEURAL-MEMORIES · test
- Uses
- Validate (import), copy, json, pathlib, unittest
- Used by
- none found
- Produces
- LedgerTests
- Defines here
- LedgerTests, setUp, reject, test_actual_handoff_has_ordered_dependencies_and_no_public_claim, test_missing_dependency, test_cycle, test_stale_ci_does_not_follow_new_head, test_count_cannot_be_incremented_without_publication, test_passing_ci_alone_is_not_publication, passing_candidate_ci, test_release_dependency_missing, test_machine_verification_rejected, test_old_version_delta_cannot_be_blind_cherry_pick, edit, test_duplicate_inventory_key, test_short_commit_is_not_exact_pin, test_private_path_is_not_public_memory, test_json_duplicate_keys_rejected
- 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 SESSIONS/AGENT-13/NEURAL-MEMORIES/test_validate.py:1-77 · blob f8be5a843171a5ad01a511ce2706a2ed7767c2a7 · GitHub at these lines
- State
- achieves: name · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import copy
import json
from pathlib import Path
import unittest
from validate import unique, validate
class LedgerTests(unittest.TestCase):
def setUp(self):
self.doc = json.loads(Path(__file__).with_name("20261116-build-ledger.json").read_text(encoding="utf-8"))
def reject(self, edit, message):
edit(self.doc)
with self.assertRaisesRegex(ValueError, message):
validate(self.doc)
def test_actual_handoff_has_ordered_dependencies_and_no_public_claim(self):
result = validate(self.doc)
self.assertEqual(result["public_pipeline_count"], 0)
order = result["code_dependency_order"]
self.assertLess(order.index("figures"), order.index("covenant_ledger"))
self.assertLess(order.index("prospecting_ui"), order.index("prospecting_export"))
def test_missing_dependency(self):
self.reject(lambda d: d["components"][0]["code_requires"].append("absent"), "missing dependency")
def test_cycle(self):
self.reject(lambda d: d["components"][0]["code_requires"].append("news_consumer"), "dependency cycle")
def test_stale_ci_does_not_follow_new_head(self):
self.passing_candidate_ci()
self.reject(lambda d: d["milestones"][0].update(head="f" * 40), "stale CI head")
def test_count_cannot_be_incremented_without_publication(self):
self.reject(lambda d: d.update(public_pipeline_count=1), "count differs")
def test_passing_ci_alone_is_not_publication(self):
self.passing_candidate_ci()
self.reject(lambda d: d["milestones"][0].update(published=True), "public receipt")
def passing_candidate_ci(self):
row = self.doc["milestones"][0]
row["ci"] = {
"status": "observed_pass",
"tested_head": row["head"],
"urls": ["https://github.com/example/repository/actions/runs/1"],
}
def test_release_dependency_missing(self):
self.reject(lambda d: d["milestones"][1]["requires_release"].append("V0"), "missing dependency")
def test_machine_verification_rejected(self):
self.reject(lambda d: d["invariants"].update(automatic_verified=True), "machine verification")
def test_old_version_delta_cannot_be_blind_cherry_pick(self):
def edit(d):
row = next(c for c in d["components"] if c["id"] == "dc_expansion")
row["next_action"]["command"] = "git cherry-pick " + row["authored_commits"][0]
self.reject(edit, "historical-path")
def test_duplicate_inventory_key(self):
self.reject(lambda d: d["components"].append(copy.deepcopy(d["components"][0])), "duplicate id")
def test_short_commit_is_not_exact_pin(self):
self.reject(lambda d: d["components"][0]["authored_commits"].__setitem__(0, "c2b89326"), "invalid source commit")
def test_private_path_is_not_public_memory(self):
self.reject(lambda d: d["coverage"]["missing"].append("C:/Users/example/private"), "private path")
def test_json_duplicate_keys_rejected(self):
with self.assertRaisesRegex(ValueError, "duplicate JSON key"):
json.loads('{"status": "PASS", "status": "FAIL"}', object_pairs_hook=unique)
if __name__ == "__main__":
unittest.main()Validate
A Python command-line tool in Neural Link Between Agents that reads build ledger. It checks ci (`check_ci`) and is built from the require step (`require`) and the unique step (`unique`).
ingestneural-link-between-agents / SESSIONS/AGENT-13/NEURAL-MEMORIES/validate.py · lines 1–126 of 126 · Entry point · pattern unique (shared by 10 files)
- What it does
- It loads build ledger. Defines 7 functions or classes, including require, unique, acyclic, visit, check_ci. Uses libraries json, pathlib, re, sys. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'agent'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file 20261116-build-ledger.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Test Validate (neural-link-between-agents).
- What it achieves
- Validate this declared build handoff. No network, Git writes or command execution.
- Why it matters
- Checked by Test Validate.
- Application
- neural-link-between-agents · SESSIONS/AGENT-13/NEURAL-MEMORIES · Python CLI
- Uses
- json, pathlib, re, sys
- Used by
- imported by Test Validate (import)
- Produces
- require, unique, acyclic, check_ci, validate, main
- Defines here
- require, unique, acyclic, visit, check_ci, validate, 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 SESSIONS/AGENT-13/NEURAL-MEMORIES/validate.py:1-126 · blob 8c0537e6928fd6fb0768e99174f5f931255bbb25 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Validate this declared build handoff. No network, Git writes or command execution."""
import json
from pathlib import Path
import re
import sys
SHA = re.compile(r"[0-9a-f]{40}\Z")
DIGEST = re.compile(r"[0-9a-f]{64}\Z")
def require(condition, message):
if not condition:
raise ValueError(message)
def unique(pairs):
result = {}
for key, value in pairs:
require(key not in result, f"duplicate JSON key: {key}")
result[key] = value
return result
def acyclic(rows, key, dependencies):
nodes = {row[key]: row for row in rows}
require(len(nodes) == len(rows), f"duplicate {key}")
active, done, ordered = set(), set(), []
def visit(name):
require(name in nodes, f"missing dependency: {name}")
require(name not in active, f"dependency cycle: {name}")
if name in done:
return
active.add(name)
for child in nodes[name][dependencies]:
visit(child)
active.remove(name)
done.add(name)
ordered.append(name)
for name in nodes:
visit(name)
return ordered
def check_ci(row):
ci = row["ci"]
require(ci["status"] in {"observed_pass", "pending", "failed"}, "unknown CI status")
if ci["status"] == "observed_pass":
require(bool(SHA.fullmatch(row["head"] or "")), "CI has no exact head")
require(ci["tested_head"] == row["head"], "stale CI head")
require(bool(ci["urls"]), "passing CI has no receipt")
for url in ci["urls"]:
require(url.startswith("https://github.com/") and "/actions/runs/" in url, "invalid CI receipt URL")
def validate(doc):
require(doc["schema"] == "globalgrid2050.neural-build-ledger.v1", "unknown ledger schema")
require(doc["coverage"]["complete_transcript"] is False, "transcript completeness is not measured")
inv = doc["invariants"]
require((inv["repd_records"], inv["solar_records"], inv["solar1000_count"]) == (7775, 3604, 1000), "baseline counts changed")
require(inv["automatic_verified"] is False, "machine verification forbidden")
require(inv["critical_evidence_failure_blocks_publication"] is True, "critical source/schema gate removed")
require(bool(DIGEST.fullmatch(inv["solar1000_sha256"])), "missing pilot digest")
require(bool(SHA.fullmatch(doc["protocol_sources"]["commit"])), "protocol source is not pinned")
components = doc["components"]
require(bool(components), "empty component inventory")
ordered = acyclic(components, "id", "code_requires")
for row in components:
require(bool(row["authored_commits"]), "component lacks authored commits")
require(len(set(row["authored_commits"])) == len(row["authored_commits"]), "duplicate authored commit")
for sha in row["authored_commits"] + row["integrated_as"]:
require(bool(SHA.fullmatch(sha)), "short or invalid source commit")
require(bool(row["owned_paths"]), "component lacks file scope")
for path in row["owned_paths"]:
require(not path.startswith(("/", "\\")) and ".." not in path.split("/") and ":" not in path, "non-relative file scope")
require(row["checks"]["status"] in {"reported_pass", "observed_pass", "pending", "failed", "unavailable"}, "unknown component check status")
require(row["checks"]["evidence_url"].startswith("https://github.com/"), "missing handoff evidence")
if row["integration"] == "transplant_required":
require(row["next_action"]["kind"] == "transplant", "old release delta must be transplanted")
require(not (row["next_action"]["command"] or "").startswith("git cherry-pick"), "unsafe historical-path cherry-pick")
if row["integration"] == "candidate_integrated":
require(bool(row["integrated_as"]), "integrated component lacks resulting commit")
milestones = doc["milestones"]
acyclic(milestones, "version", "requires_release")
ids = set(ordered)
count = 0
for row in milestones:
require(set(row["components"]) <= ids, "milestone references missing component")
check_ci(row)
require(type(row["published"]) is bool, "published must be boolean")
if row["published"]:
require(row["ci"]["status"] == "observed_pass", "publication lacks passing exact-head CI")
require(bool(row["public_receipts"]), "publication lacks public receipt")
for receipt in row["public_receipts"]:
require(receipt["url"].startswith("https://"), "public URL must be HTTPS")
require(bool(SHA.fullmatch(receipt["deployment_sha"])), "missing deployed commit")
require(bool(DIGEST.fullmatch(receipt["html_sha256"])), "missing served-byte digest")
require(receipt["browser_receipt_url"].startswith("https://"), "missing actual browser receipt")
count += 1
require(type(doc["public_pipeline_count"]) is int and doc["public_pipeline_count"] == count, "public release count differs from receipts")
for row in doc["prerequisite_releases"]:
check_ci(row)
# The ledger is public. These checks are only obvious-leak checks, not a security certification.
text = json.dumps(doc, ensure_ascii=False)
require(not re.search(r"(?i)(?<![A-Za-z])[A-Z]:[\\/]|/Users/|/home/|session_id\s*[\":]|threadId", text), "private path or session identifier in public ledger")
return {"status": "PASS", "components": len(components), "milestones": len(milestones), "public_pipeline_count": count, "code_dependency_order": ordered}
def main():
path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name("20261116-build-ledger.json")
try:
doc = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique)
print(json.dumps(validate(doc), sort_keys=True))
return 0
except (OSError, ValueError, KeyError, TypeError) as exc:
print(json.dumps({"status": "FAIL", "reason": str(exc) if not isinstance(exc, OSError) else "ledger unavailable"}))
return 1
if __name__ == "__main__":
raise SystemExit(main())Audit
A Python command-line tool in the automation folder of Neural Link Between Agents that reads the Renewable Energy Planning Database (REPD) register, using SHA-256.
storageneural-link-between-agents / automation/v923-recovery/audit.py · lines 1–160 of 160 · Entry point · pattern evaluate (shared by 18 files)
- What it does
- It loads the REPD register. Defines 6 functions or classes, including digest, issue_comments, product_head, latest_real_map_run, evaluate. Uses libraries __future__, datetime, hashlib, json, os. 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). Domain terms in the code: the REPD register.
- Inputs & outputs
- Out: JSON file latest.json.
- Downstream impact
- Used directly by 1 file: V923 Six Hour Neural Audit Workflow (neural-link-between-agents).
- What it achieves
- It is built from the digest step (`digest`), the issue comments helper (`issue_comments`) and the product head helper (`product_head`). Read-only V9.23 vs V9.22 evidence audit.
- Why it matters
- Run by V923 Six Hour Neural Audit Workflow.
- Application
- neural-link-between-agents · automation/v923-recovery · Python CLI
- Uses
- __future__, datetime, hashlib, json, os, re, subprocess, sys
- Used by
- run by V923 Six Hour Neural Audit Workflow (workflow run)
- Produces
- digest, issue_comments, product_head, latest_real_map_run, evaluate, main
- Defines here
- digest, issue_comments, product_head, latest_real_map_run, evaluate, 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 automation/v923-recovery/audit.py:1-160 · blob d100451798ced1b69c9ce56fddbeae4b3967d8ee · 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
"""Read-only V9.23 vs V9.22 evidence audit. No product or GridAtlas writes."""
from __future__ import annotations
import datetime as dt
import hashlib
import json
import os
import re
import subprocess
import sys
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
PRODUCT=ROOT/"product"
BASE_ID="202611151300"
TARGET_ID="202611160020"
CUTOFF=dt.datetime(2026,11,16,6,15,tzinfo=dt.timezone.utc)
START=dt.datetime(2026,11,16,0,0,tzinfo=dt.timezone.utc)
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None
def issue_comments(repo,number):
uri=f"repos/{repo}/issues/{number}/comments?per_page=100"
try:
p=subprocess.run(["gh","api","--paginate",uri,"--jq",".[] | [.id, .created_at, .body] | @json"],capture_output=True,text=True,timeout=45)
if p.returncode:return [{"error":p.stderr[:400]}]
rows=[json.loads(x) for x in p.stdout.splitlines() if x.strip()]
return [{"id":x[0],"created_at":x[1],"snippet":x[2][:260]} for x in rows[-3:]]
except Exception as ex:return [{"error":str(ex)}]
def product_head():
"""GitHub Actions GITHUB_SHA is the *Neural* checkout, not the product commit."""
try:
p=subprocess.run(["git","-C",str(PRODUCT),"rev-parse","HEAD"],
capture_output=True,text=True,timeout=10)
return p.stdout.strip() if p.returncode == 0 else "UNVERIFIED"
except Exception:
return "UNVERIFIED"
def latest_real_map_run():
"""Read hosted GridAtlas browser verdict; URL success is not engine evidence."""
uri=("repos/Ventusltd/globalgrid2050/actions/workflows/"
"v923-gridatlas-real-map-qa.yml/runs?per_page=20")
try:
p=subprocess.run(["gh","api",uri],capture_output=True,text=True,timeout=25)
if p.returncode:
return {"state":"UNVERIFIED","error":p.stderr[:250]}
rows=json.loads(p.stdout).get("workflow_runs",[])
finished=[v for v in rows if v.get("status")=="completed"]
if not finished:return {"state":"UNVERIFIED","error":"no completed hosted run"}
# Reruns of older workflows may have a newer updated_at timestamp.
v=max(finished,key=lambda a:(a.get("updated_at") or "",a.get("created_at") or ""))
return {"state":"COMPLETED","conclusion":v.get("conclusion") or "UNVERIFIED",
"run_id":v.get("id"),"run_attempt":v.get("run_attempt"),
"updated_at":v.get("updated_at"),"url":v.get("html_url")}
except Exception as ex:
return {"state":"UNVERIFIED","error":str(ex)[:250]}
def evaluate():
now=dt.datetime.now(dt.timezone.utc)
result={"schema":"globalgrid2050.neural.v923-six-hour-audit.v1","recorded_utc":now.isoformat(),
"repository":"Ventusltd/globalgrid2050","target":"V9.23",
"window_active":START <= now <= CUTOFF,"sha":os.environ.get("GITHUB_SHA"),
"product_head_sha":product_head(),
"source":{},"checks":{},"blockers":[],"neural":{}}
parent=PRODUCT/"uk_renewables_pipeline"/BASE_ID
newer=PRODUCT/"uk_renewables_pipeline"/TARGET_ID
for label,root in [("v922",parent),("v923",newer)]:
idx=root/"index.html"
live=root/"scripts/plugins/live-news.js"
project=root/"scripts/plugins/projects-v9-8.js"
info={"index_sha256":digest(idx),"live_news_sha256":digest(live),
"project_module_sha256":digest(project),"exists":idx.is_file()}
result["source"][label]=info
if not result["source"]["v922"]["exists"]:
result["blockers"].append("MISSING_V922_BASELINE")
if not result["source"]["v923"]["exists"]:
result["blockers"].append("MISSING_V923_BUILD")
else:
html=(newer/"index.html").read_text()
live=(newer/"scripts/plugins/live-news.js").read_text()
pj=(newer/"scripts/plugins/projects-v9-8.js").read_text()
old=(parent/"scripts/plugins/projects-v9-8.js").read_text()
notes_path=newer/"scripts/plugins/machine-notes-v923.js"
notes_js=notes_path.read_text() if notes_path.exists() else ""
map_test_path=newer/"tests/browser_real_map_to_engine_agent7.mjs"
map_test=map_test_path.read_text() if map_test_path.exists() else ""
marker="\nfunction projectRowHtml(project) {"
if pj.count(marker) == 1:
inter,repd=pj.split(marker,1)
else:
inter,repd="",""
checks={
"machine_notes_heading":"MACHINE READ NOTES" in html and "data-note-ref" in pj,
"exactly_one_note_column_per_vertical":(
inter.count('class="machine-note-cell"')==1
and repd.count('class="machine-note-cell"')==1
and 'data-note-ref' not in inter
and 'data-note-ref' in repd),
"headline_summary_visible_without_click":(
"headlineSummaryV923" in notes_js
and "REFUSAL REPORTED" in notes_js
and "Possible, unverified project headline" in notes_js),
"notes_rebound_on_search_sort_and_paging":(
"pipeline-projects-rendered" in pj
and "pipeline-projects-rendered" in notes_js),
"late_gridatlas_visibility_test_retained":(
"visibility_stability" in map_test
and "visibilityStability.every" in map_test
and "1700, 4000, 4400" in map_test),
"one_visible_news_feed":"id=\"liveNews\"" in html and "id=\"newsArchive\" hidden" in html and "datacentre-news.js?v=1" not in html,
"show_table_removed":"function showProject(" not in live and "chip.addEventListener('click'" not in live,
"no_politics_panel":"datacentre-news.js?v=1" not in html,
"map_link_builder_preserved": ("function atlasUrlV9_5_1" in pj and "function atlasUrlV9_5_1" in old and
(newer/"scripts/core/atlas-receiver-v9-7.js").read_bytes()==(parent/"scripts/core/atlas-receiver-v9-7.js").read_bytes()),
"canonical_data_loader_unchanged":(newer/"scripts/data/canonical-projects-v9-5-1.js").read_bytes()==(parent/"scripts/data/canonical-projects-v9-5-1.js").read_bytes(),
"candidate_only_no_homepage_promotion":True
}
result["checks"]=checks
for name,passed in checks.items():
if not passed:result["blockers"].append("FAIL_"+name.upper())
for name,command in [
("python_candidate_structure",["python3","automation/v923-recovery/repair.py","check"]),
("candidate_js_syntax",["node","--check",f"uk_renewables_pipeline/{TARGET_ID}/scripts/plugins/machine-notes-v923.js"])
]:
p=subprocess.run(command,cwd=PRODUCT,capture_output=True,text=True,timeout=90)
result["checks"][name]=p.returncode==0
result.setdefault("command_log",{})[name]=(p.stdout+p.stderr)[-1400:]
if p.returncode:result["blockers"].append("FAIL_"+name.upper())
result["neural"]["coordination_30"]=issue_comments("Ventusltd/neural-link-between-agents",30)
result["neural"]["agent10_40"]=issue_comments("Ventusltd/neural-link-between-agents",40)
result["neural"]["gridatlas_87"]=issue_comments("Ventusltd/gridatlas",87)
result["external_ci"]={"real_map":latest_real_map_run()}
map_state=result["external_ci"]["real_map"]
if map_state.get("state")=="COMPLETED" and map_state.get("conclusion")=="failure":
result["blockers"].append("REAL_MAP_MOBILE_LATEST_HOSTED_FAILURE")
# A successful three-project run is never 7,775-record acceptance.
# Source integrity is not a visual MAP acceptance.
result["not_proven"]=["real 390px first-restore nearest result","full 7775 rendered MAP href/CSV parity",
"original publisher/REPD receipts","physical iPhone Safari","served V9.23 bytes and homepage acceptance"]
result["verdict"]="BLOCKED" if result["blockers"] else "STRUCTURAL_PASS_RELEASE_NOT_ACCEPTED"
return result
def main():
r=evaluate()
print(json.dumps({k:r[k] for k in ("recorded_utc","target","verdict","blockers","checks")},indent=2))
out=ROOT/"automation/v923-recovery/results"
out.mkdir(parents=True,exist_ok=True)
(out/"latest.json").write_text(json.dumps(r,indent=2,ensure_ascii=False)+"\n")
markdown=["# V9.23 six-hour repair audit",f"Time (UTC): {r['recorded_utc']}",f"Exact PRODUCT checkout SHA: {r['product_head_sha']}",
f"Result: **{r['verdict']}**",f"GitHub run: {os.environ.get('GITHUB_SERVER_URL','https://github.com')}/{os.environ.get('GITHUB_REPOSITORY','Ventusltd/neural-link-between-agents')}/actions/runs/{os.environ.get('GITHUB_RUN_ID','LOCAL')}","",
"## Structural gates"]
for name,val in r["checks"].items():markdown.append(f"- {'PASS' if val else 'FAIL'} {name}")
markdown+=["","## Unresolved evidence"]+[f"- {x}" for x in r["blockers"]+r["not_proven"]]
markdown+=["","## Latest real MAP browser check",
"- Hosted result: " + json.dumps(r.get("external_ci",{}).get("real_map",{}),
ensure_ascii=False,sort_keys=True),
"- Three sampled projects never establish the whole 7,775-row fleet. Hidden DOM is not user-visible acceptance."]
markdown+=["","## Coordination", "- Read latest Neural #30, Agent 10 #40 and GridAtlas #87 from the public GitHub API; source comments retained by id in the JSON receipt.","- GitHub Actions runs the deterministic checks. An issue comment does not start or continue a ChatGPT session.","- NO HOMEPAGE PROMOTION OR PRODUCT WRITES."]
(out/"latest.md").write_text("\n".join(markdown)+"\n")
return 0 # failures are visible findings, not a reason to lose receipts
if __name__=="__main__":sys.exit(main())Validate Operations
A Python module in the automation folder of Neural Link Between Agents that validates the compact coordination index without network or dependencies.
ingestneural-link-between-agents / automation/validate_operations.py · lines 1–29 of 29 · Entry point
- What it does
- It loads data. Uses libraries json, datetime, pathlib, urllib.parse. 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 STATUS.json.
- Downstream impact
- Used directly by 1 file: Operations Index Workflow (neural-link-between-agents).
- What it achieves
- Its name says it validates operations.
- Why it matters
- Run by Operations Index Workflow.
- Application
- neural-link-between-agents · automation · Python module
- Uses
- json, datetime, pathlib, urllib.parse
- Used by
- run by Operations Index Workflow (workflow run)
- 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 automation/validate_operations.py:1-29 · blob 1280d7a3973013978187794d4a5a1e3d8b232d42 · GitHub at these lines
- State
- achieves: name · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Validate the compact coordination index without network or dependencies."""
import json
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse
root = Path(__file__).resolve().parents[1]
data = json.loads((root / 'STATUS.json').read_text(encoding='utf-8'))
if data['schema_version'] != 1:
raise SystemExit('Unsupported schema_version')
stamp = datetime.fromisoformat(data['checked_at_utc'].replace('Z', '+00:00'))
if stamp.tzinfo is None:
raise SystemExit('checked_at_utc requires timezone')
states = {'HISTORICAL_ACCEPTANCE', 'REPORTED_DRAFT', 'PENDING_OWNER_SCOPE',
'IN_PROGRESS', 'BLOCKED', 'RETRYING', 'TESTED', 'REVIEWED', 'MERGED',
'PUBLICLY_VERIFIED', 'COMPLETE'}
seen = set()
for item in data['work']:
for field in ('id', 'owner', 'state', 'evidence', 'next_action'):
if not isinstance(item.get(field), str) or not item[field].strip():
raise SystemExit(f'Missing/non-text {field}')
if item['id'] in seen or item['state'] not in states:
raise SystemExit(f'Duplicate ID or invalid state: {item["id"]}')
seen.add(item['id'])
for url in [data['channel']] + [item['evidence'] for item in data['work']]:
parsed = urlparse(url)
if parsed.scheme != 'https' or parsed.hostname != 'github.com' or parsed.username or parsed.password:
raise SystemExit('Evidence must use credential-free GitHub HTTPS links')
print(f'PASS: {len(seen)} unique work IDs; valid states, timestamp and evidence links')