GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore

Ship

A Python command-line tool in the explore folder of Cosmic that reads build graph and extras, using SHA-256. It summarises changes (`summarise_changes`), runs cmd (`run_cmd`) and picks manifest (`pick_manifest`).

557 lines of Python from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1136 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. Ship storage · cosmic / tools/explore/ship.py lines 1–557

Ship

A Python command-line tool in the explore folder of Cosmic that reads build graph and extras, using SHA-256. It summarises changes (`summarise_changes`), runs cmd (`run_cmd`) and picks manifest (`pick_manifest`).

storagecosmic / tools/explore/ship.py · lines 1–557 of 557 · Entry point · pattern delta (shared by 9 files)

What it does
It loads build graph and extras. Defines 29 functions or classes, including now, warn, snapshot, summarise_changes, script_flags. Uses libraries argparse, datetime, hashlib, json, os. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file build_graph.json; JSON file extras.json; DuckDB queries; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 1 file: Test Ship (cosmic).
What it achieves
Explore Code ship: a local, fail-safe wrapper that runs the Explore Code pipeline in deploy order. It accepts `--src`, `--out` and `--base`.
Why it matters
Checked by Test Ship.
Application
cosmic · tools/explore · Python CLI
Uses
Build (script call), Visualise (script call), Extras (script call), argparse, datetime, hashlib, json, os, shutil, subprocess, sys
Used by
imported by Test Ship (import)
Produces
now, warn, snapshot, summarise_changes, script_flags, Step, run_cmd, measure, tail, skip, plan, ship
Defines here
now, warn, snapshot, summarise_changes, script_flags, Step, __init__, run_cmd, measure, tail, skip, plan, ship, step_clean, pick_manifest, step_build, step_duckdb, step_visualise, step_extras, step_verify, budget_check, duplicate_groups, tree_size, size_budget, budget_lines, delta, write_report, write_json, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/ship.py:1-557 · blob b5cc3f21d19ab0a73a99cc22199b1e7f42344311 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""Explore Code ship: a local, fail-safe wrapper that runs the Explore Code pipeline in deploy order.

    python tools/explore/ship.py --src clones --out _site/explore-code \\
        [--base URL] [--kuiper-tools kuiper/tools] [--report SHIP-REPORT.md] [--duckdb-vendor DIR]

Steps, in order (each runs as a subprocess with its own timeout; its log goes to <report dir>/logs/<step>.log):

  clean      tools/explore/clean/apply.py      optional  writes a clean manifest from the proposals, read
                                                         against the previous build_graph.json (if any)
  build      tools/explore/build.py            REQUIRED  gets --clean-manifest only when build.py supports it
                                                         and a manifest exists (clean output, else
                                                         /tmp/vk/clean/manifest.json, else --clean-manifest)
  duckdb     (in process)                      optional  copies self-hosted DuckDB-WASM files from
                                                         --duckdb-vendor into <out>/vendor/duckdb/
  visualise  tools/explore/visualise.py        optional
  extras     tools/explore/extras.py           optional  (CONDUIT-72's CLI, with --link-index); extras.py owns
                                                         the order of every extra, including theme inject,
                                                         periodic feed, See Through, Laws, Pilot and Stories,
                                                         so ship.py does not run those itself
  verify     tools/explore/verify/vaccines.py  optional  findings are warnings, never a stop

Only build.py failing (non-zero exit, timeout, or no build_graph.json/index.html) stops the run and makes
ship.py exit 1. A missing script, missing input, crash or timeout in any optional step logs a warning
(plus a GitHub "::warning::" line under Actions) and the step is skipped. ship.py always writes the report
(--report, default ./SHIP-REPORT.md, plus a .json twin) listing each step, its duration, its outputs and what
was skipped and why.

Size budget (table at the top of the report): artifact size and file count against the last build (read from
the previous report's .json twin), a warning for any extra adding more than 15 MB or 500 files (per step, and
per top-level folder extras.py adds), and every group of files >= 50 KB whose bytes occur more than once in
the artifact (sha256 of every candidate file). Budget findings are warnings, never a stop.
"""
import argparse
import datetime
import hashlib
import json
import os
import shutil
import subprocess
import sys
import time

GENERATOR_VERSION = 'ship-2'
HERE = os.path.dirname(os.path.abspath(__file__))
PY = sys.executable or 'python3'
VK_MANIFEST = '/tmp/vk/clean/manifest.json'
BUDGET_STEP_MB = 15.0      # an extra (step, or one top-level folder an extra adds) may add at most this ...
BUDGET_STEP_FILES = 500    # ... and at most this many files
DUP_MIN_BYTES = 50 * 1024  # duplicate-content groups are listed for files at least this big

OK, WARN, SKIP, FAIL = 'ok', 'warning', 'skipped', 'FAILED'


def now():
    return datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')


def warn(msg):
    print('ship: warning: ' + msg, file=sys.stderr, flush=True)
    if os.environ.get('GITHUB_ACTIONS'):
        print('::warning::ship: ' + msg.replace('\n', ' '), flush=True)


def snapshot(root):
    """{relpath: (mtime_ns, size)} for every file under root (empty if root is missing)."""
    out = {}
    if not os.path.isdir(root):
        return out
    for dp, dns, fns in os.walk(root):
        dns[:] = [d for d in dns if d not in ('.extras-staging', '__pycache__')]
        for f in fns:
            p = os.path.join(dp, f)
            try:
                st = os.stat(p)
            except OSError:
                continue
            out[os.path.relpath(p, root)] = (st.st_mtime_ns, st.st_size)
    return out


def summarise_changes(before, after, limit=6):
    """Short text: N files written/changed, grouped by top-level entry."""
    changed = [p for p, v in after.items() if before.get(p) != v]
    if not changed:
        return 'no files written', 0
    groups = {}
    for p in changed:
        top = p.split(os.sep, 1)[0] + ('/' if os.sep in p else '')
        groups[top] = groups.get(top, 0) + 1
    tops = sorted(groups.items(), key=lambda kv: (-kv[1], kv[0]))
    parts = ['%s (%d)' % (k, n) if n > 1 else k for k, n in tops[:limit]]
    if len(tops) > limit:
        parts.append('+%d more' % (len(tops) - limit))
    return '%d files: %s' % (len(changed), ', '.join(parts)), len(changed)


def script_flags(script):
    """Flags a script's --help lists ('' if it cannot be asked). Cheap: argparse exits before work."""
    try:
        r = subprocess.run([PY, script, '--help'], capture_output=True, text=True, timeout=60)
        return r.stdout + r.stderr
    except Exception:
        return ''


class Step:
    def __init__(self, name, script, required=False, timeout=600, note=''):
        self.name, self.script, self.required, self.timeout, self.note = name, script, required, timeout, note
        self.status, self.reason, self.duration, self.outputs, self.nfiles, self.cmd, self.rc = (
            None, '', 0.0, '', 0, [], None)
        self.bytes_added, self.files_added, self.groups, self.budget = 0, 0, {}, []


def run_cmd(step, cmd, log_dir, out_root, cwd=None, env=None):
    """Run one step's command with its timeout. Sets step status; never raises."""
    step.cmd = cmd
    os.makedirs(log_dir, exist_ok=True)
    log = os.path.join(log_dir, step.name + '.log')
    before = snapshot(out_root)
    t0 = time.time()
    try:
        with open(log, 'w') as fh:
            fh.write('$ %s\n' % ' '.join(cmd))
            fh.flush()
            r = subprocess.run(cmd, stdout=fh, stderr=subprocess.STDOUT, timeout=step.timeout, cwd=cwd,
                               env=env)
        step.rc = r.returncode
        if r.returncode == 0:
            step.status = OK
        else:
            step.status = FAIL if step.required else WARN
            step.reason = 'exit %d (log: %s): %s' % (r.returncode, log, tail(log))
    except subprocess.TimeoutExpired:
        step.status = FAIL if step.required else WARN
        step.reason = 'timed out after %ds (log: %s)' % (step.timeout, log)
    except Exception as e:  # crash launching the step
        step.status = FAIL if step.required else WARN
        step.reason = 'could not run: %s' % e
    step.duration = time.time() - t0
    after = snapshot(out_root)
    step.outputs, step.nfiles = summarise_changes(before, after)
    measure(step, before, after)
    return step


def measure(step, before, after):
    """Bytes/files a step added, overall and per top-level entry it wrote (for the size budget)."""
    step.bytes_added = sum(v[1] for v in after.values()) - sum(v[1] for v in before.values())
    step.files_added = len(after) - len(before)
    groups = {}
    for p, v in after.items():
        if before.get(p) == v:
            continue
        top = p.split(os.sep, 1)[0]
        g = groups.setdefault(top, [0, 0])
        g[0] += 1
        g[1] += v[1] - (before[p][1] if p in before else 0)
    step.groups = {k: tuple(v) for k, v in groups.items()}


def tail(log, n=2):
    try:
        lines = [l.strip() for l in open(log, errors='replace').read().splitlines()
                 if l.strip() and set(l.strip()) - set('^~ ')]
        where = [l for l in lines if l.startswith('File "')][-1:]
        return ' | '.join(where + lines[-n:])[-400:]
    except OSError:
        return ''


def skip(step, reason):
    step.status, step.reason = SKIP, reason
    return step


def plan(a):
    t = a.tools
    return [
        Step('clean', os.path.join(t, 'clean', 'apply.py'), timeout=a.timeout_clean,
             note='clean manifest (dry run unless the proposals say otherwise)'),
        Step('build', os.path.join(t, 'build.py'), required=True, timeout=a.timeout_build),
        Step('duckdb', '', timeout=120, note='self-hosted DuckDB-WASM'),
        Step('visualise', os.path.join(t, 'visualise.py'), timeout=a.timeout_visualise),
        Step('extras', os.path.join(t, 'extras.py'), timeout=a.timeout_extras),
        Step('verify', os.path.join(t, 'verify', 'vaccines.py'), timeout=a.timeout_verify),
    ]


def ship(a):
    out = os.path.abspath(a.out)
    report = os.path.abspath(a.report)
    rdir = os.path.dirname(report)
    logs = os.path.join(rdir, 'logs')
    os.makedirs(rdir, exist_ok=True)
    graph = os.path.join(out, 'build_graph.json')
    skips = set(s.strip() for s in a.skip.split(',') if s.strip())
    steps = plan(a)
    by = {s.name: s for s in steps}
    started = now()
    t_all = time.time()
    stopped = False

    if a.fresh and os.path.isdir(out):
        shutil.rmtree(out, ignore_errors=True)

    for st in steps:
        print('ship: %s ...' % st.name, flush=True)
        try:
            if stopped:
                skip(st, 'build.py failed; run stopped')
            elif st.name in skips:
                skip(st, '--skip %s' % st.name)
            elif st.script and not os.path.isfile(st.script):
                skip(st, 'script not found: %s' % os.path.relpath(st.script, a.tools))
            else:
                globals()['step_' + st.name](st, a, out, graph, logs, by)
        except Exception as e:  # ship.py's own bug in a step must not break the site either
            if st.required:
                st.status, st.reason = FAIL, 'ship.py error: %r' % e
            else:
                st.status, st.reason = WARN, 'ship.py error: %r' % e
        if st.status in (WARN,):
            warn('%s: %s' % (st.name, st.reason))
        if st.status == SKIP and st.name not in skips and not stopped:
            warn('%s skipped: %s' % (st.name, st.reason))
        if st.required and st.status == FAIL:
            warn('%s FAILED: %s' % (st.name, st.reason))
            stopped = True
        print('ship: %s %s %.1fs %s' % (st.name, st.status, st.duration, st.reason), flush=True)

    total = time.time() - t_all
    budget = size_budget(a, steps, out, report, stopped)
    write_report(report, steps, a, out, started, total, stopped, budget)
    write_json(os.path.splitext(report)[0] + '.json', steps, out, started, total, stopped, budget)
    return 1 if stopped else 0


# --- steps ---------------------------------------------------------------------------------------------------

def step_clean(st, a, out, graph, logs, by):
    prev = a.clean_graph or (graph if os.path.isfile(graph) else '')
    proposals = a.clean_proposals
    if not prev or not os.path.isfile(prev):
        return skip(st, 'no previous build_graph.json to clean against (first build); '
                        'manifest falls back to %s if present' % (a.clean_manifest or VK_MANIFEST))
    if not proposals or not os.path.isdir(proposals) or not any(
            f.endswith('.json') for f in os.listdir(proposals)):
        return skip(st, 'no clean proposals folder (%s)' % proposals)
    os.makedirs(os.path.dirname(os.path.abspath(a.clean_out)), exist_ok=True)
    cmd = [PY, st.script, '--graph', prev, '--proposals', proposals, '--out', a.clean_out]
    if a.src and os.path.isdir(a.src):
        cmd += ['--src', a.src]
    else:
        cmd += ['--no-verify-blobs']
    run_cmd(st, cmd, logs, os.path.dirname(os.path.abspath(a.clean_out)))
    if st.status == OK:
        st.outputs = a.clean_out
        try:
            m = json.load(open(a.clean_out))
            st.outputs += ' (dry_run=%s)' % m.get('dry_run')
        except Exception:
            pass


def pick_manifest(a, by):
    """The manifest build.py should get: this run's clean output, else the shared one, else --clean-manifest."""
    cands = []
    if by['clean'].status == OK:
        cands.append(a.clean_out)
    if a.clean_manifest:
        cands.append(a.clean_manifest)
    cands += [a.clean_out, VK_MANIFEST]
    for c in cands:
        if c and os.path.isfile(c):
            return c
    return ''


def step_build(st, a, out, graph, logs, by):
    cmd = [PY, st.script, '--src', a.src, '--out', out, '--base', a.base]
    if a.kuiper_tools:
        cmd += ['--kuiper-tools', a.kuiper_tools]
    manifest = pick_manifest(a, by)
    flags = script_flags(st.script)
    a.duckdb_by_build = False
    if a.duckdb_vendor and os.path.isdir(a.duckdb_vendor) and '--duckdb-dir' in flags:
        cmd += ['--duckdb-dir', a.duckdb_vendor]  # same path as CI: build.py places vendor/duckdb/
        a.duckdb_by_build = True
    if manifest:
        if '--clean-manifest' in flags:
            cmd += ['--clean-manifest', manifest]
            st.note = 'with --clean-manifest %s' % manifest
        else:
            st.note = 'manifest %s exists but build.py has no --clean-manifest yet; built without it' % manifest
    else:
        st.note = 'no clean manifest found; built without --clean-manifest'
    if not os.path.isdir(a.src):
        st.status, st.reason = FAIL, 'clones folder not found: %s' % a.src
        return
    run_cmd(st, cmd, logs, out)
    if st.status == OK:
        missing = [f for f in ('build_graph.json', 'index.html') if not os.path.isfile(os.path.join(out, f))]
        if missing:
            st.status, st.reason = FAIL, 'build.py exited 0 but wrote no %s' % ', '.join(missing)


def step_duckdb(st, a, out, graph, logs, by):
    src = a.duckdb_vendor
    dst = os.path.join(out, 'vendor', 'duckdb')
    if getattr(a, 'duckdb_by_build', False) and os.path.isdir(dst):
        files = os.listdir(dst)
        size = sum(os.path.getsize(os.path.join(dst, f)) for f in files)
        st.status, st.note = OK, 'placed by build.py --duckdb-dir (counted here for the size budget)'
        st.nfiles = st.files_added = len(files)
        st.bytes_added = size
        st.outputs = 'vendor/duckdb/ (%d files, %.1f MB)' % (len(files), size / 1e6)
        return
    if not src or not os.path.isdir(src):
        return skip(st, 'no DuckDB-WASM staging folder (%s); search.html keeps its CDN/fallback path' % src)
    files = [f for f in os.listdir(src) if os.path.isfile(os.path.join(src, f))]
    if not any(f.endswith('.wasm') for f in files) or not any(f.endswith('.mjs') for f in files):
        return skip(st, 'staging folder %s lacks .wasm/.mjs files' % src)
    t0 = time.time()
    os.makedirs(dst, exist_ok=True)
    size = 0
    for f in files:
        shutil.copy2(os.path.join(src, f), os.path.join(dst, f))
        size += os.path.getsize(os.path.join(dst, f))
    st.status = OK
    st.duration = time.time() - t0
    st.nfiles = st.files_added = len(files)
    st.bytes_added = size
    st.outputs = 'vendor/duckdb/ (%d files, %.1f MB)' % (len(files), size / 1e6)


def step_visualise(st, a, out, graph, logs, by):
    if not os.path.isfile(graph):
        return skip(st, 'no build_graph.json')
    run_cmd(st, [PY, st.script, '--graph', graph, '--out', os.path.join(out, 'visual')], logs, out)


def step_extras(st, a, out, graph, logs, by):
    cmd = [PY, st.script, '--site', out, '--graph', graph, '--base', a.base,
           '--timeout', str(max(60, a.timeout_extras // 3))]
    if a.src and os.path.isdir(a.src):
        cmd += ['--src', a.src]
    if not a.no_link_index:
        cmd += ['--link-index']
    run_cmd(st, cmd, logs, out)
    try:
        ex = json.load(open(os.path.join(out, 'extras.json')))
        items = [e for e in ex.get('extras', []) if isinstance(e, dict)]
        ran = ['%s (%s)' % (e.get('slug'), e.get('status')) for e in items if e.get('status') in ('ok', 'data')]
        other = ['%s (%s)' % (e.get('slug'), e.get('status')) for e in items if e.get('status') not in ('ok', 'data')]
        st.note = 'extras published: %s' % (', '.join(ran) or 'none')
        if other:
            st.note += '; not published: ' + ', '.join(other)
    except Exception:
        pass


def step_verify(st, a, out, graph, logs, by):
    vrep = os.path.join(os.path.dirname(os.path.abspath(a.report)), 'VACCINES.md')
    cmd = [PY, st.script, 'run', out, '--report', vrep, '--no-mobile']
    run_cmd(st, cmd, logs, os.path.dirname(vrep))
    if st.status == WARN and st.rc == 1:
        st.reason = 'vaccines found FAIL cells (see %s); site shipped anyway' % vrep
    st.outputs = vrep if os.path.isfile(vrep) else st.outputs


# --- size budget ("a photon without mass": nothing duplicated, no view bigger than it must be) ---------------

def budget_check(steps):
    """Warnings for any optional step (extra) adding more than the budget, overall or per folder it adds."""
    out = []
    for s in steps:
        if s.required or s.status not in (OK, WARN) or s.name in ('verify', 'clean'):
            continue
        items = [(s.name + ' (whole step)', s.files_added, s.bytes_added)]
        if s.name == 'extras':  # one extra = one top-level folder
            items += [('extras: %s/' % k, n, b) for k, (n, b) in s.groups.items()]
        for label, n, b in items:
            if b > BUDGET_STEP_MB * 1e6 or n > BUDGET_STEP_FILES:
                msg = '%s adds %.1f MB / %d files (budget %.0f MB / %d files)' % (
                    label, b / 1e6, n, BUDGET_STEP_MB, BUDGET_STEP_FILES)
                s.budget.append(msg)
                out.append(msg)
    return out


def duplicate_groups(root, min_bytes=DUP_MIN_BYTES):
    """[(size, [relpaths])] for files of at least min_bytes whose bytes occur more than once under root."""
    by_size = {}
    for dp, dns, fns in os.walk(root):
        dns[:] = [d for d in dns if d not in ('.git', '.extras-staging', '__pycache__')]
        for f in fns:
            p = os.path.join(dp, f)
            try:
                sz = os.path.getsize(p)
            except OSError:
                continue
            if sz >= min_bytes and not os.path.islink(p):
                by_size.setdefault(sz, []).append(p)
    groups = []
    for sz, ps in by_size.items():
        if len(ps) < 2:
            continue
        by_hash = {}
        for p in ps:
            h = hashlib.sha256()
            with open(p, 'rb') as fh:
                for chunk in iter(lambda: fh.read(1 << 20), b''):
                    h.update(chunk)
            by_hash.setdefault(h.hexdigest(), []).append(os.path.relpath(p, root))
        groups += [(sz, sorted(v)) for v in by_hash.values() if len(v) > 1]
    return sorted(groups, key=lambda g: -g[0] * (len(g[1]) - 1))


def tree_size(root):
    n = b = 0
    for dp, dns, fns in os.walk(root):
        dns[:] = [d for d in dns if d not in ('.git', '.extras-staging', '__pycache__')]
        for f in fns:
            try:
                b += os.path.getsize(os.path.join(dp, f))
                n += 1
            except OSError:
                pass
    return n, b


def size_budget(a, steps, out, report, stopped):
    root = os.path.abspath(a.artifact or out)
    prev = {}
    pj = os.path.splitext(report)[0] + '.json'
    try:
        prev = json.load(open(pj)).get('budget', {}) or {}
    except Exception:
        pass
    n, b = tree_size(root)
    dups = duplicate_groups(root) if os.path.isdir(root) else []
    warns = budget_check(steps)
    for w in warns:
        warn('size budget: ' + w)
    if dups:
        warn('size budget: %d duplicate-content groups >= %d KB (%.1f MB wasted)' % (
            len(dups), DUP_MIN_BYTES // 1024, sum(sz * (len(ps) - 1) for sz, ps in dups) / 1e6))
    return {'root': root, 'files': n, 'bytes': b,
            'prev_files': prev.get('files'), 'prev_bytes': prev.get('bytes'), 'prev_started': prev.get('started'),
            'warnings': warns, 'duplicates': [{'bytes': sz, 'paths': ps} for sz, ps in dups],
            'wasted_bytes': sum(sz * (len(ps) - 1) for sz, ps in dups), 'started': now()}


def budget_lines(bd, steps):
    def delta(cur, old, fmt):
        return '-' if old is None else fmt(cur - old)
    L = ['## Size budget', '',
         '| measure | this build | last build | change |', '|---|---|---|---|',
         '| artifact size (`%s`) | %.1f MB | %s | %s |' % (
             bd['root'], bd['bytes'] / 1e6, '-' if bd['prev_bytes'] is None else '%.1f MB' % (bd['prev_bytes'] / 1e6),
             delta(bd['bytes'], bd['prev_bytes'], lambda d: '%+.1f MB' % (d / 1e6))),
         '| file count | %d | %s | %s |' % (bd['files'], '-' if bd['prev_files'] is None else bd['prev_files'],
                                            delta(bd['files'], bd['prev_files'], lambda d: '%+d' % d)),
         '| duplicate bytes (groups >= %d KB) | %.1f MB in %d groups | | |' % (
             DUP_MIN_BYTES // 1024, bd['wasted_bytes'] / 1e6, len(bd['duplicates'])), '']
    L += ['| step | added | files | budget (%.0f MB / %d files per extra) |' % (BUDGET_STEP_MB, BUDGET_STEP_FILES),
          '|---|---|---|---|']
    for s in steps:
        if s.status in (OK, WARN) and s.name not in ('verify', 'clean'):
            L.append('| %s | %.1f MB | %+d | %s |' % (s.name, s.bytes_added / 1e6, s.files_added,
                                                     'OVER: ' + '; '.join(s.budget) if s.budget else
                                                     ('n/a (required)' if s.required else 'within')))
    if bd['duplicates']:
        L += ['', 'Duplicate-content groups (largest waste first; code text should live once):', '']
        for d in bd['duplicates'][:25]:
            ps = d['paths']
            L.append('- %.0f KB x%d: %s' % (d['bytes'] / 1024, len(ps), ', '.join('`%s`' % p for p in ps[:4]) +
                                           (' +%d more' % (len(ps) - 4) if len(ps) > 4 else '')))
        if len(bd['duplicates']) > 25:
            L.append('- ... %d more groups (see SHIP-REPORT.json)' % (len(bd['duplicates']) - 25))
    return L + ['']


# --- report --------------------------------------------------------------------------------------------------

def write_report(path, steps, a, out, started, total, stopped, budget=None):
    verdict = 'BUILD FAILED - run stopped' if stopped else (
        'shipped with warnings' if any(s.status in (WARN, SKIP) for s in steps) else 'shipped clean')
    L = ['# SHIP-REPORT', '',
         'ship.py %s, started %s, total %.0fs. Verdict: **%s**.' % (GENERATOR_VERSION, started, total, verdict),
         '', 'Site: `%s`  Clones: `%s`  Base: %s' % (out, a.src, a.base), '']
    if budget:
        L += budget_lines(budget, steps)
    L += ['## Steps', '',
          '| # | step | status | duration | outputs | notes |', '|---|---|---|---|---|---|']
    for i, s in enumerate(steps, 1):
        notes = '; '.join(x for x in (s.note, s.reason if s.status != SKIP else '') if x)
        L.append('| %d | %s%s | %s | %.1fs | %s | %s |' % (
            i, s.name, ' (required)' if s.required else '', s.status, s.duration,
            (s.outputs or '-').replace('|', '/'), notes.replace('|', '/').replace('\n', ' ')))
    sk = [s for s in steps if s.status in (SKIP, WARN, FAIL)]
    L += ['', '## Skipped or warned', '']
    L += ['- **%s** (%s): %s' % (s.name, s.status, s.reason or 'no reason recorded') for s in sk] or ['- none']
    L += ['', '## Commands', '']
    L += ['- %s: `%s`' % (s.name, ' '.join(s.cmd)) for s in steps if s.cmd]
    L += ['', 'Logs: `%s/logs/<step>.log`. Only build.py failing stops the run; every other step is optional.'
          % os.path.dirname(path), '']
    with open(path, 'w') as fh:
        fh.write('\n'.join(L))


def write_json(path, steps, out, started, total, stopped, budget=None):
    rec = {'generator': GENERATOR_VERSION, 'started': started, 'total_s': round(total, 1), 'site': out,
           'stopped': stopped, 'budget': budget,
           'steps': [{'name': s.name, 'required': s.required, 'status': s.status, 'duration_s': round(s.duration, 1),
                      'outputs': s.outputs, 'files': s.nfiles, 'bytes_added': s.bytes_added,
                      'files_added': s.files_added, 'over_budget': s.budget, 'reason': s.reason, 'note': s.note, 'rc': s.rc}
                     for s in steps]}
    with open(path, 'w') as fh:
        json.dump(rec, fh, indent=1)


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--src', required=True, help='folder with one clone per public repository')
    ap.add_argument('--out', required=True, help='the explore-code output folder, e.g. _site/explore-code')
    ap.add_argument('--base', default=os.environ.get('EXPLORE_BASE', 'https://code.globalgrid2050.com/explore-code/'))
    ap.add_argument('--kuiper-tools', default='')
    ap.add_argument('--report', default='SHIP-REPORT.md', help='report path (a .json twin is written beside it)')
    ap.add_argument('--artifact', default='', help='folder measured by the size budget (default --out; CI: _site)')
    ap.add_argument('--tools', default=HERE, help='tools/explore folder holding the step scripts')
    ap.add_argument('--skip', default='', help='comma-separated step names to skip')
    ap.add_argument('--fresh', action='store_true', help='delete --out before building')
    ap.add_argument('--duckdb-vendor', default=os.environ.get('DUCKDB_VENDOR', ''),
                    help='staged DuckDB-WASM files copied to <out>/vendor/duckdb/')
    ap.add_argument('--clean-manifest', default='', help='existing clean manifest (used if clean/apply.py does not run)')
    ap.add_argument('--clean-out', default='', help='where clean/apply.py writes (default <report dir>/clean/manifest.json)')
    ap.add_argument('--clean-proposals', default='', help='proposals folder (default clean/proposals in tools, else /tmp/vk/clean/proposals)')
    ap.add_argument('--clean-graph', default='', help='graph for clean/apply.py (default: previous <out>/build_graph.json)')
    ap.add_argument('--no-link-index', action='store_true', help='do not pass --link-index to extras.py')
    for name, default in (('build', 3000), ('clean', 300), ('visualise', 900), ('extras', 2400), ('verify', 1200)):
        ap.add_argument('--timeout-' + name, type=int, default=default, help='seconds (default %(default)s)')
    a = ap.parse_args(argv)
    a.base = a.base.rstrip('/') + '/'
    a.tools = os.path.abspath(a.tools)
    a.src = os.path.abspath(a.src)
    if not a.clean_out:
        a.clean_out = os.path.join(os.path.dirname(os.path.abspath(a.report)), 'clean', 'manifest.json')
    if not a.clean_proposals:
        local = os.path.join(a.tools, 'clean', 'proposals')
        a.clean_proposals = local if os.path.isdir(local) else '/tmp/vk/clean/proposals'
    return ship(a)


if __name__ == '__main__':
    sys.exit(main())