Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions prototypes/t3/README.md
Original file line number Diff line number Diff line change
@@ -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 (<run>)`. 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.
216 changes: 216 additions & 0 deletions prototypes/t3/driver
Original file line number Diff line number Diff line change
@@ -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))
Loading