diff --git a/prototypes/t3/README.md b/prototypes/t3/README.md new file mode 100644 index 00000000..094c1d1d --- /dev/null +++ b/prototypes/t3/README.md @@ -0,0 +1,63 @@ +# T3 driver lifecycle prototype + +Login: stays on your machine +Effort: the host can't set it (the T3 0.1.11 CLI accepts model options but cannot discover or verify the exact executed effort) + +This disposable driver implements the [v1 protocol](../../kernel/driver.v1.md) against a local fixture. It requires Python 3.9 or later on macOS or Linux and an existing private temporary directory. The only transport it can launch is the sibling `fixture.py`, using its own Python interpreter. The fixture models an agent, its work, and a ticket's builder note in JSON files. It uses no login, T3 server, agent CLI, network, private T3 storage, or GitHub. + +The fixture maps `example/site` to project `prj_syn-openwiz` with a checkout under the disposable directory, and maps `codex` with `gpt-6.2-sol` to provider instance `instance-syn-codex`. A start uses the project root, the host's default effort, and a stable title of the form `#7: example/site builder ()`. The driver returns its own per-run identifier. An explicit effort for the mapped pair gets the v1 refusal before the driver opens state or dispatches anything. A production caller with a configured effort must wait for support, under E4. + +## T3 0.1.11 evidence and fixture behavior + +- Checked the installed `t3` only with `--version`, `--help`, `thread --help`, `thread start --help`, `thread send --help`, `provider --help`, and `project --help`. The release tag points to `59651c1761f6c63e9b6056839067066968e6a406`. [Upstream release](https://github.com/pingdotgg/t3code/releases/tag/v0.1.11) +- The fixture parses the supported argument forms `t3 thread start --json --title TITLE --provider INSTANCE --model MODEL PROJECT -` and `t3 thread send --json THREAD -`, with the prompts on stdin. Start sends a project ID, omits the worktree flag, and expects a receipt containing `threadId`, `projectId` and `runId`. A null run ID can describe a thread without a verified run. The start receipt itself carries neither the selected checkout nor the executed model or effort. A live check must confirm those separately. [Start and workspace options in the tagged source](https://github.com/pingdotgg/t3code/blob/v0.1.11/apps/server/src/cli/thread.ts#L703-L756) · [Start dispatch and JSON](https://github.com/pingdotgg/t3code/blob/v0.1.11/apps/server/src/cli/thread.ts#L817-L891) +- Send uses queue mode. A busy thread keeps its active turn and queues the follow-up. An idle thread starts a turn immediately. The reply identifies the thread, message, and turn with a status and delivery disposition. It acknowledges delivery or queuing. The tracker checks whether the turn later edits the original note. [Send dispatch and JSON](https://github.com/pingdotgg/t3code/blob/v0.1.11/apps/server/src/cli/thread.ts#L894-L933) · [Receipt schema](https://github.com/pingdotgg/t3code/blob/v0.1.11/packages/contracts/src/orchestratorMcp.ts#L568-L577) +- The installed CLI has no thread stop or archive verb. Tagged server source has an MCP interrupt tool with a stop option that requests a stop and addresses delegated tasks. Its receipt can say `interrupt_requested`. A production driver still needs a supported, approved host entry point and independent proof that the provider, subprocesses, and delegated work ended. The CLI parity issue moved to a discussion. [CLI commands](https://github.com/pingdotgg/t3code/blob/v0.1.11/apps/server/src/cli/thread.ts#L989-L997) · [Server stop behavior](https://github.com/pingdotgg/t3code/blob/v0.1.11/apps/server/src/mcp/OrchestratorMcpService.ts#L3721-L3770) · [Parity discussion](https://github.com/pingdotgg/t3code/discussions/33855) +- `terminate-fixture` and `advance-fixture` are local fixture controls. The fixture clears queued turns and modeled work, including delegated work, while retaining the thread and ticket note. T3’s stop holds queued work. A live proof must verify that held messages cannot restart the stopped run. An incomplete receipt keeps wakes fenced and permits a stop retry. Tests verify an unrelated thread and note survive. The fixture uses no long-lived provider or child processes. + +The driver serializes lifecycle requests in each disposable directory. Before dispatch, it records attempts that could have side effects. An ambiguous start fences that ticket, and an ambiguous send fences further wakes while stop stays available for a known thread. Each acknowledged wake sends one message to the original thread. V1 carries no caller request ID, so an unresolved send requires inspection before another wake. It leaves an unresolved start for inspection in the disposable state. + +## Reproduce the local checks + +Run these commands from the repository root. + +```sh +python3 -I prototypes/t3/test_driver.py -v +prototypes/t3/driver version +prototypes/t3/driver schema | cmp - kernel/driver-kit/schema.json +``` + +Run the existing kit against a newly created fake tracker. Automatic advance lets the kit observe the queued turn edit the note without a separate fixture control call. + +```sh +( + export TMPDIR="${TMPDIR:-/tmp}" + OPENWIZ_T3_FIXTURE_DIR=$(mktemp -d "${TMPDIR%/}/openwiz-t3-fixture-XXXXXX") || exit 1 + export OPENWIZ_T3_FIXTURE_DIR + trap 'rm -rf -- "$OPENWIZ_T3_FIXTURE_DIR"' EXIT + export OPENWIZ_T3_FIXTURE_AUTO_ADVANCE=1 + export PATH="$(dirname "$(command -v python3)"):/usr/bin:/bin" + python3 -I prototypes/t3/fixture.py init-tracker 7 || exit + python3 -I kernel/driver-kit/kit.py --driver prototypes/t3/driver \ + --repo example/site --ticket 7 --harness codex --model gpt-6.2-sol \ + --skill build-ticket --effort medium --wait 5 \ + --tracker "$OPENWIZ_T3_FIXTURE_DIR/tracker-7.json" +) +``` + +Before implementation, `python3 -I prototypes/t3/test_driver.py Lifecycle.test_executable_lifecycle` ran one test and exited 1 at the first start, with the assertion `expected an executable driver for start; prototypes/t3/driver is missing`. It passed after implementation. The focused suite also exercises concurrent requests, an idle wake, malformed state, credential-shaped fields, and stopping after the checkout disappears. On macOS arm64, the fake-tracker kit passed version, start, wake, stop, and token. The macOS observer saw marked fixture processes. The provider and delegated work were simulated. + +## Later authorized host proof + +After spec and child-ticket approval, establish the supported host command and evidence for per-thread stop, descendant cleanup, and exact effort. Confirm the mapped project, checkout, provider instance and model on the selected build before dispatch. Use the host's own signed-in CLI and harness without handling credentials. For the approved Mac smoke, use a separate T3 data directory, isolated checkout and one approved throwaway ticket. Check the visible thread and executed settings, wake it while busy, and verify the original note changes. Verify queue disposition and termination of the provider, process and child work, keep the thread inspectable, and check another thread survives. Archive only if the approved design calls for it. + +Run the [five-check kit](../../kernel/driver-kit/README.md) on that candidate and authorized ticket, with its record author and supported model and effort. Set the values below to those approved for the smoke. The kit reads GitHub and the live agent writes its own note. + +```sh +python3 -I kernel/driver-kit/kit.py --driver "$APPROVED_DRIVER" \ + --repo "$SMOKE_REPOSITORY" --ticket "$SMOKE_TICKET" \ + --harness "$SMOKE_HARNESS" --model "$SMOKE_MODEL" \ + --skill build-ticket --effort "$SMOKE_EFFORT" --wait 900 +``` + +Use the same live procedure on the approved deployment host and record the exact driver and host builds and cleanup. macOS requires the process observer to see a marked run process for stop and token to pass. A kit outside the host needs separate host-side evidence of termination. diff --git a/prototypes/t3/driver b/prototypes/t3/driver new file mode 100755 index 00000000..bf0be45e --- /dev/null +++ b/prototypes/t3/driver @@ -0,0 +1,216 @@ +#!/usr/bin/env -S python3 -I +"""Disposable OpenWiz v1 lifecycle driver for the pinned repository fixture.""" +import json +from pathlib import Path +import re +import subprocess +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.dont_write_bytecode = True +import fixture + +# Read the kit's public patterns without inspecting the caller's environment. +sys.path.insert(0, str(HERE.parents[1] / "kernel" / "live-rig")) +import rig + +SCHEMA = HERE.parents[1] / "kernel" / "driver-kit" / "schema.json" +VERSION = {"driver": "t3-fixture", "records": ["openwiz:records v1"], "can": ["start", "wake", "stop"]} +CANT_SET_EFFORT = ("this host can't set effort: remove the effort for this harness in your Models table or Roster " + "to run it at the host's default") +INSPECT = "inspect the disposable fixture state before any new start or wake" +ACCEPTED_RUN_STATES = {"preparing", "queued", "starting", "running", "waiting", "completed"} + + +class Refused(Exception): + pass + + +def request(command): + schema = json.loads(SCHEMA.read_bytes())["commands"][command]["input"] + try: + value = json.loads(sys.stdin.buffer.read().decode("utf-8"), object_pairs_hook=fixture.unique) + except (ValueError, RecursionError): + raise Refused("input is unreadable JSON or repeats a key", "send one JSON object, with each key once") + properties = schema["properties"] + if not isinstance(value, dict) or not set(schema["required"]) <= value.keys() <= properties.keys(): + raise Refused("input fields do not match driver v1", "send only the fields shown by driver schema") + try: + shapes = rig.kit_shapes() + except rig.Refused: + raise Refused("credential shapes are unavailable", "use a checkout with the v1 driver kit") + for name, field in value.items(): + rule = properties[name] + if rule["type"] == "integer": + valid = type(field) is int and field >= rule["minimum"] + else: + valid = (isinstance(field, str) and len(field) <= rule.get("maxLength", len(field)) + and re.fullmatch(rule["pattern"], field)) + if not valid: + raise Refused(f"invalid {name}", "use the type and format shown by driver schema") + if isinstance(field, str) and shapes.search(field): + raise Refused("input looks like a credential", "send only driver fields without credentials") + return value + + +def transport(cwd, words, prompt=""): + # The only program this driver starts is the repository's fake transport. + try: + result = subprocess.run( + [sys.executable, "-I", str(HERE / "fixture.py"), *words], + input=prompt, capture_output=True, text=True, cwd=cwd, timeout=5, + ) + if result.returncode == 0: + return json.loads(result.stdout, object_pairs_hook=fixture.unique) + except (OSError, ValueError, subprocess.TimeoutExpired): + pass + return None + + +def synthetic_id(value, prefix): + return isinstance(value, str) and re.fullmatch(prefix + "[0-9a-f]{32}", value) is not None + + +def load_runs(root): + runs = fixture.load(root / "runs.json", {}) + if not isinstance(runs, dict): + raise ValueError("invalid run index") + threads = set() + for run, record in runs.items(): + if not (synthetic_id(run, "run-") and isinstance(record, dict) + and type(record.get("ticket")) is int and record["ticket"] > 0): + raise ValueError("invalid run record") + if record.get("state") == "starting" and set(record) == {"state", "ticket"}: + continue + thread = record.get("thread") + if not (set(record) == {"state", "ticket", "thread"} + and record["state"] in ("active", "waking", "stopping", "stopped") + and synthetic_id(thread, "thr_syn-") and thread not in threads): + raise ValueError("invalid run binding") + threads.add(thread) + return runs + + +def start(root, runs, value, provider): + ticket = value["ticket"] + if any(r["ticket"] == ticket and r["state"] != "stopped" for r in runs.values()): + raise Refused("this ticket already has an active or unresolved fixture start", INSPECT) + + checkout = root / fixture.CHECKOUT + checkout.mkdir(exist_ok=True) + if checkout.is_symlink() or not checkout.is_dir(): + raise ValueError("invalid checkout") + run = fixture.new_id("run-") + record = {"ticket": ticket, "state": "starting"} + runs[run] = record + fixture.save(root / "runs.json", runs) + + title = f"#{ticket}: {fixture.REPOSITORY} builder ({run})" + receipt = transport(checkout, [ + "thread", "start", "--json", "--title", title, "--provider", provider, + "--model", value["model"], fixture.PROJECT, "-", + ], f"Build {fixture.REPOSITORY}#{ticket} with the {value['skill']} skill.") + if not (isinstance(receipt, dict) and receipt.keys() == {"threadId", "projectId", "runId"} + and receipt["projectId"] == fixture.PROJECT and synthetic_id(receipt["threadId"], "thr_syn-") + and synthetic_id(receipt["runId"], "t3-run-syn-") + and all(other.get("thread") != receipt["threadId"] for other in runs.values())): + raise Refused("fixture start outcome is unverified", INSPECT) + + record.update(state="active", thread=receipt["threadId"]) + fixture.save(root / "runs.json", runs) + return {"run": run} + + +def send_receipt(receipt, thread): + required = {"threadId", "messageId", "runId", "status", "delivery"} + allowed = required | {"link", "taskId"} + return (isinstance(receipt, dict) and required <= receipt.keys() <= allowed + and receipt["threadId"] == thread and synthetic_id(receipt["messageId"], "message-syn-") + and synthetic_id(receipt["runId"], "t3-run-syn-") + and all(isinstance(receipt.get(key, ""), str) for key in ("link", "taskId")) + and isinstance(receipt["status"], str) and receipt["status"] in ACCEPTED_RUN_STATES + and receipt["delivery"] in ("started", "queued")) + + +def wake(root, runs, run, record): + if record["state"] != "active": + raise Refused("this fixture run cannot be woken", "use an active run or verify termination with stop") + thread = record["thread"] + if not synthetic_id(thread, "thr_syn-"): + raise ValueError("invalid fixture thread") + # Fence retries before dispatch. An unverified send can still have queued work. + record["state"] = "waking" + fixture.save(root / "runs.json", runs) + receipt = transport( + root, ["thread", "send", "--json", thread, "-"], + f"Read {fixture.REPOSITORY}#{record['ticket']} again and edit your existing status note.", + ) + if not send_receipt(receipt, thread): + raise Refused("fixture wake outcome is unverified", "inspect the fixture state or stop this run") + record["state"] = "active" + fixture.save(root / "runs.json", runs) + return {"run": run, "woke": True} + + +def stop(root, runs, run, record): + if record["state"] == "stopped": + return {"run": run, "stopped": True} + thread = record.get("thread") + if not synthetic_id(thread, "thr_syn-"): + raise Refused("the fixture thread for this run is unverified", INSPECT) + + # Fence additional wakes even when termination is incomplete. + record["state"] = "stopping" + fixture.save(root / "runs.json", runs) + receipt = transport(root, ["terminate-fixture", thread]) + expected = {"threadId": thread, "activeRunId": None, "pendingMessages": 0, "remainingWork": [], "preserved": True} + if (receipt != expected or type(receipt["pendingMessages"]) is not int or receipt["preserved"] is not True): + raise Refused("fixture termination is unverified", "inspect the fixture work and retry stop on this run") + record["state"] = "stopped" + fixture.save(root / "runs.json", runs) + return {"run": run, "stopped": True} + + +def main(words): + if len(words) != 1 or words[0] not in {*VERSION["can"], "version", "schema"}: + raise Refused("unknown driver command", "use version, schema, start, wake or stop") + command = words[0] + if command == "version": + return VERSION + if command == "schema": + sys.stdout.buffer.write(SCHEMA.read_bytes()) + return None + + value = request(command) + if command == "start": + if value["repository"] != fixture.REPOSITORY: + raise Refused("repository has no fixture project", "use the pinned example/site repository") + provider = fixture.PROVIDERS.get((value["harness"], value["model"])) + if provider is None: + raise Refused("harness and model have no fixture provider instance", "use the pinned codex and gpt-6.2-sol") + if "effort" in value: + raise Refused(f"T3 0.1.11 cannot verify effort {value['effort']} for {value['harness']}", CANT_SET_EFFORT) + root = fixture.directory() + with fixture.lock(root / "driver.lock"): + runs = load_runs(root) + if command == "start": + return start(root, runs, value, provider) + run = value["run"] + if run not in runs: + raise Refused("unknown fixture run", "use a run id returned by start in this disposable state") + return (wake if command == "wake" else stop)(root, runs, run, runs[run]) + + +if __name__ == "__main__": + try: + try: + answer = main(sys.argv[1:]) + except (OSError, ValueError, KeyError, TypeError, RecursionError): + raise Refused("fixture state is unavailable or unreadable", + "use an existing private openwiz-t3-fixture directory in the system temp folder") + except Refused as error: + print(json.dumps(dict(zip(("error", "next"), error.args)))) + sys.exit(1) + if answer is not None: + print(json.dumps(answer)) diff --git a/prototypes/t3/fixture.py b/prototypes/t3/fixture.py new file mode 100644 index 00000000..554ef8aa --- /dev/null +++ b/prototypes/t3/fixture.py @@ -0,0 +1,231 @@ +"""Pinned fake T3 transport. All its work and ticket notes are local JSON.""" +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import re +import stat +import sys +import tempfile +import uuid + +PREFIX = "openwiz-t3-fixture-" +REPOSITORY = "example/site" +PROJECT = "prj_syn-openwiz" +CHECKOUT = "checkout" +PROVIDERS = {("codex", "gpt-6.2-sol"): "instance-syn-codex"} +AUTHOR = "example-bot[bot]" +RUN_WORK = ("provider", "terminal", "delegated-child") + + +def new_id(prefix): + return prefix + uuid.uuid4().hex + + +def unique(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("repeated key") + result[key] = value + return result + + +def directory(): + path = Path(os.environ.get("OPENWIZ_T3_FIXTURE_DIR", "")) + info = path.lstat() + if not (path.is_absolute() and path.name.startswith(PREFIX) + and path.parent.resolve() == Path(tempfile.gettempdir()).resolve() + and stat.S_ISDIR(info.st_mode) and info.st_uid == os.getuid() and not info.st_mode & 0o077): + raise ValueError("invalid fixture directory") + return path.resolve() + + +@contextmanager +def local_file(path, flags): + fd = os.open(path, flags | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) + with os.fdopen(fd) as stream: + info = os.fstat(fd) + if not (stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid() and info.st_nlink == 1): + raise ValueError("invalid fixture file") + yield stream + + +@contextmanager +def lock(path): + with local_file(path, os.O_CREAT | os.O_RDWR) as stream: + fcntl.flock(stream, fcntl.LOCK_EX) + yield + + +def load(path, default): + try: + with local_file(path, os.O_RDONLY) as stream: + return json.load(stream, object_pairs_hook=unique) + except FileNotFoundError: + return default + + +def save(path, value): + temporary = None + try: + with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as stream: + temporary = Path(stream.name) + json.dump(value, stream) + stream.flush() + os.fsync(stream.fileno()) + temporary.replace(path) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + + +def update_note(state, thread): + note_id = thread["note"] + turn = thread["turn"] + now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + model, skill = thread["model"], thread["skill"] + step = "started the throwaway ticket" if turn == 1 else f"woke and read the ticket again (turn {turn})" + body = ("\nagent: builder\nstate: working\n" + f"harness: Codex\nmodel: {model}\nskills: {skill}@0.1.0\nstep: {step}\ntime: {now}\n") + state["notes"][str(note_id)] = {"id": note_id, "author": AUTHOR, "updated_at": now, "body": body} + + +def tracker(root, ticket, state): + comments = [state["notes"][str(thread["note"])] for thread in state["threads"].values() + if thread["ticket"] == ticket] + save(root / f"tracker-{ticket}.json", {"record_authors": [AUTHOR], "comments": comments}) + + +def start(root, state, args, message): + found = re.fullmatch(r"Build example/site#([1-9][0-9]*) with the ([a-z0-9-]+) skill\.", message) + if not (found and args.project == PROJECT and Path.cwd() == root / CHECKOUT + and (args.provider, args.model) in {(i, m) for (_, m), i in PROVIDERS.items()} + and re.fullmatch(rf"#{found[1]}: example/site builder \(run-[0-9a-f]{{32}}\)", args.title)): + raise ValueError("start differs from the fixture map") + + thread_id = new_id("thr_syn-") + run_id = new_id("t3-run-syn-") + thread = { + "ticket": int(found[1]), "skill": found[2], "title": args.title, + "provider": args.provider, "model": args.model, "effort": "host-default", + "project": args.project, "checkout": CHECKOUT, "kind": "top-level", + "active": run_id, "queue": [], "work": list(RUN_WORK), + "note": len(state["notes"]) + 1, "turn": 1, "stopped": False, + } + state["threads"][thread_id] = thread + update_note(state, thread) + return {"threadId": thread_id, "projectId": PROJECT, "runId": run_id}, thread + + +def advance(state, thread): + """Simulate the active turn finishing and its queued successor taking over.""" + if thread["stopped"]: + raise ValueError("fixture run has stopped") + if not thread["queue"]: + thread["active"] = None + thread["work"].clear() + return + thread["work"] = list(RUN_WORK) + thread["active"] = thread["queue"].pop(0)["runId"] + thread["turn"] += 1 + update_note(state, thread) + + +def send(state, thread, args, message, advance_now): + if thread["stopped"] or message != f"Read {REPOSITORY}#{thread['ticket']} again and edit your existing status note.": + raise ValueError("wake differs from the fixture run") + idle = thread["active"] is None + receipt = { + "threadId": args.thread, "messageId": new_id("message-syn-"), "runId": new_id("t3-run-syn-"), + "status": "running" if idle else "queued", "delivery": "started" if idle else "queued", + } + thread["queue"].append({"messageId": receipt["messageId"], "runId": receipt["runId"]}) + if idle or advance_now: + advance(state, thread) + return receipt + + +def terminate_fixture(thread_id, thread, incomplete): + thread["active"] = None + thread["queue"].clear() + thread["work"] = ["delegated-child"] if incomplete else [] + thread["stopped"] = not incomplete + return { + "threadId": thread_id, "activeRunId": thread["active"], "pendingMessages": len(thread["queue"]), + "remainingWork": thread["work"], "preserved": True, + } + + +def thread_command(words): + parser = argparse.ArgumentParser(allow_abbrev=False) + verb = parser.add_subparsers(dest="command", required=True) + launch = verb.add_parser("start", allow_abbrev=False) + for name in ("title", "provider", "model"): + launch.add_argument(f"--{name}", required=True) + launch.add_argument("project") + wake = verb.add_parser("send", allow_abbrev=False) + wake.add_argument("thread") + for command in (launch, wake): + command.add_argument("--json", action="store_true", required=True) + command.add_argument("message", choices=["-"]) + return parser.parse_args(words) + + +def main(words): + root = directory() + fault = os.environ.get("OPENWIZ_T3_FIXTURE_FAULT") + if not words: + raise ValueError("missing fixture operation") + with lock(root / "fixture.lock"): + state = load(root / "host.json", {"threads": {}, "notes": {}, "calls": []}) + if words[0] == "thread": + args = thread_command(words[1:]) + message = sys.stdin.read() + state["calls"].append({"argv": words, "stdin": message, "cwd": Path.cwd().name}) + if args.command == "start": + reply, thread = start(root, state, args, message) + operation = "start" + else: + thread = state["threads"][args.thread] + reply = send(state, thread, args, message, os.environ.get("OPENWIZ_T3_FIXTURE_AUTO_ADVANCE") == "1") + operation = "send" + else: + # These are fixture controls, outside the modeled CLI. + operation, target = words + if operation == "init-tracker": + tracker(root, int(target), state) + return + thread = state["threads"][target] + state["calls"].append({"fixture": words}) + if operation == "advance-fixture": + advance(state, thread) + reply = {"advanced": True} + elif operation == "terminate-fixture": + reply = terminate_fixture(target, thread, fault == "stop-incomplete") + else: + raise ValueError("unknown fixture operation") + + save(root / "host.json", state) + tracker(root, thread["ticket"], state) + if operation == "start" and fault == "start-partial": + reply["runId"] = None + if operation == "start" and fault == "start-failed": + print("synthetic host diagnostic", file=sys.stderr) + return 1 + if operation == "send" and fault == "send-wrong-thread": + reply["threadId"] = new_id("thr_syn-") + if operation == "send" and fault == "send-malformed": + print("unreadable fixture reply") + return + print(json.dumps(reply)) + + +if __name__ == "__main__": + try: + sys.exit(main(sys.argv[1:])) + except (KeyError, OSError, ValueError): + sys.exit("fixture operation failed") diff --git a/prototypes/t3/test_driver.py b/prototypes/t3/test_driver.py new file mode 100644 index 00000000..2d21a4a7 --- /dev/null +++ b/prototypes/t3/test_driver.py @@ -0,0 +1,329 @@ +#!/usr/bin/env python3 +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +from threading import Barrier +import unittest + +HERE = Path(__file__).resolve().parent +SCHEMA = HERE.parents[1] / "kernel" / "driver-kit" / "schema.json" +REQUEST = { + "repository": "example/site", + "ticket": 7, + "skill": "build-ticket", + "harness": "codex", + "model": "gpt-6.2-sol", +} + + +class Lifecycle(unittest.TestCase): + def setUp(self): + workspace = tempfile.TemporaryDirectory(prefix="openwiz-t3-fixture-") + self.addCleanup(workspace.cleanup) + self.state = Path(workspace.name).resolve() + self.env = { + "PATH": os.pathsep.join((str(Path(sys.executable).parent), os.defpath)), + "TMPDIR": tempfile.gettempdir(), + "OPENWIZ_T3_FIXTURE_DIR": str(self.state), + } + + def execute(self, command, payload, *, fault=None, env=None): + entry = HERE / "driver" + call_env = (self.env if env is None else env).copy() + if fault is not None: + call_env["OPENWIZ_T3_FIXTURE_FAULT"] = fault + try: + return subprocess.run( + [str(entry), command], input=payload, capture_output=True, env=call_env, timeout=10, + ) + except FileNotFoundError: + self.fail(f"expected an executable driver for {command}; prototypes/t3/driver is missing") + + def answer(self, result, status): + self.assertEqual(result.returncode, status, (result.stdout, result.stderr)) + self.assertEqual(result.stderr, b"") + response = json.loads(result.stdout) + if status == 1: + self.assertEqual(set(response), {"error", "next"}) + for field in response.values(): + self.assertIsInstance(field, str) + self.assertTrue(0 < len(field) <= 300) + self.assertFalse(any(ord(char) < 32 for char in field)) + return response + + def call(self, command, payload=None, *, status=0, fault=None): + data = b"" if payload is None else json.dumps(payload).encode() + return self.answer(self.execute(command, data, fault=fault), status) + + def state_file(self, name): + return json.loads((self.state / name).read_bytes()) + + def host(self): + return self.state_file("host.json") + + def fixture(self, operation, target): + subprocess.run([sys.executable, "-I", str(HERE / "fixture.py"), operation, str(target)], + env=self.env, capture_output=True, check=True, timeout=10) + + def test_version_and_verbatim_schema(self): + self.assertEqual(self.call("version"), { + "driver": "t3-fixture", "records": ["openwiz:records v1"], "can": ["start", "wake", "stop"], + }) + result = self.execute("schema", b"") + self.assertEqual((result.returncode, result.stdout, result.stderr), (0, SCHEMA.read_bytes(), b"")) + self.call("archive", status=1) + self.assertEqual(list(self.state.iterdir()), []) + + def test_executable_lifecycle(self): + started = self.call("start", REQUEST) + self.assertRegex(started["run"], r"^run-[0-9a-f]{32}$") + self.assertEqual(set(started), {"run"}) + thread_id, thread = next(iter(self.host()["threads"].items())) + title = f"#7: example/site builder ({started['run']})" + self.assertNotEqual(started["run"], thread_id) + self.assertEqual({ + "checkout": thread["checkout"], "project": thread["project"], "kind": thread["kind"], + "provider": thread["provider"], "model": thread["model"], "effort": thread["effort"], + "title": thread["title"], + }, { + "checkout": "checkout", "project": "prj_syn-openwiz", "kind": "top-level", + "provider": "instance-syn-codex", "model": "gpt-6.2-sol", "effort": "host-default", + "title": title, + }) + self.assertEqual(self.host()["calls"], [{ + "argv": ["thread", "start", "--json", "--title", title, + "--provider", "instance-syn-codex", "--model", "gpt-6.2-sol", "prj_syn-openwiz", "-"], + "stdin": "Build example/site#7 with the build-ticket skill.", "cwd": "checkout", + }]) + note, = self.state_file("tracker-7.json")["comments"] + self.assertEqual(note["id"], thread["note"]) + self.assertIn("skills: build-ticket@", note["body"]) + + self.assertEqual(self.call("wake", started), {**started, "woke": True}) + self.assertEqual(self.host()["calls"][-1], { + "argv": ["thread", "send", "--json", thread_id, "-"], + "stdin": "Read example/site#7 again and edit your existing status note.", "cwd": self.state.name, + }) + threads = self.host()["threads"] + self.assertEqual(set(threads), {thread_id}) + queued, = threads[thread_id]["queue"] + self.assertEqual(threads[thread_id]["active"], thread["active"]) + self.assertNotEqual(queued["runId"], thread["active"]) + self.assertEqual(self.state_file("tracker-7.json")["comments"], [note]) + self.fixture("advance-fixture", thread_id) + self.assertEqual(self.host()["threads"][thread_id]["active"], queued["runId"]) + edited, = self.state_file("tracker-7.json")["comments"] + self.assertEqual(edited["id"], note["id"]) + self.assertNotEqual(edited["body"], note["body"]) + + self.call("wake", started) + unrelated = self.call("start", {**REQUEST, "ticket": 8}) + unrelated_id = self.state_file("runs.json")[unrelated["run"]]["thread"] + unrelated_before = self.host()["threads"][unrelated_id] + unrelated_tracker = self.state_file("tracker-8.json") + expected_stop = {**started, "stopped": True} + self.assertEqual(self.call("stop", started), expected_stop) + host = self.host() + stopped = host["threads"][thread_id] + self.assertTrue(stopped["stopped"]) + self.assertIsNone(stopped["active"]) + self.assertEqual((stopped["work"], stopped["queue"]), ([], [])) + self.assertEqual(stopped["note"], edited["id"]) + self.assertEqual(self.state_file("tracker-7.json")["comments"], [edited]) + self.assertEqual(host["threads"][unrelated_id], unrelated_before) + self.assertEqual(self.state_file("tracker-8.json"), unrelated_tracker) + self.assertEqual(self.call("stop", started), expected_stop) + self.assertIn("error", self.call("wake", started, status=1)) + self.assertEqual(self.host(), host) + self.call("wake", unrelated) + self.call("stop", unrelated) + + fresh = self.call("start", REQUEST) + self.assertNotEqual(fresh, started) + fresh_id = self.state_file("runs.json")[fresh["run"]]["thread"] + self.assertEqual(self.host()["threads"][fresh_id]["title"], f"#7: example/site builder ({fresh['run']})") + self.call("stop", fresh) + + def test_invalid_requests_never_touch_fixture(self): + raw = json.dumps(REQUEST).encode() + invalid_starts = [ + b"[" * 2000 + b"]" * 2000, b"", b"[]", b"null", b"{}", b"\xff", raw + b"{}", + raw[:-1] + b', "ticket": 7}', raw[:-1] + b', "token": "fake-canary"}', + ] + for fields in [ + {"ticket": True}, {"ticket": 7.0}, {"ticket": "7"}, {"ticket": 0}, {"ticket": float("nan")}, + {"skill": "bad skill"}, {"harness": "codex\n"}, {"repository": "invalid"}, + {"model": []}, {"effort": False}, {"effort": "Medium"}, {"model": "a" * 101}, + ]: + invalid_starts.append(json.dumps({**REQUEST, **fields}).encode()) + for invalid in invalid_starts: + with self.subTest(input=invalid): + self.answer(self.execute("start", invalid), 1) + for command in ("wake", "stop"): + for invalid in (b'{"run":true}', b'{"run":"a","run":"b"}', b'{"run":"a","extra":1}', b'{"run":"a/b"}'): + self.answer(self.execute(command, invalid), 1) + self.assertEqual(list(self.state.iterdir()), []) + + def test_mapping_and_effort_refusal(self): + for fields in ( + {"repository": "example/another"}, {"harness": "another"}, {"model": "another"}, + ): + self.assertIn("no fixture", self.call("start", {**REQUEST, **fields}, status=1)["error"]) + refused = self.call("start", {**REQUEST, "effort": "medium"}, status=1) + self.assertIn("effort medium for codex", refused["error"]) + self.assertEqual(refused["next"], + "this host can't set effort: remove the effort for this harness in your Models table " + "or Roster to run it at the host's default") + self.assertEqual(list(self.state.iterdir()), []) + + def test_credential_shaped_fields_are_refused_privately(self): + canary = "sk-" + "a" * 16 + for name in ("skill", "effort"): + response = self.execute("start", json.dumps({**REQUEST, name: canary}).encode()) + self.assertNotIn(canary.encode(), response.stdout + response.stderr) + self.answer(response, 1) + self.assertEqual(list(self.state.iterdir()), []) + + def test_malformed_state_returns_a_v1_error(self): + for value in ([], {"run-invalid": {}}, {"run-" + "0" * 32: {"ticket": True, "state": "active"}}): + (self.state / "runs.json").write_text(json.dumps(value)) + self.call("start", REQUEST, status=1) + self.assertFalse((self.state / "host.json").exists()) + + def test_idle_wake_starts_a_turn_and_edits_the_current_note(self): + started = self.call("start", REQUEST) + thread_id, = self.host()["threads"] + self.fixture("advance-fixture", thread_id) + self.assertIsNone(self.host()["threads"][thread_id]["active"]) + self.call("wake", started) + thread = self.host()["threads"][thread_id] + self.assertIsNotNone(thread["active"]) + self.assertEqual((thread["turn"], thread["queue"]), (2, [])) + note, = self.state_file("tracker-7.json")["comments"] + self.assertEqual(note["id"], thread["note"]) + updated = datetime.fromisoformat(note["updated_at"].replace("Z", "+00:00")) + self.assertLess(abs((datetime.now(timezone.utc) - updated).total_seconds()), 60) + self.call("stop", started) + + def test_stop_survives_a_missing_or_replaced_checkout(self): + checkout = self.state / "checkout" + for ticket in (7, 8): + started = self.call("start", {**REQUEST, "ticket": ticket}) + checkout.rmdir() + if ticket == 8: + checkout.symlink_to(self.state, target_is_directory=True) + for _ in range(2): + self.assertEqual(self.call("stop", started), {**started, "stopped": True}) + stopped = self.host()["threads"][self.state_file("runs.json")[started["run"]]["thread"]] + self.assertEqual(stopped["work"], []) + + def test_missing_or_symlinked_workspace(self): + raw = json.dumps(REQUEST).encode() + env = self.env.copy() + del env["OPENWIZ_T3_FIXTURE_DIR"] + self.answer(self.execute("start", raw, env=env), 1) + (self.state / "driver.lock").symlink_to(SCHEMA) + self.answer(self.execute("start", raw), 1) + self.assertEqual(list(self.state.iterdir()), [self.state / "driver.lock"]) + + def test_unknown_run_never_reaches_fixture(self): + for command in ("wake", "stop"): + response = self.call(command, {"run": "run-unknown"}, status=1) + self.assertIn("unknown fixture run", response["error"]) + self.assertFalse((self.state / "host.json").exists()) + + def test_ambiguous_starts_are_fenced(self): + for ticket, fault in enumerate(("start-partial", "start-failed"), start=7): + with self.subTest(fault=fault): + payload = {**REQUEST, "ticket": ticket} + answer = self.call("start", payload, fault=fault, status=1) + self.assertIn("unverified", answer["error"]) + self.assertNotIn("diagnostic", json.dumps(answer)) + host = self.host() + self.assertEqual(len(host["threads"]), ticket - 6) + self.assertIn("unresolved", self.call("start", payload, status=1)["error"]) + self.assertEqual(self.host(), host) + + def test_ambiguous_wake_is_fenced_but_stop_is_possible(self): + for ticket, fault in enumerate(("send-wrong-thread", "send-malformed"), start=7): + with self.subTest(fault=fault): + started = self.call("start", {**REQUEST, "ticket": ticket}) + thread_id = self.state_file("runs.json")[started["run"]]["thread"] + answer = self.call("wake", started, fault=fault, status=1) + self.assertIn("unverified", answer["error"]) + host = self.host() + self.assertEqual(len(host["threads"][thread_id]["queue"]), 1) + self.call("wake", started, status=1) + self.assertEqual(self.host(), host) + self.call("stop", started) + self.assertEqual(self.host()["threads"][thread_id]["queue"], []) + + def test_stop_requires_verified_child_cleanup(self): + started = self.call("start", REQUEST) + self.call("wake", started) + refused = self.call("stop", started, fault="stop-incomplete", status=1) + self.assertIn("termination is unverified", refused["error"]) + host = self.host() + thread, = host["threads"].values() + self.assertEqual(thread["work"], ["delegated-child"]) + self.assertFalse(thread["stopped"]) + self.call("wake", started, status=1) + self.assertEqual(self.host(), host) + self.assertEqual(self.call("stop", started), {**started, "stopped": True}) + thread, = self.host()["threads"].values() + self.assertEqual(thread["work"], []) + self.assertTrue(thread["stopped"]) + + def race(self, requests): + ready = Barrier(len(requests)) + + def invoke(request): + command, value = request + ready.wait(timeout=10) + return self.execute(command, json.dumps(value).encode()) + + with ThreadPoolExecutor(max_workers=len(requests)) as workers: + return list(workers.map(invoke, requests)) + + def test_concurrent_start_keeps_one_thread(self): + results = self.race([("start", REQUEST)] * 4) + self.assertEqual(sorted(result.returncode for result in results), [0, 1, 1, 1]) + started = self.answer(next(result for result in results if result.returncode == 0), 0) + self.assertEqual(len(self.host()["threads"]), 1) + self.call("stop", started) + + def test_each_acknowledged_wake_queues_one_followup(self): + started = self.call("start", REQUEST) + for result in self.race([("wake", started)] * 4): + self.assertEqual(self.answer(result, 0), {**started, "woke": True}) + host = self.host() + self.assertEqual([call["argv"][1] for call in host["calls"]], ["start"] + ["send"] * 4) + thread, = host["threads"].values() + self.assertEqual(len({message["messageId"] for message in thread["queue"]}), 4) + self.call("stop", started) + + def test_concurrent_wake_and_stop_never_send_after_stop(self): + started = self.call("start", REQUEST) + results = self.race([("wake", started), ("stop", started), ("wake", started), ("stop", started)]) + for result in results[1::2]: + self.assertEqual(self.answer(result, 0), {**started, "stopped": True}) + for result in results[::2]: + self.assertIn(result.returncode, (0, 1)) + self.answer(result, result.returncode) + host = self.host() + thread, = host["threads"].values() + self.assertEqual((thread["stopped"], thread["queue"], thread["work"]), (True, [], [])) + kinds = [call["argv"][1] if "argv" in call else call["fixture"][0] for call in host["calls"]] + wakes = sum(result.returncode == 0 for result in results[::2]) + self.assertEqual(kinds, ["start"] + ["send"] * wakes + ["terminate-fixture"]) + self.call("wake", started, status=1) + self.assertEqual(self.host(), host) + + +if __name__ == "__main__": + unittest.main()