GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / claude / sessions/202609030120-cicd-spider

Pass and 4 more files

A Python module in the sessions folder of Claude that fetches spider state and ETYS normalized, using SHA-256.

666 lines of Python from claude, in 5 files. Topic: AI agents and coordination. Section 1614 of 2044.

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

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

In this section

  1. Gen Drift other · claude / sessions/202609030120-cicd-spider/gen-drift.py lines 1–52
  2. Pass storage · claude / sessions/202609030120-cicd-spider/pass.py lines 1–405
  3. Estate CI automation · claude / sessions/202609030422-handover/scripts/estate_ci.py lines 1–74
  4. Gen Drift other · claude / sessions/202609030422-handover/scripts/gen_drift.py lines 1–70
  5. Pn Walls ingest · claude / sessions/202609030422-handover/scripts/pn_walls.py lines 1–65

Gen Drift

A Python module in the sessions folder of Claude that splits monotonic-utc-generations failures by KIND and by SIGN.

otherclaude / sessions/202609030120-cicd-spider/gen-drift.py · lines 1–52 of 52 · version 2026-09-03 01:20 · Not reached from any entry point (candidate for review)

What it does
Uses libraries subprocess, re, datetime, sys, os. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'spider'): 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.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609030120-cicd-spider · Python module
Uses
subprocess, re, datetime, sys, os
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
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609030120-cicd-spider/gen-drift.py:1-52 · blob dd9e329d406dcc20b75051f50523441f1428bfae · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Split monotonic-utc-generations failures by KIND and by SIGN.

The rule asserts two things - ordering, and that a stamp sits within 15 minutes
of its real UTC commit time - and only one direction of the second is a defect.

A stamp BEHIND its commit can be innocent: an archive commit filing
sessions/202609021813-.../ is correctly titled with that session's generation.
A stamp AHEAD of its own commit cannot be innocent, because `date -u` does not
return the future. It means the generation was chosen when the work began and
the commit landed hours later - which is verbatim what the rule forbids:
"generations are read from date -u at commit time, never chosen."

Not a clock or timezone fault: BST-vs-UTC would give a constant 60-minute
offset, and the observed spread is 16 to 253 minutes. The remedy is a habit -
compute the stamp in the same command as the commit - not a tool.
"""
import subprocess, re, datetime, sys, os
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
GH = "C:/Users/vikra/OneDrive/Documents/GitHub"
LIMIT = int(os.environ.get('GEN_DRIFT_LIMIT', '400'))
repos = sys.argv[1:] or ['pipelinenews','gridatlas','globalgrid2050','claude','cvaa','data-grid-gb']
print('%-22s %8s %7s %7s %8s   %s' % ('repo','stamped','AHEAD','behind','worst+','verdict'))
for repo in repos:
    path = os.path.join(GH, repo)
    if not os.path.isdir(os.path.join(path, '.git')): continue
    out = subprocess.run(['git','-C',path,'log','-%d'%LIMIT,'--format=%H%x09%aI%x09%s'],
                         capture_output=True, text=True, errors='replace').stdout
    ahead, behind, tot = [], [], 0
    for line in out.splitlines():
        p = line.split('\t')
        if len(p) < 3: continue
        m = re.match(r'^(\d{12})', p[2])
        if not m: continue
        tot += 1
        try:
            gen = datetime.datetime.strptime(m.group(1), '%Y%m%d%H%M').replace(tzinfo=datetime.timezone.utc)
            commit = datetime.datetime.fromisoformat(p[1]).astimezone(datetime.timezone.utc)
        except Exception:
            continue
        d = (gen - commit).total_seconds() / 60
        if d > 15: ahead.append((d, p[0][:7], p[2][:60]))
        elif d < -15: behind.append((-d, p[0][:7], p[2][:60]))
    if not tot: continue
    worst = max(a[0] for a in ahead) if ahead else 0
    verdict = ('%d chosen in advance' % len(ahead)) if ahead else 'clean'
    print('%-22s %8d %7d %7d %8.0f   %s' % (repo, tot, len(ahead), len(behind), worst, verdict))
    if '-v' in os.environ.get('GEN_DRIFT_OPTS',''):
        for d, sha, subj in sorted(ahead, reverse=True)[:5]:
            print('      +%4.0f min  %s  %s' % (d, sha, subj))
print('\nAHEAD is the defect. behind may be an archive commit correctly titled with')
print('the generation of the session it files. Remedy: compute the stamp in the')
print('same command as the commit - date -u +%Y%m%d%H%M - never at task start.')

Pass

A Python module in the sessions folder of Claude that fetches spider state and ETYS normalized, using SHA-256.

storageclaude / sessions/202609030120-cicd-spider/pass.py · lines 1–405 of 405 · version 2026-09-03 01:20 · Entry point

What it does
It fetches spider state and etys normalized. Defines 9 functions or classes, including now, git, run, D, tree_state. Uses libraries json, os, subprocess, sys, datetime. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file spider-state.json; JSON file etys-2025.normalized.json; 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
It is built from the now step (`now`), the git step (`git`) and the run step (`run`). Cicd-spider pass driver.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
claude · sessions/202609030120-cicd-spider · Python module
Uses
json, os, subprocess, sys, datetime, collections, re, concurrent.futures
Used by
none found
Produces
now, git, run, D, tree_state, one_gate, api, ci
Defines here
now, git, run, D, tree_state, one_gate, one_cvaa, api, ci
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609030120-cicd-spider/pass.py:1-405 · blob 0e21f3f0d74963e963b12352ff26af79f6719e4e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""cicd-spider pass driver.

Usage:  python pass.py            run one full pass, update spider-state.json,
                                  print ONLY what changed
        python pass.py --quick    HEAD + gates only, skip cvaa and crosslink

Read-only on every repository except this directory. Never writes outside
sessions/202609030120-cicd-spider/. cvaa is always invoked with --no-write so
the run does not touch cvaa/vaccines/last-fired.json.

Context diet: this prints drift, not status. Silence means nothing moved.
"""
import json, os, subprocess, sys, datetime, collections, re, concurrent.futures as cf

GH   = r"C:\Users\vikra\OneDrive\Documents\GitHub"
HERE = os.path.dirname(os.path.abspath(__file__))
STATE= os.path.join(HERE, 'spider-state.json')
QUICK= '--quick' in sys.argv

def now():
    return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds').replace('+00:00','Z')

def git(d, *a):
    try:
        return subprocess.run(['git','-C',os.path.join(GH,d)]+list(a),
                              capture_output=True, text=True, timeout=60).stdout.strip()
    except Exception:
        return None

def run(cwd, argv, timeout=600):
    try:
        p = subprocess.run(argv, cwd=os.path.join(GH,cwd), capture_output=True,
                           text=True, timeout=timeout)
        return p.returncode, (p.stdout or '') + (p.stderr or '')
    except subprocess.TimeoutExpired:
        return 124, 'TIMEOUT'
    except Exception as e:
        return 125, str(e)

st = json.load(open(STATE))
drift = []
def D(sev, msg): drift.append(f'[{sev}] {msg}')

# ---------------------------------------------------------------- 1. HEADs
repos = sorted(st['heads'])
new_heads = {}
for d in repos:
    st_p = git(d,'status','--porcelain') or ''
    new_heads[d] = {
        "head": git(d,'rev-parse','HEAD'),
        "branch": git(d,'rev-parse','--abbrev-ref','HEAD'),
        "committed_at": git(d,'log','-1','--format=%cI'),
        "subject": (git(d,'log','-1','--format=%s') or '')[:110],
        "dirty_files": len([l for l in st_p.split('\n') if l.strip()]),
        "commit_count": st['heads'][d].get('commit_count'),
        "workflows": st['heads'][d].get('workflows'),
    }
    old = st['heads'][d]
    if old['head'] != new_heads[d]['head']:
        D('HEAD', f"{d} {old['head'][:7]} -> {new_heads[d]['head'][:7]} "
                  f"[{new_heads[d]['branch']}] {new_heads[d]['subject']}")

# ------------------------------------------------------------------ 2. gates
# The command string in spider-state.json is authoritative and already carries
# every required argument. RH2: a gate run without its arguments prints a usage
# string and looks like a failure. Never re-derive these.
GATE_ARGV = {
 "gridatlas__run-current":              ("gridatlas",   ['node','tools/proofs/run-current.mjs']),
 "datagridgb__verify-connection-points":("data-grid-gb",['python','derived/verify_connection_points.py']),
 "datagridgb__verify-phase0-acceptance":("data-grid-gb",['python','derived/verify_phase0_acceptance.py']),
 "datagridgb__verify-product":          ("data-grid-gb",['python','chatgpt/verify_product.py','chatgpt/derived/etys-2025.normalized.json']),
 "pipelinenews__render_proof":          ("pipelinenews",['node','tools/intelligence/render_proof.mjs','@RELEASE@']),
 "pipelinenews__sector_render_proof":   ("pipelinenews",['node','tools/intelligence/sector_render_proof.mjs','@RELEASE@']),
 "pipelinenews__surface_truth_proof":   ("pipelinenews",['node','tools/intelligence/surface_truth_proof.mjs','@RELEASE@']),
 "gdm__verify":                         ("grid-distance-maths",['node','test/verify.mjs']),
 "gdm__verify_nearest":                 ("grid-distance-maths",['node','test/verify_nearest.mjs']),
 "gdm__verify_parity":                  ("grid-distance-maths",['python','test/verify_parity.py']),
 "dgbe__price_decade_rollup":           ("data-gb-electricity",['python','derived/verify_price_decade_rollup.py']),
 "gg2050__verify_published_versions":   ("globalgrid2050",['python','scripts/verify_published_versions.py']),
}
# the newest release directory is the one the proofs must be pointed at
rel = sorted(x for x in os.listdir(os.path.join(GH,'pipelinenews','releases'))
             if re.match(r'^\d{12}-pipelinenews$', x))
RELEASE = rel[-1] if rel else None
if RELEASE and RELEASE != st.get('pipelinenews_release'):
    D('REL', f"pipelinenews release {st.get('pipelinenews_release')} -> {RELEASE}")

def tree_state(repo):
    """RH6. Three other agents are writing to these repositories continuously.
    A gate run against a dirty tree measures a half-written edit, not a repo,
    and reporting it as a failure spends attention a real failure then cannot
    get. Dirty is UNMEASURABLE, which is a third state, not a failure."""
    return git(repo,'rev-parse','HEAD'), len([l for l in (git(repo,'status','--porcelain') or '').split('\n') if l.strip()])

def one_gate(item):
    gid,(repo,argv) = item
    argv = [RELEASE if a=='@RELEASE@' else a for a in argv]
    if '@RELEASE@' in argv or (RELEASE is None and any('proof' in a for a in argv)):
        return gid, 'not-runnable-locally', 'no pipelinenews release directory'
    head0, dirty0 = tree_state(repo)
    if dirty0:
        return gid, 'unmeasurable-dirty-tree', f'{repo} has {dirty0} uncommitted path(s); another agent is mid-write'
    rc,out = run(repo, argv)
    # and re-check AFTER: a commit or an edit landing mid-run is equally fatal
    head1, dirty1 = tree_state(repo)
    if head1 != head0 or dirty1:
        return gid, 'unmeasurable-dirty-tree', f'{repo} moved during the run ({head0[:7]}->{head1[:7]}, dirty {dirty1})'
    fails = []
    seen = False
    for line in out.split('\n'):
        if line.strip() == 'FAILURES': seen = True; continue
        if seen and line.strip(): fails.append(line.strip())
    detail = ('; '.join(fails)[:190] if fails
              else ([l for l in out.strip().split('\n') if l.strip()][-1:] or [''])[0][:190])
    return gid, ('pass' if rc==0 else 'FAIL'), detail

gates = dict(st['gates'])
with cf.ThreadPoolExecutor(max_workers=8) as ex:
    for gid, state_now, detail in ex.map(one_gate, GATE_ARGV.items()):
        prev = gates.get(gid,{}).get('state')
        gates.setdefault(gid,{}).update(state=state_now, detail=detail, last_run=now())
        # An unmeasurable pass is not a transition in either direction. Never
        # report red or green across one; carry the previous verdict forward.
        if state_now == 'unmeasurable-dirty-tree':
            gates[gid]['state'] = prev or state_now
            gates[gid]['last_unmeasurable'] = now()
            continue
        if prev != state_now and prev != 'unmeasurable-dirty-tree':
            if state_now == 'FAIL':
                gates[gid]['first_seen'] = now()
                D('RED',   f"{gid}: {prev} -> FAIL :: {detail}")
            elif prev == 'FAIL':
                D('GREEN', f"{gid}: FAIL -> {state_now} :: {detail}")
            else:
                D('GATE',  f"{gid}: {prev} -> {state_now}")

# --------------------------------------------------------------- 3. cvaa
if not QUICK:
    # RH11: measure with the PUBLISHED cvaa, never the working copy beside it.
    # The local copy was two commits ahead of origin and carried an untracked
    # 28th vaccine, so three passes of estate numbers described a ruler nobody
    # else has. Refresh a clean clone each pass and record the commit measured.
    CV = os.environ.get('CVAA_CLEAN') or os.path.join(HERE, '.cvaa-clean')
    if not os.path.isdir(os.path.join(CV,'.git')):
        subprocess.run(['git','clone','-q','--no-tags',
                        'https://github.com/Ventusltd/cvaa.git', CV], timeout=600)
    else:
        subprocess.run(['git','-C',CV,'fetch','-q','--no-tags','origin','main'], timeout=300)
        subprocess.run(['git','-C',CV,'reset','-q','--hard','origin/main'], timeout=120)
    cv_head = subprocess.run(['git','-C',CV,'rev-parse','HEAD'],
                             capture_output=True, text=True).stdout.strip()
    # The RULER is the ACTIVE VACCINE SET, not the commit. cvaa can be committed
    # to for a hundred reasons that leave every rule identical -- a workflow fix,
    # a README -- and firing on the SHA would cry ruler-change at each of them,
    # which is the same noise in the other direction. Compare the set: active
    # vaccine slugs and their content hashes, superseded ones excluded.
    import hashlib, glob as _glob
    ruler = {}
    for f in sorted(_glob.glob(os.path.join(CV,'vaccines','*.md'))):
        body = open(f,'rb').read()
        text = body.decode('utf-8','replace').replace(chr(13)+chr(10), chr(10))
        if re.search(r'^superseded_by:', text, re.M): continue
        ruler[os.path.basename(f)] = hashlib.sha256(text.encode()).hexdigest()[:12]
    prev_ruler = st['cvaa'].get('ruler') or {}
    if prev_ruler and ruler != prev_ruler:
        added   = sorted(set(ruler) - set(prev_ruler))
        removed = sorted(set(prev_ruler) - set(ruler))
        changed = sorted(k for k in set(ruler) & set(prev_ruler) if ruler[k] != prev_ruler[k])
        D('CVAA-RULER', f"active vaccine set changed ({len(prev_ruler)} -> {len(ruler)}): "
                        f"+{added} -{removed} ~{changed}; a findings delta this pass may be the ruler, not the repo")
    elif cv_head != st['cvaa'].get('measured_with_commit'):
        D('CVAA-COMMIT', f"cvaa published HEAD -> {cv_head[:7]}, active vaccine set UNCHANGED "
                         f"({len(ruler)} rules); any findings delta is real")
    st['cvaa']['ruler'] = ruler
    st['cvaa']['active_vaccines'] = len(ruler)
    st['cvaa']['measured_with_commit'] = cv_head

    def one_cvaa(d):
        # RH16. The dirty-tree guard was applied to gates and not to cvaa, which
        # reads the same working copies. A findings delta measured while an agent
        # is mid-write is the same false signal RH6 was written to stop.
        h0, dirty0 = tree_state(d)
        if dirty0:
            return d, None, f'{dirty0} uncommitted path(s)'
        rc,out = run('.', ['node', os.path.join(CV,'inoculate.mjs'),
                           os.path.join(GH,d), '--json','--no-write'], timeout=900)
        h1, dirty1 = tree_state(d)
        if h1 != h0 or dirty1:
            return d, None, f'tree moved during the run ({h0[:7]}->{h1[:7]}, dirty {dirty1})'
        for line in out.split('\n'):
            line = line.strip()
            if line.startswith('{') and '"schema"' in line:
                try: return d, json.loads(line), None
                except Exception: pass
        return d, None, 'no JSON record'
    cv = {}
    unmeasurable = []
    with cf.ThreadPoolExecutor(max_workers=6) as ex:
        for d,obj,why in ex.map(one_cvaa, repos):
            if obj is None:
                if why and ('uncommitted' in why or 'moved during' in why):
                    unmeasurable.append(d)          # not a finding, not a change
                else:
                    D('RUNNER', f"cvaa produced no JSON for {d} ({why}) - suspect the runner, not the repo")
                continue
            cv[d] = obj
    if unmeasurable:
        D('CVAA-SKIP', f"{len(unmeasurable)} repo(s) mid-write, not measured: {', '.join(sorted(unmeasurable))}")
    prev = st['cvaa']['per_repo']
    for d,obj in cv.items():
        if d in prev and prev[d]['findings'] != obj['findings']:
            D('CVAA', f"{d} findings {prev[d]['findings']} -> {obj['findings']}")
    # RH18. Comparing incidence COUNTS across passes is only valid when the
    # denominator is the same, and RH16 made it vary: three repos mid-write meant
    # "14 -> 11 of 15" and every one of those was a repo that was not looked at.
    # A wrong denominator is worse than a wrong finding (RH11), and I shipped one
    # as a side effect of fixing something else. So: diff PER REPOSITORY, over
    # the repos measured in BOTH passes, and name the repo rather than a count.
    # RH19. git status compares through .gitattributes normalisation, so a tree
    # can be git-clean while the bytes on disk are CRLF and the blob is LF. Any
    # verdict that depends on file BYTES is then wrong in both directions: the
    # working copy invented pointer-verifies on gridatlas and concealed
    # on-ledger-commits. Vaccines that hash or byte-compare are therefore not
    # reportable from a workspace with CRLF drift; they are dropped, and the
    # count of what was dropped is stated rather than silently omitted.
    BYTE_SENSITIVE = {'pointer-verifies', 'disk-is-not-what-ships',
                      'registry-integrity', 'attestation-freshness'}
    crlf = {}
    for d in cv:
        out = git(d, 'ls-files', '--eol') or ''
        crlf[d] = sum(1 for l in out.splitlines() if 'w/crlf' in l or 'w/mixed' in l)
    st['cvaa']['crlf_drift'] = crlf
    # RH25. cvaa now emits THREE states: immune, fail, skipped. A skip is a rule
    # declining to decide for want of evidence - it is not a failure, and
    # counting it as one produced two false VACCINE-RED lines the moment
    # rollback-exercised was rewritten to skip where no drills file exists.
    # I built exactly this distinction for my own gate results in RH6 and RH16
    # (unmeasurable is a third state, never a fail) and then failed to honour
    # the identical concept in someone else's output.
    now_fail = {d: sorted(r['vaccine'] for r in o['results'] if r['state'] == 'fail'
                          and not (crlf.get(d) and r['vaccine'] in BYTE_SENSITIVE))
                for d, o in cv.items()}
    # A skip is not a pass either: surface it, separately, without alarm.
    now_skip = {d: sorted(r['vaccine'] for r in o['results'] if r['state'] == 'skipped')
                for d, o in cv.items()}
    was_skip = st['cvaa'].get('skipped') or {}
    for d in sorted(set(now_skip) & set(was_skip)):
        for v in sorted(set(now_skip[d]) - set(was_skip[d])):
            D('VACCINE-SKIP', f'{d}: {v} now declines to decide - a skip is not a pass')
    st['cvaa']['skipped'] = dict(was_skip, **now_skip)
    suppressed = sorted(d for d in cv if crlf.get(d) and
                        any(r['vaccine'] in BYTE_SENSITIVE and r['state'] == 'fail'
                            for r in cv[d]['results']))
    if suppressed:
        D('BYTE-UNSAFE', f"{len(suppressed)} repo(s) have CRLF drift, so byte-dependent "
                         f"vaccines are not reportable from the workspace: {', '.join(suppressed)}"
                         " - re-measure in a clean clone")
    was_fail = st['cvaa'].get('not_immune') or {}
    comparable = sorted(set(now_fail) & set(was_fail))
    for d in comparable:
        gained = sorted(set(now_fail[d]) - set(was_fail[d]))
        lost   = sorted(set(was_fail[d]) - set(now_fail[d]))
        for v in gained: D('VACCINE-RED',   f'{d} now fails {v}')
        for v in lost:   D('VACCINE-GREEN', f'{d} no longer fails {v}')
    st['cvaa']['not_immune'] = dict(was_fail, **now_fail)
    # RH27/RH28. Two rules, both learned the hard way, both mechanical now.
    # (a) Every count carries its CONTROL: how many repositories the rule is
    #     quiet on. A rule that fires everywhere is a broken instrument, not a
    #     finding - that is what caught disk-is-not-what-ships at 18/18. A rule
    #     that is quiet somewhere has demonstrated it can discriminate.
    # (b) fail, warn and skip are counted SEPARATELY. Counting "not immune"
    #     merged pinned-actions (level: warning, an accepted dated allowance)
    #     with real failures, and put it top of a "worst failures" table all
    #     night when it fails nowhere.
    tally = collections.defaultdict(lambda: collections.Counter())
    for d, o in cv.items():
        for r in o['results']:
            tally[r['vaccine']][r['state']] += 1
    st['cvaa']['by_state'] = {v: dict(c) for v, c in sorted(tally.items())}
    st['cvaa']['incidence'] = {v: c.get('fail', 0) for v, c in tally.items() if c.get('fail')}
    st['cvaa']['incidence_denominator'] = len(cv)
    st['cvaa']['incidence_counts'] = 'state == fail only; warnings and skips are in by_state'
    for v, c in sorted(tally.items()):
        if c.get('fail') and not c.get('immune'):
            D('NO-CONTROL', f"{v} fails on all {c['fail']} repositories measured and is quiet on "
                            "none - suspect the rule before the estate")
    if len(comparable) != len(now_fail):
        D('VACCINE-BASE', f'{len(now_fail)-len(comparable)} repo(s) had no prior vaccine '
                          'record; baselined silently, not reported as change')
    # carry forward the last good figures for anything not measured this pass,
    # so an unmeasured repository can never read as a change next pass either
    carried = {k:v for k,v in prev.items() if k not in cv}
    st['cvaa']['per_repo'] = dict(carried,
        **{k:{"status":v['status'],"findings":v['findings']} for k,v in cv.items()})

    for d,obj in cv.items():
        wf = obj['context']['workflows']
        if st['heads'][d].get('workflows') not in (None, wf):
            D('COUNT', f"{d} workflow files {st['heads'][d]['workflows']} -> {wf}")
        new_heads[d]['workflows'] = wf
        new_heads[d]['commit_count'] = obj['context']['commit_count']

# ------------------------------------------------- 4. CI state, from the API
# RH6 again: the Actions API reports what CI ran against a COMMIT. It is the
# only CI signal here that a live working tree cannot corrupt. 7 calls a pass
# against a 60/hour unauthenticated budget.
import urllib.request
CI_REPOS = ['gridatlas','pipelinenews','globalgrid2050','data-grid-gb','cvaa','companies','data-gridatlas']
GH_API = os.path.join(GH, 'claude', 'scripts', 'gh-api.sh')
def api(path):
    """RH24. The 60/hour ceiling was never real. Every push here authenticates,
    so the credential helper holds a token; gh-api.sh wraps it and gives 5000/h.
    I believed CLAUDE.md instead of measuring, then built a budget floor around
    the false limit, which made every later pass print a confirmation of it."""
    p = subprocess.run(['bash', GH_API, path], capture_output=True, text=True, timeout=90)
    return json.loads(p.stdout)

def ci(repo):
    try:
        d = api(f'repos/Ventusltd/{repo}/actions/runs?per_page=25')
    except Exception as e:
        return repo, None, str(e)[:80]
    # RH20. A CI failure on a feature branch is another agent's work in
    # progress, not estate drift. gridatlas b67d0a0 on
    # codex/202609030251-grid-data-v9-89 failed its first run and I was about to
    # report it - the same mistake as the pass-2 dirty-tree red, one level out.
    # Only the default branch describes the estate.
    latest = {}
    for x in d.get('workflow_runs',[]):
        if x.get('head_branch') != 'main': continue
        latest.setdefault(x.get('path') or x['name'], x)
    return repo, {n:{'conclusion':x['conclusion'],'head_sha':x['head_sha'][:7],
                     'at':x['updated_at']} for n,x in latest.items()}, None
# RH15. The 60/hour unauthenticated budget is SHARED - by four agents on this
# machine and by the estate's own gates, which come from the same IP. At 02:02Z
# globalgrid2050/scripts/verify_published_versions.py printed
#   skipped: pipelinenews lineage head: HTTP Error 403: rate limit exceeded
# because the budget was at 0/60. A standing observer that exhausts the budget
# blinds the gates it is observing, and the gate SKIPS rather than failing -
# and a skip is not a pass. So: check the free rate_limit endpoint first, leave
# a floor for everyone else, and sample the busy repos more often than the
# quiet ones.
# RH24: the budget floor is withdrawn. It rationed against a 60/hour limit that
# does not bind, and printing "API-BUDGET 24/60 left" every pass made the false
# constraint look confirmed. Sample every repo every pass; 5000/hour is not a
# constraint at this cadence.
try:
    remaining = api('rate_limit')['resources']['core']['remaining']
except Exception:
    remaining = None
sample = list(CI_REPOS)
if remaining is not None and remaining < 100:
    D('API-BUDGET', f'{remaining} authenticated calls left, which should not happen; '
                    'check scripts/gh-api.sh before trusting this pass')
st['github_api']= {'authenticated': True, 'via': 'claude/scripts/gh-api.sh',
                   'limit': 5000, 'remaining_at_pass': remaining,
                   'ci_repos_sampled': sample,
                   'logs_readable': True,
                   'note': 'RH24 - the 60/hour unauthenticated ceiling in CLAUDE.md is not '
                           'binding and /actions/runs/<id>/logs returns 200. Use ci-log.sh.'}

prev_ci = st.get('ci', {})
new_ci = dict(prev_ci)
with cf.ThreadPoolExecutor(max_workers=3) as ex:
    for repo, res, err in ex.map(ci, sample):
        if res is None:
            D('API', f'{repo} actions API unreachable: {err}')
            new_ci[repo] = prev_ci.get(repo, {})
            continue
        new_ci[repo] = res
        old = prev_ci.get(repo, {})
        # RH10: a first observation is a baseline, not a transition. Without
        # this, every long-standing failure is announced as though it just broke.
        if not old:
            n = sum(1 for c in res.values() if c['conclusion'] == 'failure')
            if n: D('CI-BASE', f'{repo}: {n} workflow(s) already failing at first observation')
            continue
        for wf, cur in res.items():
            was = old.get(wf, {}).get('conclusion')
            if was == cur['conclusion']: continue
            if cur['conclusion'] == 'failure':
                D('CI-RED',   f"{repo} :: {wf[:60]} -> failure @{cur['head_sha']} {cur['at']}")
            elif was == 'failure' and cur['conclusion'] == 'success':
                D('CI-GREEN', f"{repo} :: {wf[:60]} failure -> success @{cur['head_sha']}")
st['ci'] = new_ci
st['github_api']['calls_used_last_pass'] = len(sample) + 1

# ------------------------------------------------------------- 5. write out
st['heads'] = new_heads
st['gates'] = gates
st['pass']  = st['pass'] + 1
st['pass_completed_utc'] = now()
st['pipelinenews_release'] = RELEASE
st['last_pass_drift'] = drift
tmp = STATE + '.tmp'
json.dump(st, open(tmp,'w',encoding='utf-8',newline=chr(10)), indent=1)
os.replace(tmp, STATE)

print(f"pass {st['pass']}  {now()}  {'quick' if QUICK else 'full'}")
if drift:
    print(f"{len(drift)} drift item(s):")
    for x in drift: print('  '+x)
else:
    print('no drift')

Estate CI

A Python module in the scripts folder of Claude using data from GitHub API. It is built from the API step (`api`).

automationclaude / sessions/202609030422-handover/scripts/estate_ci.py · lines 1–74 of 74 · version 2026-09-03 04:22 · Not reached from any entry point (candidate for review)

What it does
It fetches data. Defines api. Uses libraries json, subprocess, sys, urllib.request. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: data source: GitHub API.
What it achieves
Estate CI status, from the API, filtered to each repo's own default branch.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609030422-handover/scripts · Python module
Uses
json, subprocess, sys, urllib.request
Used by
none found
Produces
api
Defines here
api
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609030422-handover/scripts/estate_ci.py:1-74 · blob 16b7b1c6579ae8cbec65b04cd7215cfeaab5c2c4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Estate CI status, from the API, filtered to each repo's own default branch.

Only possible cheaply since the 60/hour ceiling turned out to be fictional. Enumerates repos
from the API rather than from disk, because a disk scan has under-counted this estate twice.
"""
import json
import subprocess
import sys
import urllib.request

token = subprocess.run(
    ['git', 'credential', 'fill'], input='protocol=https\nhost=github.com\n\n',
    capture_output=True, text=True).stdout
token = [l[9:] for l in token.splitlines() if l.startswith('password=')]
token = token[0] if token else None
if not token:
    print('no credential'); sys.exit(1)


def api(path):
    req = urllib.request.Request('https://api.github.com/' + path)
    req.add_header('Authorization', 'Bearer ' + token)
    req.add_header('Accept', 'application/vnd.github+json')
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.load(r)


repos = []
page = 1
while True:
    batch = api('user/repos?per_page=100&affiliation=owner&page=%d' % page)
    if not batch:
        break
    repos.extend(batch)
    page += 1

print('repositories on the account: %d' % len(repos))
print()
print('%-46s %-8s %-10s %-9s %s' % ('repo', 'branch', 'CI', 'age', 'last run'))
print('-' * 104)

green = red = none = 0
reds = []
for r in sorted(repos, key=lambda x: x['name']):
    name = r['name']
    branch = r.get('default_branch') or 'main'
    try:
        runs = api('repos/%s/actions/runs?branch=%s&per_page=1' % (r['full_name'], branch))
    except Exception as exc:
        print('%-46s %-8s %-10s %-9s %s' % (name[:46], branch[:8], 'ERR', '-', str(exc)[:28]))
        continue
    wr = runs.get('workflow_runs') or []
    if not wr:
        none += 1
        print('%-46s %-8s %-10s %-9s %s' % (name[:46], branch[:8], '-', '-', 'no workflow runs'))
        continue
    run = wr[0]
    concl = run.get('conclusion') or run.get('status') or '?'
    if concl == 'success':
        green += 1
    elif concl in ('failure', 'startup_failure', 'timed_out'):
        red += 1
        reds.append((name, run.get('name', '')[:40], run.get('created_at', '')))
    print('%-46s %-8s %-10s %-9s %s' % (
        name[:46], branch[:8], concl[:10], run.get('created_at', '')[5:16].replace('T', ' '),
        (run.get('name') or '')[:34]))

print()
print('green %d   red %d   no runs %d   total %d' % (green, red, none, len(repos)))
if reds:
    print()
    print('RED on default branch:')
    for n, w, t in reds:
        print('  %-40s %-40s %s' % (n, w, t))

Gen Drift

A Python module in the scripts folder of Claude that converts to min (`to_min`).

otherclaude / sessions/202609030422-handover/scripts/gen_drift.py · lines 1–70 of 70 · version 2026-09-03 04:22 · Not reached from any entry point (candidate for review)

What it does
Defines to_min. Uses libraries re, subprocess, sys, datetime, pathlib. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): 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
Classify generation-stamp drift in a repo: genuine error vs session-archive convention.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609030422-handover/scripts · Python module
Uses
re, subprocess, sys, datetime, pathlib
Used by
none found
Produces
to_min
Defines here
to_min
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609030422-handover/scripts/gen_drift.py:1-70 · blob f32e60fc9b7e9924e072bf7af120fe384e9e1844 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Classify generation-stamp drift in a repo: genuine error vs session-archive convention.

monotonic-utc-generations flags any commit whose subject generation is more than 15 minutes from
its real UTC commit time. In an ARCHIVE repository that is ambiguous: a commit that files
sessions/202609021813-.../ is correctly titled with the session's generation, not the moment the
file landed. Those are a naming convention, not a clock error. A stamp AHEAD of its own commit is
never a convention - date -u cannot return the future.
"""
import re
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

repo = Path(sys.argv[1])
sessions = set()
sdir = repo / 'sessions'
if sdir.is_dir():
    for d in sdir.iterdir():
        m = re.match(r'^(\d{12})', d.name)
        if m:
            sessions.add(m.group(1))

log = subprocess.run(['git', 'log', '--format=%H|%aI|%s', '-400'], cwd=repo,
                     capture_output=True, text=True).stdout

def to_min(stamp):
    return datetime(int(stamp[0:4]), int(stamp[4:6]), int(stamp[6:8]),
                    int(stamp[8:10]), int(stamp[10:12]), tzinfo=timezone.utc).timestamp() / 60

ahead, archive, behind, ok, unstamped = [], [], [], 0, 0
for line in log.splitlines():
    parts = line.split('|', 2)
    if len(parts) < 3:
        continue
    sha, when, subj = parts
    m = re.match(r'^(\d{12})', subj)
    if not m:
        unstamped += 1
        continue
    gen = m.group(1)
    utc = datetime.fromisoformat(when).astimezone(timezone.utc)
    delta = to_min(gen) - utc.timestamp() / 60      # positive = stamp is in the FUTURE
    if abs(delta) <= 15:
        ok += 1
    elif delta > 15:
        ahead.append((sha[:7], gen, int(delta), subj[:58]))
    elif gen in sessions:
        archive.append((sha[:7], gen, int(-delta), subj[:58]))
    else:
        behind.append((sha[:7], gen, int(-delta), subj[:58]))

print('repo: %s   commits examined: %d' % (repo.name, ok + len(ahead) + len(archive) + len(behind)))
print('  within 15 min (clean):            %d' % ok)
print('  stamp AHEAD of commit (ERROR):    %d   <- date -u cannot return the future' % len(ahead))
print('  behind, names a session dir:      %d   <- archive convention, not a clock error' % len(archive))
print('  behind, no session dir:           %d   <- unexplained' % len(behind))
print('  no generation stamp:              %d' % unstamped)

for label, rows in (('STAMPED AHEAD OF ITS OWN COMMIT', ahead),
                    ('BEHIND, UNEXPLAINED', behind),
                    ('BEHIND, FILES THAT SESSION', archive)):
    if not rows:
        continue
    print()
    print('%s:' % label)
    for sha, gen, d, subj in rows[:10]:
        print('  %s %s %5d min  %s' % (sha, gen, d, subj))
    if len(rows) > 10:
        print('  ... and %d more' % (len(rows) - 10))

Pn Walls

A Python module in the scripts folder of Claude that works with collecting require (`collecting_require`).

ingestclaude / sessions/202609030422-handover/scripts/pn_walls.py · lines 1–65 of 65 · version 2026-09-03 04:22 · Not reached from any entry point (candidate for review)

What it does
It loads data. Defines collecting_require. Uses libraries importlib.util, sys, traceback, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file release-manifest.json; command-line arguments.
What it achieves
Enumerate every gate that would fail for a PipelineNews release, not just the first.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609030422-handover/scripts · Python module
Uses
importlib.util, sys, traceback, pathlib
Used by
none found
Produces
collecting_require
Defines here
collecting_require
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609030422-handover/scripts/pn_walls.py:1-65 · blob 935e61c8e06193b754e61bcf5975d63e42bdfb7d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Enumerate every gate that would fail for a PipelineNews release, not just the first.

The deploy gate stops at the first failed require(). That answers "why is it red" but not the
question the architect actually needs: if the schema constant were updated, would it deploy, or
is there a second wall? This replaces require() with a collector so one run walks as far as the
code physically can, and reports every assertion that failed on the way.

It modifies nothing in the repository. Run against a throwaway clone.

    python pn_walls.py <clone-root> <release-id>
"""
import importlib.util
import sys
import traceback
from pathlib import Path

root = Path(sys.argv[1]).resolve()
release_id = sys.argv[2]

mod_path = root / 'atman' / '202608262014-build-pages.py'
spec = importlib.util.spec_from_file_location('buildpages', mod_path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)

failures = []
_original = mod.require


def collecting_require(condition, message):
    if not condition:
        failures.append(message)
    # deliberately does not raise: we want the walls behind this one


mod.require = collecting_require

print('release:', release_id)
print('schema in its release-manifest:',
      (root / 'releases' / release_id / 'release-manifest.json').exists()
      and __import__('json').loads((root / 'releases' / release_id / 'release-manifest.json').read_text())
      .get('schema'))
print()

crashed = None
try:
    mod.validate_timestamp_folder_release(root, release_id)
except Exception as exc:
    crashed = ''.join(traceback.format_exception_only(type(exc), exc)).strip()

if failures:
    print('ASSERTIONS THAT FAILED (in order encountered):')
    for i, f in enumerate(failures, 1):
        print('  %2d. %s' % (i, f))
else:
    print('NO ASSERTION FAILED once the schema check was made non-fatal.')

if crashed:
    print()
    print('execution could not continue past that point:')
    print('  ' + crashed)
    print('  (a crash here usually means an earlier assertion guarded this code,')
    print('   so treat everything after it as unmeasured rather than passing)')
else:
    print()
    print('the validator ran to completion.')