In this section
- 01 Protocol storage · neural-link-between-agents / FIXES/NL-011/01-protocol.py lines 1–288
- Build Link Graph storage · neural-link-between-agents / FIXES/NL-011/build_link_graph.py lines 1–156
- Dryrun Workflow automation · neural-link-between-agents / FIXES/NL-012/M1/scripts/dryrun_workflow.py lines 1–127
01 Protocol
A Python module in Neural Link Between Agents that reads rows. It is built from the fieldval step (`fieldval`), the typ step (`typ`) and the norm step (`norm`).
storageneural-link-between-agents / FIXES/NL-011/01-protocol.py · lines 1–288 of 288 · Entry point
- What it does
- It loads rows. Defines 8 functions or classes, including ts, gh, fieldval, g, typ. Uses libraries os, subprocess, sys, json, re. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file rows.json; JSON file edges.json; command-line arguments. Out: JSON file rows.json; JSON file edges.json.
- Downstream impact
- It is itself an entry point (Python module); no other file was found loading it.
- What it achieves
- Fetches issues 1-10 comments with gh into /i .JSON if absent, then prints all sections. It reads `c/rows.json` and writes `c/edges.json`.
- 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-011 · Python module
- Uses
- os, subprocess, sys, json, re, collections, datetime, statistics
- Used by
- none found
- Produces
- ts, gh, fieldval, g, typ, norm, typ, irt_ok
- Defines here
- ts, gh, fieldval, g, typ, norm, typ, irt_ok
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-011/01-protocol.py:1-288 · blob f2c625487f453a941333cc3a7a9405e619826707 · 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
# NL-011 STUDY-01 (protocol adherence). Reproduces every count in 01-protocol.md.
# Usage: python3 -I 01-protocol.py <empty-or-existing-dir>
# fetches issues 1-10 comments with gh into <dir>/i<n>.json if absent, then prints all sections.
import os,subprocess,sys
D=sys.argv[1]; os.makedirs(D,exist_ok=True)
for n in range(1,11):
p=f'{D}/i{n}.json'
if not os.path.exists(p):
out=subprocess.run(['gh','api','--paginate','--slurp',f'repos/Ventusltd/neural-link-between-agents/issues/{n}/comments?per_page=100'],capture_output=True,text=True,check=True).stdout
import json as _j; pages=_j.loads(out); open(p,'w').write(_j.dumps([c for pg in pages for c in pg]))
os.chdir(D); os.makedirs('c',exist_ok=True)
for n in range(1,11):
if not os.path.exists(f'c/i{n}.json'): os.symlink(os.path.abspath(f'i{n}.json'),f'c/i{n}.json')
sys.argv=[sys.argv[0],'c']
print('\n######## parse')
exec(compile(r'''
import json,re,sys,collections,datetime as dt
D=sys.argv[1]
ALL={}
for n in range(1,11):
for c in json.load(open(f'{D}/i{n}.json')):
c['issue']=n; ALL[c['id']]=c
FIELDS=['TYPE','IN-REPLY-TO','SCOPE','HEAD','EVIDENCE','STATUS','DETAILS','ACTION REQUESTED']
HDR=re.compile(r'^[`*\s]*\[([^\]]+?)\s*(?:→|->)\s*([^\]]+)\]\s*\[(NL-\d{3})\]\s*\[([^\]]+)\]')
FOOT='_Generated by [Claude Code](https://claude.ai/code)_'
def ts(s):
s=s.strip()
m=re.match(r'^(\d{4}-\d\d-\d\d)[ T](\d\d:\d\d)(?::\d\d)?\s*(?:UTC|Z)?\s*$',s)
if not m: return None
return dt.datetime.fromisoformat(m.group(1)+'T'+m.group(2)+':00+00:00')
def gh(s): return dt.datetime.fromisoformat(s.replace('Z','+00:00'))
def fieldval(body,f):
# line-start form, allow markdown wrappers, or inline on header line
m=re.search(r'(?m)^[\s>*`_-]*'+re.escape(f)+r'[*`_]*\s*:(.*)$',body)
if m: return m.group(1).strip()
first=body.split('\n',1)[0]
m=re.search(r'\b'+re.escape(f)+r'\s*:(.*)$',first)
if m: return m.group(1).strip()
return None
rows=[]
for n in [6,7,8,9,10]:
for c in json.load(open(f'{D}/i{n}.json')):
b=c['body']; r={'issue':n,'id':c['id'],'created':c['created_at'],'updated':c['updated_at']}
h=HDR.match(b.split('\n',1)[0])
r['hdr']=bool(h)
if h:
r['from'],r['to'],r['tag'],r['tstr']=h.group(1).strip(),h.group(2).strip(),h.group(3),h.group(4)
r['tag_ok']= r['tag']==f'NL-{n:03d}'
t=ts(r['tstr']); r['tdecl']=t
r['drift_min']= None if t is None else round((t-gh(c['created_at'])).total_seconds()/60,1)
for f in FIELDS: r[f]=fieldval(b,f)
r['nfields']=sum(r[f] is not None for f in FIELDS)
r['foot']=b.rstrip().endswith(FOOT)
r['literal_file']= b.strip().startswith('@')
rows.append(r)
json.dump(rows,open(f'{D}/rows.json','w'),default=str,indent=0)
''','parse','exec'),{'__name__':'__main__','sys':sys})
print('\n######## stats')
exec(compile(r'''
import json,collections,re,sys
R=json.load(open('c/rows.json'))
F=['TYPE','IN-REPLY-TO','SCOPE','HEAD','EVIDENCE','STATUS','DETAILS','ACTION REQUESTED']
TYPES={'HANDOFF','REQUEST','FINDING','ACK','BLOCKER','REVIEW','DECISION-PROPOSAL'}
STAT={'PASS','FAIL','UNVERIFIED','IN-PROGRESS'}
C=collections.Counter
print('per issue: total, complete8, hdr, partial, none')
tot=C()
for n in [6,7,8,9,10]:
rr=[r for r in R if r['issue']==n]
comp=sum(r['hdr'] and r['nfields']==8 for r in rr)
part=sum((r['hdr'] or r['nfields']>0) and not (r['hdr'] and r['nfields']==8) for r in rr)
none=sum((not r['hdr']) and r['nfields']==0 for r in rr)
print(n,len(rr),comp,sum(r['hdr'] for r in rr),part,none)
print('ALL',len(R),sum(r['hdr'] and r['nfields']==8 for r in R))
print('field presence',{f:sum(r[f] is not None for r in R) for f in F})
print('footer',sum(r['foot'] for r in R),'tag_ok',sum(r.get('tag_ok',False) for r in R))
# header time formats
fm=C()
for r in R:
t=r.get('tstr','')
if re.match(r'^\d{4}-\d\d-\d\d \d\d:\d\d UTC$',t): fm['YYYY-MM-DD HH:MM UTC (canonical)']+=1
elif re.match(r'^\d{4}-\d\d-\d\dT\d\d:\d\dZ$',t): fm['ISO T..Z']+=1
else: fm['other:'+t]+=1
print(fm)
# TYPE
tv=C(); tv_raw=C()
for r in R:
v=r['TYPE'] or 'MISSING'; tv_raw[v]+=1
w=re.match(r'[A-Z-]+',v); tv[w.group(0) if w else v]+=1
print('TYPE first token',tv.most_common())
print('TYPE exact enum', sum((r['TYPE'] or '') in TYPES for r in R))
print('TYPE raw non-enum',[(r['id'],r['TYPE']) for r in R if (r['TYPE'] or '') not in TYPES])
# STATUS
sv=C(); exact=0
for r in R:
v=r['STATUS']
if v is None: sv['MISSING']+=1; continue
if v in STAT: exact+=1
w=re.match(r'[A-Z][A-Z-]+',v); sv[w.group(0) if w else 'nonword:'+v[:30]]+=1
print('STATUS first token',sv.most_common(),'exact-enum',exact)
print('STATUS non-enum first token',[(r['id'],r['STATUS'][:70]) for r in R if r['STATUS'] and not re.match(r'(PASS|FAIL|UNVERIFIED|IN-PROGRESS)\b',r['STATUS'])])
# HEAD
hv=C()
for r in R:
v=r['HEAD']
if v is None: hv['MISSING']+=1
elif v.startswith('NOT-APPLICABLE'): hv['NOT-APPLICABLE']+=1
elif re.search(r'\b[0-9a-f]{7,40}\b',v): hv['has sha']+=1
else: hv['other']+=1
print('HEAD',hv)
# ACTION
av=C()
for r in R:
v=r['ACTION REQUESTED']
if v is None: av['MISSING']+=1
elif v.upper().startswith('NONE'): av['NONE']+=1
elif v=='' : av['empty-line']+=1
else: av['step']+=1
print('ACTION',av)
# DETAILS on same line or following
print('DETAILS empty-inline (content on following lines)',sum(r['DETAILS']=='' for r in R))
# body lengths
''','stats','exec'),{'__name__':'__main__','sys':sys})
print('\n######## irt')
exec(compile(r'''
import json,collections,re
R=json.load(open('c/rows.json'))
ALL={}
for n in range(1,11):
for c in json.load(open(f'c/i{n}.json')): c['issue']=n; ALL[c['id']]=c
byid={r['id']:r for r in R}
cat=collections.Counter(); bad=[]; xs=[]
for r in R:
v=r['IN-REPLY-TO']
if v is None: cat['missing']+=1; continue
m=re.search(r'issues/(\d+)#issuecomment-(\d+)',v)
if m:
iss,cid=int(m.group(1)),int(m.group(2))
if cid in ALL:
t=ALL[cid]
ok_issue = t['issue']==iss
before = t['created_at']<=r['created']
same = iss==r['issue']
k='comment URL: resolves'+('' if ok_issue else ' (wrong issue number)')+('' if before else ' (target later!)')+('' if same else ' [cross-issue]')
cat[k]+=1; xs.append((r['id'],cid))
else:
cat['comment URL: id does not exist']+=1; bad.append((r['issue'],r['id'],v[:140]))
continue
if re.match(r'^NEW\b',v): cat['NEW']+=1; continue
m=re.search(r'issues/(\d+)\b',v)
if m:
cat['issue URL only (issue %s)'%('same' if int(m.group(1))==r['issue'] else 'other')]+=1; continue
cat['prose / other']+=1; bad.append((r['issue'],r['id'],v[:140]))
for k,v in cat.most_common(): print(v,k)
print('BAD:'); [print(b) for b in bad]
json.dump(xs,open('c/edges.json','w'))
# how many NEW per issue
''','irt','exec'),{'__name__':'__main__','sys':sys})
print('\n######## hs')
exec(compile(r'''
import json,collections,re,datetime as dt
R=json.load(open('c/rows.json')); E=json.load(open('c/edges.json'))
byid={r['id']:r for r in R}
ALL={}
for n in range(1,11):
for c in json.load(open(f'c/i{n}.json')): c['issue']=n; ALL[c['id']]=c
def g(s): return dt.datetime.fromisoformat(s.replace('Z','+00:00'))
replies=collections.defaultdict(list)
for a,b in E: replies[b].append(a)
def typ(r):
m=re.match(r'[A-Z-]+',r['TYPE'] or ''); return m.group(0) if m else '?'
# ACK occurrences in text
ackline=[r['id'] for r in R if re.search(r'(?m)\bACK\s+(https://|[0-9a-f]{7}|<)',ALL[r['id']]['body'])]
print('TYPE ACK:',[ (r['id'],r['from'],r['IN-REPLY-TO'][-10:]) for r in R if typ(r)=='ACK'])
print('bodies with "ACK <url|sha>":',len(ackline),ackline)
print('bodies with word ACK anywhere:',sum(bool(re.search(r'\bACK\b',ALL[r["id"]]["body"])) for r in R))
print('bodies with acknowledg*:',[r['id'] for r in R if re.search(r'(?i)acknowledg',ALL[r["id"]]["body"])])
# directed messages
print()
tab=collections.Counter(); lat=[]
for r in R:
t=typ(r)
if t not in ('HANDOFF','REQUEST','BLOCKER','DECISION-PROPOSAL'): continue
directed = not re.match(r'^ALL\b',r['to'])
reps=sorted(replies.get(r['id'],[]),key=lambda i:ALL[i]['created_at'])
first=byid[reps[0]] if reps else None
k=(t,'directed' if directed else 'ALL', 'no explicit reply' if not first else 'first reply '+typ(first))
tab[k]+=1
if first: lat.append((t,r['id'],first['id'],round((g(first['created'])-g(r['created'])).total_seconds()/60,1)))
for k,v in sorted(tab.items()): print(v,k)
print('latencies to first explicit reply (min):',sorted(x[3] for x in lat))
import statistics
print('median',statistics.median([x[3] for x in lat]),'n',len(lat))
# reply graph stats
print('comments that are replied to:',len(replies),'reply count dist',collections.Counter(len(v) for v in replies.values()))
# addressee check: reply's FROM vs target's TO
ok=0;tot=0;mism=[]
def norm(s): return re.sub(r'\s*\(.*?\)','',s).upper()
for a,b in E:
if b not in byid: continue
A,B=byid[a],byid[b]; tot+=1
fa=norm(A['from']).split()[0];
if fa in norm(B['to']) or norm(B['to']).startswith('ALL'): ok+=1
else: mism.append((a,A['from'],b,B['to']))
print('reply sender was addressee of target (or target to ALL):',ok,'/',tot)
for m in mism[:40]: print(' ',m)
''','hs','exec'),{'__name__':'__main__','sys':sys})
print('\n######## hs2')
exec(compile(r'''
import json,collections,re
R=json.load(open('c/rows.json')); E=json.load(open('c/edges.json'))
byid={r['id']:r for r in R}
ALL={}
for n in range(1,11):
for c in json.load(open(f'c/i{n}.json')): c['issue']=n; ALL[c['id']]=c
replied={b for a,b in E}
def typ(r):
m=re.match(r'[A-Z-]+',r['TYPE'] or ''); return m.group(0) if m else '?'
for r in R:
if typ(r) in ('HANDOFF','REQUEST','BLOCKER','DECISION-PROPOSAL') and r['id'] not in replied:
later=[x['id'] for x in R if x['created']>r['created'] and str(r['id']) in ALL[x['id']]['body']]
print(r['issue'],r['id'],typ(r),'|',r['from'],'→',r['to'][:50],'| mentioned later in:',later)
''','hs2','exec'),{'__name__':'__main__','sys':sys})
print('\n######## drift')
exec(compile(r'''
import json,collections,statistics,re,datetime as dt
R=json.load(open('c/rows.json'))
d=[(r['drift_min'],r) for r in R if r.get('drift_min') is not None]
print('parsed',len(d),'unparsed',[ (r['id'],r.get('tstr')) for r in R if r.get('drift_min') is None])
v=sorted(x for x,_ in d)
print('min',v[0],'max',v[-1],'median',statistics.median(v),'mean',round(statistics.mean(v),1))
a=sorted(abs(x) for x in v); print('median |drift|',statistics.median(a),'p90 |drift|',a[int(.9*len(a))-1])
B=[(-1e9,-60),(-60,-15),(-15,-5),(-5,-2),(-2,0.01),(0.01,2),(2,5),(5,15),(15,60),(60,1e9)]
# envelope time is minute precision: declared HH:MM vs created HH:MM:SS; drift in (-1,0] means same minute
for lo,hi in B:
print(f'[{lo},{hi})',sum(lo<=x<hi for x in v))
print('same minute (declared == floor(created)):',sum(-1<x<=0 for x in v))
print('declared later than posted (future, >0):',sum(x>0 for x in v),' >5 min:',sum(x>5 for x in v),' >60:',sum(x>60 for x in v))
print('declared earlier than posted:',sum(x<=-1 for x in v))
print('per issue:')
for n in [6,7,8,9,10]:
w=[x for x,r in d if r['issue']==n]; aw=[abs(x) for x in w]
print(n,len(w),'median',statistics.median(w),'median|.|',statistics.median(aw),'max|.|',max(aw),'future',sum(x>0 for x in w))
print('largest 15:')
for x,r in sorted(d,key=lambda t:-abs(t[0]))[:15]: print(x,r['issue'],r['id'],r['from'],r['tstr'],r['created'])
print('canonical vs ISO format median |drift|:')
for lab,pat in [('canon',r' UTC$'),('iso',r'Z$')]:
w=[abs(x) for x,r in d if re.search(pat,r['tstr'])]; print(lab,len(w),statistics.median(w),max(w))
print('per sender class (HARNESS vs agents):')
for lab,f in [('HARNESS',lambda r:r['from'].startswith('HARNESS')),('agents',lambda r:not r['from'].startswith('HARNESS'))]:
w=[x for x,r in d if f(r)]; print(lab,len(w),'median',statistics.median(w),'median|.|',statistics.median([abs(y) for y in w]),'future>0',sum(y>0 for y in w),'future>5',sum(y>5 for y in w))
''','drift','exec'),{'__name__':'__main__','sys':sys})
print('\n######## strict')
import json,re
R=json.load(open('c/rows.json'))
IDS=set()
for n in range(1,11):
IDS|={c['id'] for c in json.load(open(f'c/i{n}.json'))}
T={'HANDOFF','REQUEST','FINDING','ACK','BLOCKER','REVIEW','DECISION-PROPOSAL'}
def irt_ok(v):
if v is None: return False
m=re.search(r'issuecomment-(\d+)',v)
if m: return int(m.group(1)) in IDS
return v.startswith('NEW') or bool(re.search(r'issues/\d+',v))
checks={
'header canonical time': lambda r: bool(re.match(r'^\d{4}-\d\d-\d\d \d\d:\d\d UTC$',r.get('tstr',''))),
'all 8 fields': lambda r: r['nfields']==8,
'TYPE exactly one enum value': lambda r: (r['TYPE'] or '') in T,
'STATUS starts with enum value': lambda r: bool(re.match(r'(PASS|FAIL|UNVERIFIED|IN-PROGRESS)\b',r['STATUS'] or '')),
'HEAD sha or NOT-APPLICABLE': lambda r: bool(r['HEAD']) and (r['HEAD'].startswith('NOT-APPLICABLE') or bool(re.search(r'\b[0-9a-f]{7,40}\b',r['HEAD']))),
'IN-REPLY-TO NEW/issue/resolving comment': lambda r: irt_ok(r['IN-REPLY-TO']),
}
for k,f in checks.items(): print(sum(f(r) for r in R),'/',len(R),k)
allok=[r for r in R if all(f(r) for f in checks.values())]
print(len(allok),'/',len(R),'pass every check above')
for n in [6,7,8,9,10]: print(' issue',n,sum(r['issue']==n for r in allok),'/',sum(r['issue']==n for r in R))
print('\n######## drift plausibility (declared minute vs GitHub second)')
v=[(r['drift_min'],r) for r in R if r.get('drift_min') is not None]
print(sum(x<=0 for x,_ in v),'<=0 : consistent with a clock read (floored to the minute) before posting')
print(sum(0<x<1 for x,_ in v),'(0,1) : consistent only with rounding up inside the minute')
print(sum(x>=1 for x,_ in v),'>=1 : declared time later than GitHub received the comment; not read from a clock before posting')
print(' of which HARNESS',sum(x>=1 and r['from'].startswith('HARNESS') for x,r in v),'of',sum(r['from'].startswith('HARNESS') for x,r in v))
print(sum(x<=-2 for x,_ in v),'<=-2 : envelope written 2+ min before posting')
print(sum(abs(x)<=2 for x,_ in v),'|drift|<=2')
print('\n######## labels')
print(len({r['from'] for r in R}),'distinct FROM labels over',len(R),'comments')
print(sum('TYPE:' in r.get('tstr','') or False for r in R) or sum(1 for n in [6,7,8,9,10] for c in json.load(open(f'c/i{n}.json')) if 'TYPE:' in c['body'].split('\n')[0]),'headers carrying TYPE on line 1')Build Link Graph
A Python command-line tool in Neural Link Between Agents that parses map (`parse_map`).
storageneural-link-between-agents / FIXES/NL-011/build_link_graph.py · lines 1–156 of 156 · Entry point · pattern norm_label (shared by 2 files)
- What it does
- It loads data. Defines 7 functions or classes, including cells, unesc, parse_map, norm_label, main. Uses libraries argparse, collections, datetime, 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).
- Inputs & outputs
- In: JSON file link-graph.json; command-line arguments. Out: JSON file.
- 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 cells step (`cells`), the unesc step (`unesc`) and the norm label helper (`norm_label`). Build `FIXES/NL-011/link-graph.json` from `FIXES/NL-011/KUIPER-MAP.md`, in the ventus-grid-engine genome graph format. It accepts `--map` and `--out`.
- 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-011 · Python CLI
- Uses
- argparse, collections, datetime, json, re
- Used by
- none found
- Produces
- cells, unesc, parse_map, norm_label, main
- Defines here
- cells, unesc, parse_map, norm_label, main, add, edge
- 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-011/build_link_graph.py:1-156 · blob 4cdee96c62967b5f183b5fd685796c2da1801bde · 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
"""Build FIXES/NL-011/link-graph.json from FIXES/NL-011/KUIPER-MAP.md, in the ventus-grid-engine genome graph format.
Format followed: ventus-grid-engine commit 96a800eb01825748936b5a193ce396a960f9302f, genome/engine-graph.json as written
by genome/build-graph.mjs: a JSON object {schema, label, generated_utc, note, focus_default, kind_labels, nodes,
node_ids, edges, edge_kind_counts}; nodes are {label, type, rag, reason, gh}; node_ids is the parallel list of stable
ids; edges are {from, to, type, evidence:{file, lines, method}} with from/to as indices into nodes. The spider
receiver (spider-sandbox.html, normaliseGenericGraph) reads exactly these fields: label, type, rag, reason, gh, and
edges by index or id, so this file can be listed in spider/manifest.json and drawn with no change to the page.
Nodes: the three issues, every agent label, every file key and every comment key of the map.
Edges: wrote (agent -> comment), on (comment -> issue), replied_to (comment -> the comment its IN-REPLY-TO names),
superseded (new -> old, from the map's supersedes column), admitted / refused (a controller REVIEW -> the hand-off it
judged), governs (a RULE -> the issues it binds).
Usage: python3 FIXES/NL-011/build_link_graph.py [--map FIXES/NL-011/KUIPER-MAP.md] [--out FIXES/NL-011/link-graph.json]
Written by FABLE-FIN-3, 2 Nov 2026.
"""
import argparse, collections, datetime, json, re
NL = 'https://github.com/Ventusltd/neural-link-between-agents'
KIND_LABELS = collections.OrderedDict([
('wrote', 'wrote'), ('on', 'posted on'), ('replied_to', 'replied to'), ('superseded', 'superseded'),
('admitted', 'admitted'), ('refused', 'refused'), ('governs', 'governs'),
])
def cells(line):
return [c.strip() for c in line.strip().strip('|').split('|')]
def unesc(s):
return s.replace('\\|', '|')
def parse_map(path):
text = open(path, encoding='utf-8').read().split('\n')
section = None
agents, files, comments = [], [], []
for ln in text:
if ln.startswith('## A.'): section = 'A'; continue
if ln.startswith('## B.'): section = 'B'; continue
m = re.match(r'## C(\d+)\.', ln)
if m: section = 'C' + m.group(1); continue
if ln.startswith('## Limits'): section = None; continue
if not ln.startswith('| ') or ln.startswith('|---') or ln.startswith('| key') or ln.startswith('| agent'): continue
c = [unesc(x) for x in cells(ln)]
if section == 'A' and len(c) >= 6:
agents.append(dict(label=c[0], model=c[1], n=int(c[2]), issues=c[3], first=c[4], last=c[5]))
elif section == 'B' and len(c) >= 6:
key = c[0].strip('`').replace('` ~', '').strip()
m2 = re.match(r'nl@([0-9a-f]+) (\S+):(\d+)', key)
if not m2: continue
files.append(dict(key=key, sha=m2.group(1), path=m2.group(2), line=int(m2.group(3)), when=c[1], who=c[2], typ=c[3], superseded=c[4], text=c[5]))
elif section and section.startswith('C') and len(c) >= 9:
key = c[0].strip('`')
m2 = re.match(r'#(\d+)/c(\d+)', key)
if not m2: continue
comments.append(dict(key=key, issue=int(m2.group(1)), id=int(m2.group(2)), when=c[1], frm=c[2], to=c[3], typ=c[4],
irt=c[5], superseded=c[6], relation=c[7], summary=c[8]))
return agents, files, comments
def norm_label(label):
s = re.sub(r'\s*\(.*?\)\s*', ' ', label).strip()
s = re.sub(r'\s+(lead|builder|tester|evidence|architect|consolidator|integrator).*$', '', s, flags=re.I)
s = re.sub(r'\s+(shell/evidence|layers|law-and-proof|bar|card|camera|touch|lines|seethrough|perf|type|robust|journey|index|persistence|decision log|resume kit|live reviewer|integration controller)$', '', s, flags=re.I)
return s.strip() or label
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--map', default='FIXES/NL-011/KUIPER-MAP.md')
ap.add_argument('--out', default='FIXES/NL-011/link-graph.json')
a = ap.parse_args()
agents, files, comments = parse_map(a.map)
nodes, node_ids, index = [], [], {}
def add(nid, label, typ, rag, reason, gh):
if nid in index: return index[nid]
index[nid] = len(nodes); nodes.append(dict(label=label, type=typ, rag=rag, reason=reason, gh=gh)); node_ids.append(nid); return index[nid]
titles = {9: 'NL-009: Kuiper Edition 5, mobile UI fixed by ten Fable agents, See Through as a button (Android)',
10: 'NL-010: the ten-step roadmap, GridAtlas lessons into the Kuiper (OS of the estate), See Through the star player',
11: 'NL-011: twelve Opus agents study and run the neural link; the link is the medium of exchange'}
for n in (9, 10, 11):
add(f'issue-{n}', f'issue #{n}', 'issue', 'green', titles[n], f'{NL}/issues/{n}')
for ag in agents:
add('agent:' + ag['label'], ag['label'], 'agent', 'green',
f"{ag['model']}; {ag['n']} comment(s) on {ag['issues']}; first {ag['first']}, last {ag['last']}", None)
comment_by_id = {c['id']: c for c in comments}
superseded_ids = set()
for c in comments:
m = re.match(r'#\d+/c(\d+)', c['superseded'])
if m: superseded_ids.add(int(m.group(1)))
for c in comments:
rag = 'green'
if c['id'] in superseded_ids: rag = 'grey'
elif c['relation'] == 'refused': rag = 'red'
elif c['typ'] == 'DECISION' and 'OWNER' in c['to'].upper(): rag = 'amber'
elif c['typ'] in ('REQUEST', 'BLOCKER'): rag = 'amber'
add(c['key'], f"{c['typ']} {c['key']}", c['typ'].lower(), rag,
f"{c['when']} · {c['frm']} → {c['to']} · {c['summary']}", f"{NL}/issues/{c['issue']}#issuecomment-{c['id']}")
for f in files:
rag = 'green'
if f['typ'] == 'DECISION' and ('OPEN' in f['text'].upper()[:10] or 'to OWNER' in f['who'] or 'NOT ADOPTED' in f['who']): rag = 'amber'
if re.search(r'superseded by', f['superseded'], re.I): rag = 'grey'
if f['typ'] == 'REVIEW': rag = 'red' if re.search(r'refus|fail', f['text'], re.I) else 'green'
add(f['key'], f"{f['typ']} {f['path']}:{f['line']}", f['typ'].lower(), rag,
f"{f['when']} · {f['who']} · {f['text']}", f'{NL}/blob/{f["sha"]}/{f["path"]}#L{f["line"]}')
edges = []
def edge(src, dst, typ, file, lines, method):
if src in index and dst in index:
edges.append(dict(**{'from': index[src], 'to': index[dst]}, type=typ, evidence=dict(file=file, lines=lines, method=method)))
for c in comments:
edge('agent:' + norm_label(c['frm']), c['key'], 'wrote', 'FIXES/NL-011/KUIPER-MAP.md', c['key'], 'FROM label of the envelope, normalised to the agent')
edge(c['key'], f"issue-{c['issue']}", 'on', 'FIXES/NL-011/KUIPER-MAP.md', c['key'], 'the issue the comment is on')
m = re.match(r'c(\d+)', c['irt'])
if m and int(m.group(1)) in comment_by_id:
t = comment_by_id[int(m.group(1))]
edge(c['key'], t['key'], 'replied_to', 'FIXES/NL-011/KUIPER-MAP.md', c['key'], 'IN-REPLY-TO field of the envelope')
if c['relation'] in ('admitted', 'refused'):
edge(c['key'], t['key'], c['relation'], 'FIXES/NL-011/KUIPER-MAP.md', c['key'], "REVIEW's STATUS line (admitted / refused)")
m = re.match(r'#\d+/c(\d+)', c['superseded'])
if m and int(m.group(1)) in comment_by_id:
edge(c['key'], comment_by_id[int(m.group(1))]['key'], 'superseded', 'FIXES/NL-011/KUIPER-MAP.md', c['key'], c['superseded'])
for f in files:
if f['typ'] == 'RULE':
targets = {'LINK-RULE.md': (10, 11), 'PROTOCOL.md': (9, 10, 11), 'AGENTS.md': (9, 10, 11),
'SESSIONS/202611012145-kuiper-edition-harness-notes.md': (9, 10), 'FIXES/NL-010/ROADMAP.md': (10,),
'FIXES/NL-010/OPUS-BRIEF.md': (10,)}.get(f['path'], ())
for n in targets:
edge(f['key'], f'issue-{n}', 'governs', 'FIXES/NL-011/KUIPER-MAP.md', f['key'], 'the rule binds the agents of that issue (LINK-RULE.md:1, BRIEF/OPUS-BRIEF channel lines)')
m = re.search(r'(D\d+[a-z]?)', f['superseded'])
if m and re.search(r'superseded by|resolved by', f['superseded'], re.I):
# D-row to D-row: find the row whose text starts with that D id
for g in files:
if g['path'].endswith('DECISIONS.md') and g['text'].startswith(m.group(1) + ' '):
edge(g['key'], f['key'], 'superseded', 'FIXES/NL-011/KUIPER-MAP.md', f['key'], f"DECISIONS.md status column: {f['superseded']}")
break
counts = collections.Counter(e['type'] for e in edges)
graph = collections.OrderedDict([
('schema', 'neural-link.kuiper-map.v1'),
('label', 'neural link between agents · agents, issues, rules and hand-offs keyed as the Kuiper keys lines'),
('generated_utc', datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds').replace('+00:00', 'Z')),
('note', 'Same shape as ventus-grid-engine genome/engine-graph.json (ventus-grid-engine@96a800eb01825748936b5a193ce396a960f9302f, '
'written by genome/build-graph.mjs): nodes {label,type,rag,reason,gh}, node_ids parallel to nodes, edges {from,to,type,evidence} '
'by index, kind_labels and edge_kind_counts. Read by spider-sandbox.html normaliseGenericGraph() unchanged. Built from '
'FIXES/NL-011/KUIPER-MAP.md by FIXES/NL-011/build_link_graph.py. rag: green in force, grey superseded, amber open or asked, red refused.'),
('focus_default', index.get('issue-10', 0)),
('kind_labels', KIND_LABELS),
('nodes', nodes), ('node_ids', node_ids), ('edges', edges),
('edge_kind_counts', dict(counts)),
])
json.dump(graph, open(a.out, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
print(f'wrote {a.out}: {len(nodes)} nodes, {len(edges)} edges, kinds {dict(counts)}')
if __name__ == '__main__':
main()Dryrun Workflow
A Python module in the scripts folder of Neural Link Between Agents that reads the Renewable Energy Planning Database (REPD) register.
automationneural-link-between-agents / FIXES/NL-012/M1/scripts/dryrun_workflow.py · lines 1–127 of 127 · Entry point
- What it does
- It loads the REPD register. Defines run_job, expr. Uses libraries os, shutil, subprocess, sys, pathlib. 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
- 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 runs job (`run_job`) and is built from the expr step (`expr`). Local dry run of `.github/workflows/repd-monthly.yml`: executes the YAML's own `run:` blocks in order.
- 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-012/M1/scripts · Python module
- Uses
- os, shutil, subprocess, sys, pathlib, yaml, re
- Used by
- none found
- Produces
- run_job
- Defines here
- run_job, expr
- 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/M1/scripts/dryrun_workflow.py:1-127 · blob 16f24de3eb6dc7279fd6211daf48957309808346 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""Local dry run of .github/workflows/repd-monthly.yml: executes the YAML's own `run:` blocks in order.
`uses:` steps are emulated (checkout = git clone of a local bare "origin" at main; upload/download
artifact = copy of the listed paths). Two substitutions only, both printed:
* the monthly.py call gets --api-file/--files-dir (offline: GOV.UK unreachable here);
* `git push` and `gh pr create` are replaced by stubs that record what would be pushed/opened.
Usage: dryrun_workflow.py <workflow.yml> <repo dir to serve as main> <api json> <files dir> <work dir> [release_folder]
"""
import os
import shutil
import subprocess
import sys
from pathlib import Path
import yaml
wf_path, repo, api, files, work = map(lambda p: Path(p).resolve(), sys.argv[1:6])
folder = sys.argv[6] if len(sys.argv) > 6 else ""
wf = yaml.safe_load(wf_path.read_text())
if work.exists():
shutil.rmtree(work)
work.mkdir(parents=True)
for p in ("/tmp/repd-monthly", "/tmp/repd-monthly-artifact"):
shutil.rmtree(p, ignore_errors=True)
origin = work / "origin.git"
subprocess.run(["git", "init", "-q", "-b", "main", str(work / "seed")], check=True)
shutil.copytree(repo, work / "seed", dirs_exist_ok=True)
git_id = ["-c", "user.name=dryrun", "-c", "user.email=dryrun@localhost"]
subprocess.run(["git", "-C", str(work / "seed"), "add", "-A"], check=True)
subprocess.run(["git", *git_id, "-C", str(work / "seed"), "commit", "-qm", "main"], check=True)
subprocess.run(["git", "clone", "-q", "--bare", str(work / "seed"), str(origin)], check=True)
stub = work / "stubbin"
stub.mkdir()
(stub / "gh").write_text('#!/bin/bash\necho "STUB gh $*"; for ((i=1;i<=$#;i++)); do [[ "${!i}" == --body-file ]] && j=$((i+1)) && cp "${!j}" "$DRYRUN_WORK/pr_body.md"; done; echo "$*" > "$DRYRUN_WORK/gh_args.txt"\n')
(stub / "gh").chmod(0o755)
def run_job(name, outputs_in, inputs):
job = wf["jobs"][name]
ws = work / f"ws-{name}"
subprocess.run(["git", "clone", "-q", "-b", "main", str(origin), str(ws)], check=True)
gh_out, summary = work / f"{name}.GITHUB_OUTPUT", work / f"{name}.STEP_SUMMARY"
gh_out.touch(); summary.touch()
step_outputs = {}
def expr(s):
if not isinstance(s, str):
return s
s = s.replace("${{ inputs.release_folder }}", inputs.get("release_folder", ""))
s = s.replace("${{ github.token }}", "dummy").replace("${{ github.run_number }}", "1")
for k, v in outputs_in.items():
s = s.replace("${{ needs.check.outputs.%s }}" % k, v)
for sid, outs in step_outputs.items():
for k, v in outs.items():
s = s.replace("${{ steps.%s.outputs.%s }}" % (sid, k), v)
return s
env = dict(os.environ, GITHUB_OUTPUT=str(gh_out), GITHUB_STEP_SUMMARY=str(summary), GITHUB_RUN_ID="0",
GITHUB_SERVER_URL="https://github.com", GITHUB_REPOSITORY="OWNER/REPO", RUNNER_TEMP=str(work / "tmp"),
DRYRUN_WORK=str(work), PATH=f"{stub}:{os.environ['PATH']}")
(work / "tmp").mkdir(exist_ok=True)
env.update({k: expr(str(v)) for k, v in (job.get("env") or {}).items()})
for step in job["steps"]:
sid, title = step.get("id"), step.get("name")
cond = step.get("if")
if cond:
c = cond
for sid2, outs in step_outputs.items():
for k, v in outs.items():
c = c.replace(f"steps.{sid2}.outputs.{k}", repr(v))
c = c.replace("always() && ", "").replace("==", "==").replace("!=", "!=")
import re
c = re.sub(r"steps\.\w+\.outputs\.\w+", "''", c)
if not eval(c): # noqa: S307 - our own YAML, simple comparisons only
print(f"[{name}] SKIP {title} (if: {cond})")
continue
if "uses" in step:
u = step["uses"]
if u.startswith("actions/upload-artifact"):
dest = work / "artifact"
for p in step["with"]["path"].split():
p = Path(p)
if p.exists():
rel = p.relative_to("/tmp/repd-monthly")
(dest / rel).parent.mkdir(parents=True, exist_ok=True)
(shutil.copytree if p.is_dir() else shutil.copy2)(p, dest / rel)
elif u.startswith("actions/download-artifact"):
shutil.copytree(work / "artifact", env["ART"])
print(f"[{name}] EMUL {title} ({u})")
continue
script = expr(step["run"])
script = script.replace('python -m automation.repd.monthly "${args[@]}"',
f'python -m automation.repd.monthly "${{args[@]}}" --api-file {api} --files-dir {files}')
script = script.replace('git push origin "HEAD:refs/heads/$BRANCH"',
'echo "WOULD PUSH $(git rev-parse HEAD) to refs/heads/$BRANCH"; '
'git diff --name-status HEAD~1 HEAD > "$DRYRUN_WORK/commit_files.txt"')
step_env = dict(env)
step_env.update({k: expr(str(v)) for k, v in (step.get("env") or {}).items()})
before = gh_out.read_text()
print(f"[{name}] RUN {title}")
proc = subprocess.run(["bash", "-e", "-c", script] if "set -" not in script else ["bash", "-c", script],
cwd=ws, env=step_env, capture_output=True, text=True)
tail = (proc.stdout + proc.stderr).strip().splitlines()[-6:]
for line in tail:
print(f" | {line[:220]}")
new = gh_out.read_text()[len(before):]
if sid:
step_outputs[sid] = dict(l.split("=", 1) for l in new.splitlines() if "=" in l)
print(f" outputs: {step_outputs[sid]}")
if proc.returncode != 0:
print(f"[{name}] FAILED step {title!r} exit {proc.returncode}")
return step_outputs, False
return step_outputs, True
outs, ok = run_job("check", {}, {"release_folder": folder})
job_out = {"status": outs.get("check", {}).get("status", ""), "release_id": outs.get("check", {}).get("release_id", ""),
"overall": outs.get("build", {}).get("overall", "")}
print(f"check job: {'green' if ok else 'RED'}; outputs {job_out}")
if ok and job_out["status"] == "new" and job_out["overall"] == "ok":
_, ok2 = run_job("open-pr", job_out, {})
print(f"open-pr job: {'green' if ok2 else 'RED'}")
else:
print("open-pr job: SKIPPED (if: status == 'new' && overall == 'ok')")