instinct-cli 0.3.10

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
#!/usr/bin/env python3
"""Replay the frozen sparse-rule experiment against an Instinct binary."""
import argparse
import concurrent.futures
import hashlib
import itertools
import json
import math
import os
from pathlib import Path
import re
import statistics
import subprocess
import tempfile


HERE = Path(__file__).resolve().parent
PROTOCOL = "5f82f8d1c9624c1fc80be442fc00c3fa0fcc91e8b130f602b93f66a9d9d9b0fd"
FIXTURES = "bc37ee5ca632a9c9fd1274a4a723d276fea90a4c4304215cabc3f1f756ba427f"
KEYS = tuple(f"f{i}" for i in range(8))
CHECKS = [{"key": k, "question": f"Is {k} set?", "cost": 1} for k in KEYS]
LABELS = ["amber", "indigo"]
ARMS = ("adaptive", "random", "coverage")
ROWS = tuple(range(256))


def digest(data):
    return hashlib.sha256(data).hexdigest()


def compact(obj):
    return json.dumps(obj, separators=(",", ":"), sort_keys=True)


def order(rows, world, purpose):
    return sorted(rows, key=lambda x: digest(f"active-v1/{world}/{purpose}/{x}".encode()))


def facts(row):
    return {key: bool(row & (1 << i)) for i, key in enumerate(KEYS)}


def decode(obj):
    if set(obj) != set(KEYS) or any(type(v) is not bool for v in obj.values()):
        raise ValueError(f"experiment returned invalid configuration {obj}")
    return sum(int(obj[key]) << i for i, key in enumerate(KEYS))


class World:
    def __init__(self, number):
        self.number = number
        self.left, self.right = order(range(8), number, "columns")[:2]
        self.flips = int(digest(f"active-v1/{number}/flips".encode())[:2], 16)
        ranking = order(ROWS, number, "historical")
        self.seeds = [next(row for row in ranking if self.label(row) == label) for label in LABELS]
        available = set(ROWS) - set(self.seeds)
        self.test = order(available, number, "holdout")[:64]
        self.pool = sorted(available - set(self.test))
        self.random = order(self.pool, number, "random")
        self.tie = order(self.pool, number, "coverage")
        assert len(set(self.pool) | set(self.seeds) | set(self.test)) == 256

    def label(self, row):
        left = bool(row >> self.left & 1) ^ bool(self.flips & 1)
        right = bool(row >> self.right & 1) ^ bool(self.flips & 2)
        value = (left and right, left or right, left != right, (not left) or right)[self.number % 4]
        return LABELS[int(value ^ bool(self.flips & 4))]


def interactions(row):
    out = 0
    for p, (a, b) in enumerate(itertools.combinations(range(8), 2)):
        value = ((row >> a) & 1) + 2 * ((row >> b) & 1)
        out |= 1 << (4 * p + value)
    return out


COVER = [interactions(row) for row in ROWS]


def next_coverage(world, observed, remaining):
    covered = 0
    for row in observed:
        covered |= COVER[row]
    def rank(row):
        return ((COVER[row] & ~covered).bit_count(),
                min((row ^ other).bit_count() for other in observed))
    # Python's max keeps the first configuration at a tied rank.
    return max((row for row in world.tie if row in remaining), key=rank)


class Bank:
    def __init__(self, binary, directory):
        self.binary = str(binary)
        self.cwd = directory
        self.env = {k: v for k, v in os.environ.items() if not k.startswith("INSTINCT_")}
        self.env.update(INSTINCT_STORE=str(Path(directory) / "bank.hxdb"),
                        INSTINCT_STARTER="0", INSTINCT_TEAM="0", HOME=directory,
                        XDG_DATA_HOME=directory, XDG_STATE_HOME=directory, XDG_CACHE_HOME=directory)
        self.lesson = None

    def run(self, args, data=None):
        proc = subprocess.run([self.binary, *args], input=data, capture_output=True,
                              text=True, cwd=self.cwd, env=self.env, timeout=30)
        if proc.returncode:
            raise RuntimeError(f"{args[:3]} failed with {proc.returncode}: {proc.stderr.strip()}")
        return proc.stdout

    def observe(self, rows):
        examples = [{"ref": ref, "facts": facts(row), "action": action}
                    for ref, row, action in rows]
        lesson = {"title": "Decide which desk receives the packet",
                  "when": "A packet arrives for routing",
                  "found": "The original desk can be verified.",
                  "how": "Read the packet checks and verify the receipt.",
                  "evidence": "Receipts for the observed desk routing examples.",
                  "cases": {"checks": CHECKS, "examples": examples}}
        text = self.run(["bank", "--project", "lab", "--from", "-"], compact(lesson))
        match = re.search(r"\bin-[0-9a-z]+\b", text)
        if not match or self.lesson is not None and match[0] != self.lesson:
            raise ValueError(f"Unexpected bank response {text!r}")
        self.lesson = match[0]

    def exact_action(self, row):
        args = ["decide", "--q", "A packet arrives for routing", "--project", "lab",
                "--facts", compact(facts(row))]
        packet = json.loads(self.run(args))
        lesson, = packet["experiences"]
        assert lesson["id"] == self.lesson
        return lesson["case_advice"].get("candidate_action")

    def experiment(self, pool, row=None):
        args = ["guide", "experiment", "--id", self.lesson, "--project", "lab", "--pool", "-", "--json"]
        if row is not None:
            args += ["--facts", compact(facts(row))]
        return json.loads(self.run(args, compact([facts(x) for x in pool])))


def trial(binary, world, arm):
    with tempfile.TemporaryDirectory(prefix="instinct-teach-") as directory:
        bank = Bank(binary, directory)
        observed = world.seeds.copy()
        remaining = set(world.pool)
        bank.observe([(str(row), row, world.label(row)) for row in observed])
        while True:
            state = bank.experiment(sorted(remaining))
            if state["status"] in ("falsified", "unsupported", "identified") or len(observed) >= 64:
                break
            if arm == "adaptive":
                if state["next_case"] is None:
                    break
                row = decode(state["next_case"]["facts"])
            elif arm == "random":
                row = world.random[len(observed) - len(world.seeds)]
            else:
                row = next_coverage(world, observed, remaining)
            if row not in remaining:
                raise RuntimeError("A proposal repeated an observation or used a held-out row.")
            remaining.remove(row)
            bank.observe([(str(row), row, world.label(row))])
            observed.append(row)
        predictions = [bank.experiment([], row)["prediction"] for row in world.test]
        correct = sum(pred == world.label(row) for row, pred in zip(world.test, predictions))
        abstained = predictions.count(None)
        exact = None
        if arm == "adaptive":
            ordinary = [bank.exact_action(row) for row in world.test]
            exact_correct = sum(pred == world.label(row) for row, pred in zip(world.test, ordinary))
            exact = {"labels": len(observed), "correct": exact_correct, "abstained": ordinary.count(None),
                     "wrong": len(ordinary) - exact_correct - ordinary.count(None)}
        result = {"labels": len(observed), "remaining_models": state["surviving_models"],
                "status": state["status"], "correct": correct, "abstained": abstained,
                "wrong": len(predictions) - correct - abstained,
                "success": state["status"] == "identified" and state["surviving_models"] == 1 and correct == 64,
                "queried": observed, "predictions_sha256": digest(compact(predictions).encode())}
        return result, exact


def negatives(binary):
    all_parity = [(str(row), row, LABELS[row.bit_count() % 2]) for row in range(8)]
    contradictory = [("a", 0, "amber"), ("b", 0, "indigo")]
    linked = [(str(row), row, LABELS[row & 1]) for row in ROWS
              if (row & 1) == ((row >> 1) & 1)]
    results = {}
    for kind, seed, pool, query in [
        ("three_bit_parity", all_parity, [10, 11], 11),
        ("contradiction", contradictory, [1, 2], 1),
        ("confounding", linked[:2], [r for _, r, _ in linked], 1),
    ]:
        with tempfile.TemporaryDirectory(prefix="instinct-teach-control-") as directory:
            bank = Bank(binary, directory)
            bank.observe(seed)
            state = bank.experiment(pool, query)
            # If any still-separating experiment exists on the confounded support, teach its true action.
            # Both equivalent literal rules will still survive every observation on that support.
            labeled = {r for _, r, _ in seed}
            while kind == "confounding" and state["next_case"] is not None:
                row = decode(state["next_case"]["facts"])
                assert row in pool and row not in labeled
                labeled.add(row)
                bank.observe([(str(row), row, LABELS[row & 1])])
                state = bank.experiment(pool, query)
            unresolved = state["prediction"] is None and state["next_case"] is None
            expected = (state["status"] == "learning" and state["surviving_models"] > 1
                        if kind == "confounding" else
                        state["status"] == "falsified" and state["surviving_models"] == 0)
            results[kind] = {"status": state["status"], "remaining_models": state["surviving_models"],
                             "prediction": state["prediction"], "proposed": state["next_case"] is not None,
                             "labels": len(labeled) if kind == "confounding" else len(seed),
                             "passed": unresolved and expected}
    return results


def compare(worlds, arm):
    pairs = [(r[arm]["labels"], r["adaptive"]["labels"]) for r in worlds]
    wins = sum(a > b for a, b in pairs)
    losses = sum(a < b for a, b in pairs)
    n = wins + losses
    p = min(1.0, 2 * sum(math.comb(n, k) for k in range(min(wins, losses) + 1)) / 2**n)
    gated = all(r[arm]["success"] and r["adaptive"]["success"] for r in worlds)
    totals = [sum(col) for col in zip(*pairs)]
    return {"adaptive_wins": wins, "ties": len(pairs) - n, "adaptive_losses": losses,
            "two_sided_sign_p": p, "labels_saved": totals[0] - totals[1],
            "label_ratio": totals[0] / totals[1] if gated else None,
            "efficiency_gate": gated and totals[0] > totals[1] and p < 0.05}


def run(binary, jobs):
    assert digest((HERE / "protocol.md").read_bytes()) == PROTOCOL, "protocol changed"
    worlds = [World(i) for i in range(16)]
    manifest = [{"world": w.number, "initial": w.seeds, "pool": w.pool, "test": w.test,
                 "truth": [w.label(row) for row in ROWS]} for w in worlds]
    assert digest(compact(manifest).encode()) == FIXTURES, "teacher or split changed"
    records = [{"world": w.number, "test_sha256": digest(compact(w.test).encode()),
                "seed_rows": w.seeds} for w in worlds]
    with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as workers:
        runs = {workers.submit(trial, binary, w, arm): (w.number, arm) for w in worlds for arm in ARMS}
        for job in concurrent.futures.as_completed(runs):
            number, arm = runs[job]
            records[number][arm], exact = job.result()
            if exact is not None:
                records[number]["exact"] = exact
    return {"protocol_sha256": PROTOCOL, "fixtures_sha256": FIXTURES, "worlds": records, "controls": negatives(binary),
            "summary": {arm: {"labels": sum(w[arm]["labels"] for w in records),
                              "median_labels": statistics.median(w[arm]["labels"] for w in records),
                              "identified_and_correct": sum(w[arm]["success"] for w in records),
                              "correct": sum(w[arm]["correct"] for w in records),
                              "wrong": sum(w[arm]["wrong"] for w in records),
                              "abstained": sum(w[arm]["abstained"] for w in records)} for arm in ARMS},
            "paired": {arm: compare(records, arm) for arm in ("random", "coverage")}}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("binary", type=Path)
    parser.add_argument("--jobs", type=int, default=3, choices=range(1, 9))
    parser.add_argument("--out", type=Path)
    args = parser.parse_args()
    result = run(args.binary.resolve(strict=True), args.jobs)
    text = json.dumps(result, indent=2, sort_keys=True) + "\n"
    if args.out:
        args.out.write_text(text)
    else:
        print(text, end="")
    if not all(c["passed"] for c in result["controls"].values()):
        raise SystemExit("A negative control failed; results retained.")
    if not all(result["summary"][a]["identified_and_correct"] == 16 for a in ARMS):
        raise SystemExit("At least one arm missed the capability gate; results retained.")