From ddf453739354a90354a3c9047c85dab84c0aa058 Mon Sep 17 00:00:00 2001 From: OpenWiz Builder Date: Thu, 26 Nov 2026 21:15:36 +0000 Subject: [PATCH 1/2] Bring the Capy driver onto current main and match the kit effort line. Co-authored-by: Jake Parker --- adapters/capy/README.md | 23 ++ adapters/capy/driver | 263 +++++++++++++ .../capy/evidence/green-key-host-pass.txt | 24 ++ adapters/capy/evidence/green-kit.txt | 7 + adapters/capy/evidence/green.txt | 28 ++ adapters/capy/evidence/red-effort.txt | 63 ++++ adapters/capy/evidence/red-fail-closed.txt | 128 +++++++ adapters/capy/evidence/red-kit.txt | 7 + adapters/capy/evidence/red-project.txt | 19 + adapters/capy/evidence/red.txt | 30 ++ adapters/capy/fixtures/fake_capy.py | 181 +++++++++ adapters/capy/fixtures/kit-host.json | 110 ++++++ adapters/capy/release.json | 1 + adapters/capy/schema.json | 219 +++++++++++ adapters/capy/test_driver.py | 345 ++++++++++++++++++ changes/2579.md | 3 + kernel/driver-kit/hosts.json | 6 + 17 files changed, 1457 insertions(+) create mode 100644 adapters/capy/README.md create mode 100755 adapters/capy/driver create mode 100644 adapters/capy/evidence/green-key-host-pass.txt create mode 100644 adapters/capy/evidence/green-kit.txt create mode 100644 adapters/capy/evidence/green.txt create mode 100644 adapters/capy/evidence/red-effort.txt create mode 100644 adapters/capy/evidence/red-fail-closed.txt create mode 100644 adapters/capy/evidence/red-kit.txt create mode 100644 adapters/capy/evidence/red-project.txt create mode 100644 adapters/capy/evidence/red.txt create mode 100644 adapters/capy/fixtures/fake_capy.py create mode 100644 adapters/capy/fixtures/kit-host.json create mode 100644 adapters/capy/release.json create mode 100644 adapters/capy/schema.json create mode 100755 adapters/capy/test_driver.py create mode 100644 changes/2579.md diff --git a/adapters/capy/README.md b/adapters/capy/README.md new file mode 100644 index 000000000..d49378f49 --- /dev/null +++ b/adapters/capy/README.md @@ -0,0 +1,23 @@ +# Capy driver + +Login: held by Capy + +Effort: passed as the run's Capy `reasoningMode`; an effort the run's model doesn't offer is refused with driver v1's effort refusal, and nothing starts + +The key is your `CAPY_API_KEY`, or the keychain entry `openwiz-capy`; only the kit's key helper reads it. + +- OpenWiz never stores the key. To revoke OpenWiz's access, remove it from your environment or your keychain (or revoke it in Capy's Settings, API). +- The harness login (Claude Code or Codex) is a secret held by Capy: the subscription you connect in Capy's Settings, Models. The run names it by its model; OpenWiz never passes it. +- **What a run bills:** model tokens go to the first connection in your Capy order that serves the run's model, so a connected Claude Code or Codex subscription pays for them, and with none, your Capy credits do. The run's machine time uses your plan's included machine minutes first, then your Capy balance, separately from model tokens ([Capy's Models & pricing page](https://docs.capy.ai/models-and-pricing)). + +A [driver v1](../../kernel/driver.v1.md) for [Capy](https://capy.ai). **Platforms:** Linux and macOS, Python 3.9 or later, standard library only. Every call to Capy goes through the [key helper](../../kernel/driver-kit/README.md#key-hosts) (driver v1 N4), as host `capy` of `kernel/driver-kit/hosts.json`: the driver sends only a method, a path and a body, never a key or an address. + +- **`start`** runs the ticket in the Capy project `CAPY_PROJECT_ID` names, when you set it (a project id from Capy's Settings, Projects & setup; not a credential), or else in the one project that lists the repository (`GET /api/v1/projects`). With neither, or with more than one project listing it, it refuses and names `CAPY_PROJECT_ID`; it never guesses a project. It creates a thread there (`POST /api/v1/threads`) with the ticket's prompt and the model `anthropic/` for `claude` or `claude-code`, or `openai/` for `codex`, and answers the thread's id as the run. A create whose answer is lost is sent once more with the same `requestId`, which Capy turns into the same thread. An effort outside Capy's `reasoningMode` values (`none`, `instant`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`) is refused with driver v1's effort refusal before any call. When Capy refuses the model, the driver reads your models (`GET /api/v1/models`) to say why, and says it is unsure when that list is unreadable. +- **`wake`** reads the thread (`GET /api/v1/threads/`) and steers a follow-up into it (`POST /api/v1/threads//message`). A message would unarchive a stopped thread, so a wake of an archived one is refused before anything is sent. +- **`stop`** interrupts the thread (`POST /api/v1/threads//interrupt`), then archives it (`POST /api/v1/threads//archive`). Stopping an archived thread answers again. + +The driver keeps no state of its own: Capy holds every run. It reads each Capy answer only in the shape [Capy's OpenAPI document](https://docs.capy.ai/openapi.json) gives it (every required field, no unlisted one, the thread's own id, its documented status and a Boolean `archived`). Any other answer is refused, and the error names the run when one may exist: a run is unknown only on Capy's own `ThreadNotFound` for that id, a wake or a stop succeeds only on Capy's receipt for each write, a project is picked only from a readable project list, and a start answers only a thread for the project it sent (or none named). + +Keep `schema.json` byte for byte the kit's `kernel/driver-kit/schema.json`: the kit checks it. + +Its own tests, Linux only (their cleanup reads `/proc`), on a fake Capy (`fixtures/fake_capy.py`, built from Capy's OpenAPI document) reached through the helper's loopback test override: `python3 -I adapters/capy/test_driver.py` (they set `OPENWIZ_CAPY_POLL`, the seconds before a lost create is sent again, default 3). On the real host, with `CAPY_PROJECT_ID` set (the kit's key check runs `start` against a fake host that can't list your repository): `CAPY_PROJECT_ID= python3 -I kernel/driver-kit/kit.py --driver adapters/capy/driver --repo / --ticket --harness claude-code --model `. diff --git a/adapters/capy/driver b/adapters/capy/driver new file mode 100755 index 000000000..db6698940 --- /dev/null +++ b/adapters/capy/driver @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +# SECURITY: driver v1 N4. Every Capy call goes through the kit's key helper, which alone reads the key and picks the +# address; this driver sends it only a host name, a method, a path and a body, and never names, reads or prints the +# key. It shows no text the host answered: each error names only the status, the method and the path. +import json, os, re, subprocess, sys, time, uuid +sys.dont_write_bytecode = True + +HERE = os.path.dirname(os.path.abspath(__file__)) +HELPER = os.path.realpath(os.path.join(HERE, '..', '..', 'kernel', 'driver-kit', 'hostkey.py')) +HOST = 'capy' +VERSION = {'driver': 'capy', 'records': ['openwiz:records v1'], 'can': ['start', 'wake', 'stop', 'effort']} +START = {'repository': r'[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}', 'ticket': None, + 'skill': r'(?=.{1,60}$)[a-z0-9]+(-[a-z0-9]+)*', 'harness': r'[a-z0-9][a-z0-9._-]{0,59}', + 'model': r'[A-Za-z0-9][A-Za-z0-9 ._:@+-]{0,59}'} +RUN = {'run': r'[A-Za-z0-9][A-Za-z0-9_-]{0,99}'} +EFFORT = r'[a-z][a-z0-9-]{0,19}' +PROJECT = r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,190}' +PROVIDERS = {'claude': 'anthropic', 'claude-code': 'anthropic', 'codex': 'openai'} +POLL = float(os.environ.get('OPENWIZ_CAPY_POLL') or 3) +NO_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") +WOKEN = 'You were woken: read the ticket again and carry on.' +STOPPED = 'start a new run' +UNSURE = 'open the run in Capy to see its state, then retry' +# External: the shapes below are Capy's documented answers (https://docs.capy.ai/openapi.json): every field a +# schema requires, and no field it doesn't list. An answer off its shape is never read as success or absence. +REASONING = ('none', 'instant', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max') +STATUSES = ('working', 'waiting', 'idle', 'failed', 'archived') +THREAD = set('id projectId authorId previousAuthorId title titleCustom status archived lastModelId queuedAt linearIssue ' + 'pullRequestAuthor usage createdAt updatedAt lastActivityAt hasUnreads mentionCount owed member'.split()) +THREAD_MAY = set('modelDefault needsYou ask crewNeedsYou participated crewMentionCount captain crewCount subscribed ' + 'personal visibility'.split()) +PROJECT_KEYS = set('id name description code visibility repos createdAt updatedAt'.split()) +MODEL_KEYS = set('id name billing route reasoningModes fast pro ultrafast'.split()) +REJECTED_MAY = {'rejection', 'modelId', 'service', 'health'} + + +class Refused(Exception): + pass + + +def unique(pairs): + if len({k for k, _ in pairs}) != len(pairs): + raise Refused('a key is repeated', 'send each key once') + return dict(pairs) + + +def read(fields): + try: + req = json.loads(sys.stdin.read(), object_pairs_hook=unique) + except ValueError: + raise Refused('the input is not JSON', 'send one JSON object on stdin, as `driver schema` shows') + optional = {'effort': EFFORT} if fields is START else {} + if not isinstance(req, dict) or not set(fields) <= set(req) <= set(fields) | set(optional): + raise Refused('the input needs exactly ' + ', '.join(fields) + (', and optionally effort' if optional else ''), + 'send only those fields; never a login') + for key, pattern in dict(fields, **optional).items(): + if key not in req: + continue + v = req[key] + if not (type(v) is int and v > 0 if pattern is None else isinstance(v, str) and re.fullmatch(pattern, v)): + raise Refused(key + ' is not valid', 'fix ' + key + ' as `driver schema` shows') + return req + + +def ask(method, path, body=None, also=()): + request = {'host': HOST, 'method': method, 'path': path} + if body is not None: + request['body'] = body + try: + p = subprocess.run([sys.executable, '-I', HELPER], input=json.dumps(request), capture_output=True, + text=True, timeout=110) + out = json.loads(p.stdout) + except (OSError, subprocess.TimeoutExpired, ValueError): + raise Refused('the key helper gave no answer', 'run kernel/driver-kit/hostkey.py by hand to see why') + if p.returncode: + raise Refused('the key helper refused: ' + out['error'], out['next']) + if not (200 <= out['status'] < 300 or out['status'] in also): + raise Refused('Capy answered %d to %s %s' % (out['status'], method, path), + 'check your key and Capy\'s status, then retry') + return out['status'], out['body'] + + +def obj(value): + return value if isinstance(value, dict) else {} + + +def shaped(value, required, may=()): + return isinstance(value, dict) and set(required) <= set(value) <= set(required) | set(may) + + +def fit(line, fallback): + return line if len(line) <= 300 else fallback + + +def a_thread(value, run, receipt=()): + # External: an archived thread doesn't run (https://docs.capy.ai/threads#archive-a-thread), so a running archived one + # is not a state the driver can read. + if not (shaped(value, THREAD | set(receipt), THREAD_MAY) and value['id'] == run and value['status'] in STATUSES + and type(value['archived']) is bool and (value['projectId'] is None or isinstance(value['projectId'], str))): + return None + if value['archived'] and value['status'] in ('working', 'waiting') or value['status'] == 'archived' and not value[ + 'archived']: + return None + return value + + +def admitted(status, value): + return status == 200 and shaped(value, {'id', 'deduped'}) and isinstance(value['id'], str) and len( + value['id']) == 26 and type(value['deduped']) is bool + + +def no_effort(req): + return Refused('Capy cannot run %s (model %s) at effort %s' % (req['harness'], req['model'], req['effort']), + NO_EFFORT) + + +def project(repository): + chosen = os.environ.get('CAPY_PROJECT_ID') + if chosen is not None: + if not re.fullmatch(PROJECT, chosen): + raise Refused('CAPY_PROJECT_ID is not a Capy project id', + 'set CAPY_PROJECT_ID to a project id from Capy\'s Settings, Projects & setup, or unset it') + return chosen + status, listed = ask('GET', '/api/v1/projects') + items = listed['items'] if status == 200 and shaped(listed, {'items'}) else None + if not (isinstance(items, list) and all( + shaped(p, PROJECT_KEYS) and isinstance(p['id'], str) and re.fullmatch(PROJECT, p['id']) + and isinstance(p['repos'], list) and all( + shaped(r, {'repoFullName', 'baseBranch', 'mode'}) and isinstance(r['repoFullName'], str) + and isinstance(r['baseBranch'], str) and r['mode'] in ('primary', 'lazy') for r in p['repos']) + for p in items)): + raise Refused('Capy answered GET /api/v1/projects in a shape the driver cannot read', + 'set CAPY_PROJECT_ID to the project to run it in (Settings, Projects & setup), then start again') + lists = [p['id'] for p in items if any(r['repoFullName'].lower() == repository.lower() for r in p['repos'])] + if len(lists) > 1: + raise Refused('more than one Capy project lists ' + repository, + 'set CAPY_PROJECT_ID to the project to run it in, then start again') + if not lists: + raise Refused('no Capy project lists ' + repository, + 'add the repository to one Capy project (Settings, Projects & setup), or set CAPY_PROJECT_ID to ' + 'the project to run it in, then start again') + return lists[0] + + +def rejected(req, model): + status, listed = ask('GET', '/api/v1/models') + items = listed['items'] if status == 200 and shaped(listed, {'items', 'default'}) and isinstance( + listed['default'], dict) else None + found = [m for m in items if shaped(m, MODEL_KEYS) and m['id'] == model['modelId']] if isinstance( + items, list) and all(shaped(m, MODEL_KEYS) and isinstance(m['id'], str) and isinstance( + m['reasoningModes'], list) and all(r in REASONING for r in m['reasoningModes']) for m in items) else None + if found is None or len(found) > 1: + raise Refused('Capy refused model %s%s, and answered GET /api/v1/models in a shape the driver cannot read' + % (model['modelId'], ' at effort ' + req['effort'] if 'effort' in req else ''), + 'check the model and its effort in Capy\'s Settings, Models, then start again') + if found and 'reasoningMode' in model and model['reasoningMode'] not in found[0]['reasoningModes']: + raise no_effort(req) + raise Refused('Capy cannot run model %s for this key' % model['modelId'], + 'pick a model Capy lists for your key (Settings, Models), or connect the subscription that serves ' + 'it, then start again') + + +def create(req): + model = {'modelId': '%s/%s' % (PROVIDERS[req['harness']], req['model'])} + if 'effort' in req: + if req['effort'] not in REASONING: + raise no_effort(req) + model['reasoningMode'] = req['effort'] + title = 'OpenWiz: %s#%d' % (req['repository'], req['ticket']) + # External: a resent create with the same requestId converges on the same Capy thread, never a second billable + # run (https://docs.capy.ai/api-reference/overview#idempotency). + body = {'requestId': str(uuid.uuid4()), 'projectId': project(req['repository']), 'title': title, + 'message': 'Build the ticket: %s#%d, with the %s skill.' % (req['repository'], req['ticket'], req['skill']), + 'model': model} + lost = fit('archive the Capy thread titled %s if it is there, then start again' % title, + 'archive the Capy thread titled OpenWiz: # if it is there, then start again') + for attempt in (1, 2): + try: + status, got = ask('POST', '/api/v1/threads', body, also=tuple(range(400, 600))) + except Refused as e: + status, why = None, e.args[0] + if status == 400 and shaped(got, {'_tag', 'message', 'candidates'}, REJECTED_MAY) and got[ + '_tag'] == 'ModelSelection.Rejected': + rejected(req, model) + if status is not None and status < 300: + break + if status is not None and status != 429 and status < 500: + raise Refused('Capy answered %d to POST /api/v1/threads' % status, + 'check your key, your Capy project and the start\'s fields, then start again') + why = why if status is None else 'Capy answered %d to POST /api/v1/threads' % status + if attempt == 2: + raise Refused(why + ', so a thread may have started', lost) + time.sleep(POLL) + run = obj(got).get('id') + run = run if isinstance(run, str) and re.fullmatch(RUN['run'], run) else None + found = a_thread(got, run) if run and status == 200 else None + if not found or found['projectId'] not in (None, body['projectId']) or found['archived']: + raise Refused('Capy answered POST /api/v1/threads in a shape the driver cannot read, so %s may have started' + % ('thread ' + run if run else 'a thread'), lost) + return run + + +def thread(run): + status, found = ask('GET', '/api/v1/threads/' + run, also=(404,)) + if status == 404 and found == {'_tag': 'capy/ThreadNotFound', 'threadId': run}: + raise Refused('Capy has no run ' + run, STOPPED) + if status != 200 or not a_thread(found, run): + raise Refused('Capy answered %d to GET /api/v1/threads/%s in a shape the driver cannot read' % (status, run), + UNSURE) + return found + + +def answer(cmd): + if cmd == 'version': + return VERSION + if cmd == 'schema': + with open(os.path.join(HERE, 'schema.json')) as f: + return json.load(f) + if cmd == 'start': + req = read(START) + if req['harness'] not in PROVIDERS: + raise Refused('harness %s is not one Capy runs for OpenWiz' % req['harness'], + 'use claude-code (or claude) or codex') + return {'run': create(req)} + if cmd == 'wake': + run = read(RUN)['run'] + found = thread(run) + # External: a message unarchives and wakes an archived Capy thread + # (https://docs.capy.ai/threads#archive-is-dormant). + if found['archived']: + raise Refused('run %s is stopped' % run, STOPPED) + if not admitted(*ask('POST', '/api/v1/threads/%s/message' % run, {'text': WOKEN, 'delivery': 'steer'})): + raise Refused('Capy did not confirm it took the wake for run ' + run, + 'open the run in Capy to see if the message arrived before you wake it again') + return {'run': run, 'woke': True} + if cmd == 'stop': + run = read(RUN)['run'] + if not thread(run)['archived']: + if not admitted(*ask('POST', '/api/v1/threads/%s/interrupt' % run)): + raise Refused('Capy did not confirm it interrupted run %s, so it may still be running' % run, + 'stop the run in Capy itself, then stop it here again') + status, got = ask('POST', '/api/v1/threads/%s/archive' % run) + if not (status == 200 and a_thread(got, run, {'automation'}) and got['archived']): + raise Refused('Capy did not confirm it archived run ' + run, + 'archive the run in Capy itself, then stop it here again') + return {'run': run, 'stopped': True} + raise Refused('unknown command', 'run one of: version, schema, start, wake, stop') + + +def main(): + try: + out, code = answer(sys.argv[1] if len(sys.argv) == 2 else ''), 0 + except Refused as e: + out, code = {'error': e.args[0], 'next': e.args[1]}, 1 + except Exception as e: + out, code = {'error': 'the driver failed: ' + type(e).__name__, 'next': 'read its code, fix it, retry'}, 1 + print(json.dumps(out)) + sys.exit(code) + + +if __name__ == '__main__': + main() diff --git a/adapters/capy/evidence/green-key-host-pass.txt b/adapters/capy/evidence/green-key-host-pass.txt new file mode 100644 index 000000000..b58a4d589 --- /dev/null +++ b/adapters/capy/evidence/green-key-host-pass.txt @@ -0,0 +1,24 @@ +Fixture checks after merging main at 343bcbbbcfce018bf698e47bddeb084d84956c33. +All suites and the kit ran behind 35 refusing agent CLI stubs with OPENWIZ_GITHUB_APP_KEY unset. + +$ env -u OPENWIZ_GITHUB_APP_KEY python3 -I adapters/capy/test_driver.py +15/15 passed. + +$ env -u OPENWIZ_GITHUB_APP_KEY python3 -I kernel/driver-kit/test_kit.py +26/26 passed. + +$ env -u OPENWIZ_GITHUB_APP_KEY python3 -I kernel/driver-kit/test_hostkey.py +25/25 passed. + +$ env -u OPENWIZ_GITHUB_APP_KEY python3 -I tools/release/test_product_identity.py +25/25 passed. + +$ env -u OPENWIZ_GITHUB_APP_KEY python3 -I tools/release/test_package.py Package.test_runtime_carries_exactly_the_selected_drivers_and_kit_where_the_caller_finds_them +1/1 passed. + +Standalone driver kit on fake Capy with CAPY_PROJECT_ID=project_synthetic1: +pass version: openwiz:records v1, and the schema is driver v1 +pass start: the run posted builder status note 2 +pass wake: the run edited builder status note 2 +pass stop: the run ended, and a wake after it is refused +pass token: no login or token passed through the driver, and on start, wake and stop the capy key reached its host only from the key helper, in its header diff --git a/adapters/capy/evidence/green-kit.txt b/adapters/capy/evidence/green-kit.txt new file mode 100644 index 000000000..7d96f825d --- /dev/null +++ b/adapters/capy/evidence/green-kit.txt @@ -0,0 +1,7 @@ +$ CAPY_PROJECT_ID=project_synthetic1 python3 -I kernel/driver-kit/kit.py --driver adapters/capy/driver --repo example/site --ticket 7 --harness claude-code --model claude-synthetic-1 --tracker --wait 8, on the fake Capy (agent CLI stubs first on PATH) +pass version: openwiz:records v1, and the schema is driver v1 +pass start: the run posted builder status note 1 +pass wake: the run edited builder status note 1 +pass stop: the run ended, and a wake after it is refused +pass token: no login or token passed through the driver, and on start, wake and stop the capy key reached its host only from the key helper, in its header +exit 0 diff --git a/adapters/capy/evidence/green.txt b/adapters/capy/evidence/green.txt new file mode 100644 index 000000000..ae7f5f0f5 --- /dev/null +++ b/adapters/capy/evidence/green.txt @@ -0,0 +1,28 @@ +$ env -u OPENWIZ_GITHUB_APP_KEY python3 -I adapters/capy/test_driver.py -v (35 refusing agent CLI stubs first on PATH; synthetic fake Capy on loopback) +test_a_create_receipt_off_its_shape_or_for_another_project_is_a_possible_start (__main__.Driver.test_a_create_receipt_off_its_shape_or_for_another_project_is_a_possible_start) ... ok +test_a_host_error_is_a_fixed_refusal (__main__.Driver.test_a_host_error_is_a_fixed_refusal) ... ok +test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread (__main__.Driver.test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread) ... ok +test_a_project_list_off_its_documented_shape_is_refused_before_any_create (__main__.Driver.test_a_project_list_off_its_documented_shape_is_refused_before_any_create) ... ok +test_a_rejected_effort_needs_a_readable_model_list_to_say_the_model_cannot_set_it (__main__.Driver.test_a_rejected_effort_needs_a_readable_model_list_to_say_the_model_cannot_set_it) ... ok +test_an_effort_outside_capys_reasoning_modes_is_refused_before_any_request (__main__.Driver.test_an_effort_outside_capys_reasoning_modes_is_refused_before_any_request) ... ok +test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing (__main__.Driver.test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing) ... ok +test_an_unknown_run_is_refused_by_wake_and_stop (__main__.Driver.test_an_unknown_run_is_refused_by_wake_and_stop) ... ok +test_an_unreadable_or_mismatched_thread_read_refuses_wake_and_stop_before_any_write (__main__.Driver.test_an_unreadable_or_mismatched_thread_read_refuses_wake_and_stop_before_any_write) ... ok +test_effort_reaches_the_host_as_the_model_reasoning_mode (__main__.Driver.test_effort_reaches_the_host_as_the_model_reasoning_mode) ... ok +test_every_refusal_fits_d3_even_for_the_longest_repository_and_ticket (__main__.Driver.test_every_refusal_fits_d3_even_for_the_longest_repository_and_ticket) ... ok +test_every_request_reaches_the_host_with_the_key_header_only (__main__.Driver.test_every_request_reaches_the_host_with_the_key_header_only) ... ok +test_inputs_off_the_schema_are_refused_before_any_request (__main__.Driver.test_inputs_off_the_schema_are_refused_before_any_request) ... ok +test_kit_passes_all_five_on_the_fake_host (__main__.Driver.test_kit_passes_all_five_on_the_fake_host) ... ok +test_no_driver_file_names_the_key_or_the_keychain (__main__.Driver.test_no_driver_file_names_the_key_or_the_keychain) ... ok +test_start_creates_one_thread_in_the_repository_project_on_the_harness_model (__main__.Driver.test_start_creates_one_thread_in_the_repository_project_on_the_harness_model) ... ok +test_start_refuses_a_harness_capy_has_no_subscription_for (__main__.Driver.test_start_refuses_a_harness_capy_has_no_subscription_for) ... ok +test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses (__main__.Driver.test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses) ... ok +test_stop_interrupts_then_archives_and_a_wake_after_it_is_refused (__main__.Driver.test_stop_interrupts_then_archives_and_a_wake_after_it_is_refused) ... ok +test_version_lists_effort_and_the_schema_is_the_kernels (__main__.Driver.test_version_lists_effort_and_the_schema_is_the_kernels) ... ok +test_wake_and_stop_refuse_unless_capy_confirms_each_write (__main__.Driver.test_wake_and_stop_refuse_unless_capy_confirms_each_write) ... ok +test_wake_steers_a_message_into_the_same_thread_and_its_note_is_edited (__main__.Driver.test_wake_steers_a_message_into_the_same_thread_and_its_note_is_edited) ... ok + +---------------------------------------------------------------------- +Ran 22 tests + +OK diff --git a/adapters/capy/evidence/red-effort.txt b/adapters/capy/evidence/red-effort.txt new file mode 100644 index 000000000..fdc712ce6 --- /dev/null +++ b/adapters/capy/evidence/red-effort.txt @@ -0,0 +1,63 @@ +$ python3 -I adapters/capy/test_driver.py -v (agent CLI stubs first on PATH; KY1 at 2292b177, EF1 at 371c9cbf merged; the test expects effort in can, before the driver and schema change) +test_a_host_error_is_a_fixed_refusal (__main__.Driver.test_a_host_error_is_a_fixed_refusal) ... ok +test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread (__main__.Driver.test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread) ... ok +test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing (__main__.Driver.test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing) ... ok +test_an_unknown_run_is_refused_by_wake_and_stop (__main__.Driver.test_an_unknown_run_is_refused_by_wake_and_stop) ... ok +test_effort_reaches_the_host_as_the_model_reasoning_mode (__main__.Driver.test_effort_reaches_the_host_as_the_model_reasoning_mode) ... ok +test_every_request_reaches_the_host_with_the_key_header_only (__main__.Driver.test_every_request_reaches_the_host_with_the_key_header_only) ... ok +test_inputs_off_the_schema_are_refused_before_any_request (__main__.Driver.test_inputs_off_the_schema_are_refused_before_any_request) ... ok +test_kit_passes_all_five_on_the_fake_host (__main__.Driver.test_kit_passes_all_five_on_the_fake_host) ... FAIL +test_no_driver_file_names_the_key_or_the_keychain (__main__.Driver.test_no_driver_file_names_the_key_or_the_keychain) ... ok +test_start_creates_one_thread_in_the_repository_project_on_the_harness_model (__main__.Driver.test_start_creates_one_thread_in_the_repository_project_on_the_harness_model) ... ok +test_start_refuses_a_harness_capy_has_no_subscription_for (__main__.Driver.test_start_refuses_a_harness_capy_has_no_subscription_for) ... ok +test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses (__main__.Driver.test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses) ... ok +test_stop_interrupts_then_archives_and_a_wake_after_it_is_refused (__main__.Driver.test_stop_interrupts_then_archives_and_a_wake_after_it_is_refused) ... ok +test_version_lists_effort_and_the_schema_is_the_kernels (__main__.Driver.test_version_lists_effort_and_the_schema_is_the_kernels) ... FAIL +test_wake_steers_a_message_into_the_same_thread_and_its_note_is_edited (__main__.Driver.test_wake_steers_a_message_into_the_same_thread_and_its_note_is_edited) ... ok + +====================================================================== +FAIL: test_kit_passes_all_five_on_the_fake_host (__main__.Driver.test_kit_passes_all_five_on_the_fake_host) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 107, in test_kit_passes_all_five_on_the_fake_host + self.assertEqual((p.stdout.splitlines(), p.stderr), (KIT_PASS, '')) +AssertionError: Tuples differ: (['fail version: its schema is not kernel/dr[343 chars], '') != (['pass version: openwiz:records v1, and the[343 chars], '') + +First differing element 0: +['fail version: its schema is not kernel/dr[338 chars]der'] +['pass version: openwiz:records v1, and the[338 chars]der'] + +- (['fail version: its schema is not kernel/driver-kit/schema.json', ++ (['pass version: openwiz:records v1, and the schema is driver v1', + 'pass start: the run posted builder status note 2', + 'pass wake: the run edited builder status note 2', + 'pass stop: the run ended, and a wake after it is refused', + 'pass token: no login or token passed through the driver, and on start, wake ' + 'and stop the capy key reached its host only from the key helper, in its ' + 'header'], + '') + +====================================================================== +FAIL: test_version_lists_effort_and_the_schema_is_the_kernels (__main__.Driver.test_version_lists_effort_and_the_schema_is_the_kernels) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 242, in test_version_lists_effort_and_the_schema_is_the_kernels + self.assertEqual(self.driver('version'), (0, {'driver': 'capy', 'records': ['openwiz:records v1'], +AssertionError: Tuples differ: (0, {[34 chars]nwiz:records v1'], 'can': ['start', 'wake', 'stop']}) != (0, {[34 chars]nwiz:records v1'], 'can': ['start', 'wake', 'stop', 'effort']}) + +First differing element 1: +{'dri[29 chars]enwiz:records v1'], 'can': ['start', 'wake', 'stop']} +{'dri[29 chars]enwiz:records v1'], 'can': ['start', 'wake', 'stop', 'effort']} + + (0, +- {'can': ['start', 'wake', 'stop'], ++ {'can': ['start', 'wake', 'stop', 'effort'], +? ++++++++++ + + 'driver': 'capy', + 'records': ['openwiz:records v1']}) + +---------------------------------------------------------------------- +Ran 15 tests in 14.187s + +FAILED (failures=2) diff --git a/adapters/capy/evidence/red-fail-closed.txt b/adapters/capy/evidence/red-fail-closed.txt new file mode 100644 index 000000000..4afed9f18 --- /dev/null +++ b/adapters/capy/evidence/red-fail-closed.txt @@ -0,0 +1,128 @@ +$ env -u OPENWIZ_GITHUB_APP_KEY python3 -I adapters/capy/test_driver.py (35 refusing agent CLI stubs first on PATH; the fail-closed proofs of the review round, before the fix) +F..FFFF.F.F......F..F. +====================================================================== +FAIL: test_a_create_receipt_off_its_shape_or_for_another_project_is_a_possible_start (__main__.Driver.test_a_create_receipt_off_its_shape_or_for_another_project_is_a_possible_start) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 273, in test_a_create_receipt_off_its_shape_or_for_another_project_is_a_possible_start + out = self.refused('start', START, shows) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "adapters/capy/test_driver.py", line 94, in refused + self.assertEqual(code, 1, (request, self.host.answers, out)) +AssertionError: 0 != 1 : ({'repository': 'example/site', 'ticket': 7, 'skill': 'build-ticket', 'harness': 'claude-code', 'model': 'claude-synthetic-1'}, [('POST', '/api/v1/threads', 200, {'id': 'jam_other', 'projectId': 'project_other', 'authorId': 'user_synthetic', 'previousAuthorId': None, 'title': 'OpenWiz: example/site#7', 'titleCustom': True, 'status': 'working', 'archived': False, 'lastModelId': 'anthropic/claude-synthetic-1', 'queuedAt': None, 'linearIssue': None, 'pullRequestAuthor': None, 'usage': {'llmCredits': 0, 'imageCredits': 0, 'vmCredits': 0, 'totalCredits': 0}, 'createdAt': '2030-01-01T00:00:00Z', 'updatedAt': '2030-01-01T00:00:00Z', 'lastActivityAt': None, 'hasUnreads': False, 'mentionCount': 0, 'owed': False, 'member': True})], {'run': 'jam_other'}) + +====================================================================== +FAIL: test_a_project_list_off_its_documented_shape_is_refused_before_any_create (__main__.Driver.test_a_project_list_off_its_documented_shape_is_refused_before_any_create) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 263, in test_a_project_list_off_its_documented_shape_is_refused_before_any_create + self.assertIn('CAPY_PROJECT_ID', self.refused('start', START)['next']) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "adapters/capy/test_driver.py", line 94, in refused + self.assertEqual(code, 1, (request, self.host.answers, out)) +AssertionError: 0 != 1 : ({'repository': 'example/site', 'ticket': 7, 'skill': 'build-ticket', 'harness': 'claude-code', 'model': 'claude-synthetic-1'}, [('GET', '/api/v1/projects', 200, {'items': [{'id': 'project_synthetic1', 'name': 'Site', 'description': None, 'code': 'SITE', 'visibility': 'org', 'repos': [{'repoFullName': 'Example/Site', 'baseBranch': 'main', 'mode': 'primary'}], 'createdAt': '2030-01-01T00:00:00Z', 'updatedAt': '2030-01-01T00:00:00Z'}], 'more': 1})], {'run': 'jam_01SYNTHETIC0000000000000'}) + +====================================================================== +FAIL: test_a_rejected_effort_needs_a_readable_model_list_to_say_the_model_cannot_set_it (__main__.Driver.test_a_rejected_effort_needs_a_readable_model_list_to_say_the_model_cannot_set_it) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 291, in test_a_rejected_effort_needs_a_readable_model_list_to_say_the_model_cannot_set_it + self.assertNotEqual(self.refused('start', dict(START, effort='xhigh'), 'xhigh')['next'], NO_EFFORT) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "adapters/capy/test_driver.py", line 96, in refused + self.assertIn(shows, out['error']) +AssertionError: 'xhigh' not found in 'Capy cannot run model anthropic/claude-synthetic-1 for this key' + +====================================================================== +FAIL: test_an_effort_outside_capys_reasoning_modes_is_refused_before_any_request (__main__.Driver.test_an_effort_outside_capys_reasoning_modes_is_refused_before_any_request) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 279, in test_an_effort_outside_capys_reasoning_modes_is_refused_before_any_request + self.assertEqual(self.driver('start', dict(START, effort=effort)), (1, { +AssertionError: Tuples differ: (1, {'error': 'Capy answered 400 to POST /api/v1/threads', 'n[79 chars]in"}) != (1, {'error': 'Capy cannot run claude-code (model claude-synt[159 chars]lt"}) + +First differing element 1: +{'error': 'Capy answered 400 to POST /api/v1/threads', 'n[78 chars]ain"} +{'error': 'Capy cannot run claude-code (model claude-synt[158 chars]ult"} + + (1, +- {'error': 'Capy answered 400 to POST /api/v1/threads', +- 'next': "check your key, your Capy project and the start's fields, then " +- 'start again'}) ++ {'error': 'Capy cannot run claude-code (model claude-synthetic-1) at effort ' ++ 'ultra', ++ '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"}) + +====================================================================== +FAIL: test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing (__main__.Driver.test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 175, in test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing + self.assertEqual((code, out), (1, {'error': 'Capy cannot run claude-code (model claude-synthetic-1) at ' +AssertionError: Tuples differ: (1, {[28 chars]aude-synthetic-1 at effort xhigh', 'next': "th[121 chars]lt"}) != (1, {[28 chars]aude-code (model claude-synthetic-1) at effort[141 chars]lt"}) + +First differing element 1: +{'err[24 chars]aude-synthetic-1 at effort xhigh', 'next': "th[120 chars]ult"} +{'err[24 chars]aude-code (model claude-synthetic-1) at effort[140 chars]ult"} + + (1, +- {'error': 'Capy cannot run claude-synthetic-1 at effort xhigh', +? ----- - + ++ {'error': 'Capy cannot run claude-code (model claude-synthetic-1) at effort ' +? +++++++++++++++++++ + + ++ 'xhigh', + '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"}) + +====================================================================== +FAIL: test_an_unreadable_or_mismatched_thread_read_refuses_wake_and_stop_before_any_write (__main__.Driver.test_an_unreadable_or_mismatched_thread_read_refuses_wake_and_stop_before_any_write) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 234, in test_an_unreadable_or_mismatched_thread_read_refuses_wake_and_stop_before_any_write + self.assertNotEqual(self.refused(cmd, {'run': run}, run)['next'], 'start a new run') +AssertionError: 'start a new run' == 'start a new run' + +====================================================================== +FAIL: test_every_refusal_fits_d3_even_for_the_longest_repository_and_ticket (__main__.Driver.test_every_refusal_fits_d3_even_for_the_longest_repository_and_ticket) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 296, in test_every_refusal_fits_d3_even_for_the_longest_repository_and_ticket + self.refused('start', dict(START, repository=repo), repo) + File "adapters/capy/test_driver.py", line 93, in refused + code, out = self.driver(cmd, request) + ^^^^^^^^^^^^^^^^^^^^^^^^^ + File "adapters/capy/test_driver.py", line 89, in driver + self.assertTrue(isinstance(line, str) and 1 <= len(line) <= 300 and '\n' not in line, out) +AssertionError: False is not true : {'error': 'no Capy project lists oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr', 'next': 'add oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr to one Capy project (Settings, Projects & setup), or set CAPY_PROJECT_ID to the project to run it in, then start again'} + +====================================================================== +FAIL: test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses (__main__.Driver.test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 144, in test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses + self.assertEqual((code, out), (1, { +AssertionError: Tuples differ: (1, {[55 chars]'add example/site to one Capy project (Setting[88 chars]in'}) != (1, {[55 chars]'add the repository to one Capy project (Setti[90 chars]in'}) + +First differing element 1: +{'err[51 chars]'add example/site to one Capy project (Setting[87 chars]ain'} +{'err[51 chars]'add the repository to one Capy project (Setti[89 chars]ain'} + +Diff is 666 characters long. Set self.maxDiff to None to see it. + +====================================================================== +FAIL: test_wake_and_stop_refuse_unless_capy_confirms_each_write (__main__.Driver.test_wake_and_stop_refuse_unless_capy_confirms_each_write) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 246, in test_wake_and_stop_refuse_unless_capy_confirms_each_write + self.refused(cmd, {'run': run}, run) + File "adapters/capy/test_driver.py", line 94, in refused + self.assertEqual(code, 1, (request, self.host.answers, out)) +AssertionError: 0 != 1 : ({'run': 'jam_01SYNTHETIC0000000000000'}, [('POST', '/api/v1/threads/jam_01SYNTHETIC0000000000000/message', 200, None)], {'run': 'jam_01SYNTHETIC0000000000000', 'woke': True}) + +---------------------------------------------------------------------- +Ran 22 tests in 16.719s + +FAILED (failures=9) diff --git a/adapters/capy/evidence/red-kit.txt b/adapters/capy/evidence/red-kit.txt new file mode 100644 index 000000000..69b7b1908 --- /dev/null +++ b/adapters/capy/evidence/red-kit.txt @@ -0,0 +1,7 @@ +$ python3 -I kernel/driver-kit/kit.py --driver adapters/capy/driver (the template, copied and renamed) --repo example/site --ticket 7 --harness claude-code --model claude-synthetic-1 --tracker --wait 8, on the fake Capy +pass version: openwiz:records v1, and the schema is driver v1 +fail start: harness claude-code is not installed here +fail wake: not run: start failed +fail stop: not run: start failed +fail token: the capy key never reached the kit's fake host +exit 1 diff --git a/adapters/capy/evidence/red-project.txt b/adapters/capy/evidence/red-project.txt new file mode 100644 index 000000000..68822263a --- /dev/null +++ b/adapters/capy/evidence/red-project.txt @@ -0,0 +1,19 @@ +$ python3 -I adapters/capy/test_driver.py -v (agent CLI stubs first on PATH; the driver at 45349f25, before the CAPY_PROJECT_ID fix; KY1 at 2292b177) +test_a_host_error_is_a_fixed_refusal ... ok +test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread ... ok +test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing ... ok +test_an_unknown_run_is_refused_by_wake_and_stop ... ok +test_effort_reaches_the_host_as_the_model_reasoning_mode ... ok +test_every_request_reaches_the_host_with_the_key_header_only ... ok +test_inputs_off_the_schema_are_refused_before_any_request ... ok +test_kit_passes_all_five_on_the_fake_host ... ok +test_no_driver_file_names_the_key_or_the_keychain ... ok +test_start_creates_one_thread_in_the_repository_project_on_the_harness_model ... ok +test_start_refuses_a_harness_capy_has_no_subscription_for ... ok +test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses ... FAIL +test_stop_interrupts_then_archives_and_a_wake_after_it_is_refused ... ok +test_version_and_schema ... ok +test_wake_steers_a_message_into_the_same_thread_and_its_note_is_edited ... ok +AssertionError: Tuples differ: (0, {'run': 'jam_01SYNTHETIC0000000000000'}) != (1, {'error': 'no Capy project lists examp[152 chars]in'}) +Ran 15 tests in 12.455s +FAILED (failures=1) diff --git a/adapters/capy/evidence/red.txt b/adapters/capy/evidence/red.txt new file mode 100644 index 000000000..fac336a98 --- /dev/null +++ b/adapters/capy/evidence/red.txt @@ -0,0 +1,30 @@ +$ python3 -I adapters/capy/test_driver.py -v (agent CLI stubs first on PATH; the driver is the template, copied and renamed; KY1 at 2292b177) +test_a_host_error_is_a_fixed_refusal ... FAIL +test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread ... FAIL +test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing ... FAIL +test_an_unknown_run_is_refused_by_wake_and_stop ... FAIL +test_effort_reaches_the_host_as_the_model_reasoning_mode ... FAIL +test_every_request_reaches_the_host_with_the_key_header_only ... FAIL +test_inputs_off_the_schema_are_refused_before_any_request ... ok +test_kit_passes_all_five_on_the_fake_host ... FAIL +test_no_driver_file_names_the_key_or_the_keychain ... ok +test_start_creates_one_thread_in_the_repository_project_on_the_harness_model ... FAIL +test_start_refuses_a_harness_capy_has_no_subscription_for ... FAIL +test_start_takes_the_only_project_and_refuses_when_none_or_many_list_the_repository ... FAIL +test_stop_interrupts_then_archives_and_a_wake_after_it_is_refused ... FAIL +test_version_and_schema ... ok +test_wake_steers_a_message_into_the_same_thread_and_its_note_is_edited ... FAIL +AssertionError: Tuples differ: (1, {'error': 'harness claude-code is not installed here[74 chars]in'}) != (1, {'error': 'Capy answered 401 to GET /api/v1/projects[54 chars]ry"}) +AssertionError: 1 != 0 : {'error': 'harness claude-code is not installed here', 'next': 'install claude-code and sign in to it yourself, then start again'} +AssertionError: Tuples differ: (1, {'error': 'the input needs exactly repository, ticke[71 chars]in'}) != (1, {'error': 'Capy cannot run claude-synthetic-1 at eff[144 chars]lt"}) +AssertionError: Tuples differ: (1, {'error': 'run is not valid', 'next': 'fix run as `driver schema` shows'}) != (1, {'error': 'Capy has no run jam_01UNKNOWN', 'next': 'start a new run'}) +AssertionError: 1 != 0 : {'error': 'the input needs exactly repository, ticket, skill, harness, model', 'next': 'send only those fields; never a login'} +AssertionError: 1 != 0 : {'error': 'harness claude-code is not installed here', 'next': 'install claude-code and sign in to it yourself, then start again'} +AssertionError: Tuples differ: (['pa[58 chars]1', 'fail start: harness claude-code is not in[148 chars], '') != (['pa[58 chars]1', 'pass start: the run posted builder status[278 chars], '') +AssertionError: 1 != 0 : {'error': 'harness claude-code is not installed here', 'next': 'install claude-code and sign in to it yourself, then start again'} +AssertionError: {'err[27 chars] not installed here', 'next': 'install gemini-[45 chars]ain'} != {'err[27 chars] not one Capy runs for OpenWiz', 'next': 'use [29 chars]dex'} +AssertionError: {'error': 'harness claude-code is not installed here[73 chars]ain'} != {'error': 'no Capy project lists example/elsewhere, [128 chars]ain'} +AssertionError: 1 != 0 : {'error': 'harness claude-code is not installed here', 'next': 'install claude-code and sign in to it yourself, then start again'} +AssertionError: 1 != 0 : {'error': 'harness claude-code is not installed here', 'next': 'install claude-code and sign in to it yourself, then start again'} +Ran 15 tests in 8.522s +FAILED (failures=12) diff --git a/adapters/capy/fixtures/fake_capy.py b/adapters/capy/fixtures/fake_capy.py new file mode 100644 index 000000000..f0e043e4a --- /dev/null +++ b/adapters/capy/fixtures/fake_capy.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +# External: the routes and shapes follow Capy's OpenAPI document (https://docs.capy.ai/openapi.json), and a message +# unarchives and wakes an archived thread (https://docs.capy.ai/threads#archive-is-dormant). +import http.server +import json +import os +import re +import threading +import time + +KEY_PATH = '/.openwiz/hostkey-test-key' +PROJECTS = [ + {'id': 'project_synthetic1', 'name': 'Site', 'description': None, 'code': 'SITE', 'visibility': 'org', + 'repos': [{'repoFullName': 'Example/Site', 'baseBranch': 'main', 'mode': 'primary'}], + 'createdAt': '2030-01-01T00:00:00Z', 'updatedAt': '2030-01-01T00:00:00Z'}, + {'id': 'project_synthetic2', 'name': 'Other', 'description': None, 'code': 'OTH', 'visibility': 'org', + 'repos': [{'repoFullName': 'example/other', 'baseBranch': 'main', 'mode': 'lazy'}], + 'createdAt': '2030-01-01T00:00:00Z', 'updatedAt': '2030-01-01T00:00:00Z'}, +] +MODELS = [ + {'id': 'anthropic/claude-synthetic-1', 'name': 'Claude Synthetic 1', 'billing': 'Claude Code', + 'route': 'member_seat', 'reasoningModes': ['low', 'medium', 'high'], 'fast': False, 'pro': False, + 'ultrafast': False}, + {'id': 'openai/gpt-synthetic-2', 'name': 'GPT Synthetic 2', 'billing': 'Codex', 'route': 'member_seat', + 'reasoningModes': ['none', 'low', 'medium', 'high', 'xhigh'], 'fast': False, 'pro': False, 'ultrafast': False}, +] +REASONING = ['none', 'instant', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] +CREATE = {'requestId', 'projectId', 'title', 'message', 'environmentVariables', 'model', 'machineSize', 'device', + 'authorId', 'visibility', 'personal', 'pullRequestAuthor', 'captainId'} +SEND = {'text', 'files', 'model', 'delivery', 'clientKey', 'editOf', 'switchTo', 'pullRequestAuthor'} +NOTE = '\n'.join(['', 'agent: builder', 'state: working', 'harness: Capy', 'model: %s', + 'skills: %s@0.1.2', 'step: %s', 'time: %s']) + '\n' + + +def tag(name, **fields): + return dict({'_tag': 'capy/' + name}, **fields) + + +class FakeCapy: + + def __init__(self, key, tracker, projects=PROJECTS, models=MODELS, lose_creates=0, served_key=None, answers=()): + self.key, self.tracker, self.projects, self.models = key, tracker, projects, models + self.answers = list(answers) + self.served_key = key if served_key is None else served_key + self.lose_creates = lose_creates + self.requests, self.threads, self.by_request = [], {}, {} + self.lock = threading.Lock() + host = self + + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def handle_one(self): + raw = self.rfile.read(int(self.headers.get('Content-Length') or 0)) + if self.command == 'GET' and self.path == KEY_PATH: + return self.reply(200, {'key': host.served_key}) + with host.lock: + host.requests.append((self.command, self.path, raw, self.headers.get('Authorization'))) + if self.headers.get('Authorization') != 'Bearer ' + host.key: + code, body = 401, tag('Unauthorized') + else: + try: + code, body = host.route(self.command, self.path, json.loads(raw) if raw else None) + except ValueError: + code, body = 400, tag('InvalidRequest', message='synthetic: unreadable JSON') + self.reply(code, body) + + def reply(self, code, body): + data = json.dumps(body).encode() + self.send_response(code) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + + do_GET = do_POST = do_DELETE = do_PATCH = do_PUT = handle_one + + self.server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler) + self.server.daemon_threads = True + self.origin = 'http://127.0.0.1:%d' % self.server.server_address[1] + threading.Thread(target=self.server.serve_forever, daemon=True).start() + + def close(self): + self.server.shutdown() + self.server.server_close() + + def calls(self): + return [(m, p) for m, p, _, _ in self.requests] + + def bodies(self, method, path): + return [json.loads(b) for m, p, b, _ in self.requests if (m, p) == (method, path)] + + def _note(self, t, step): + skill = re.search(r'with the ([a-z0-9-]+) skill', t['create']['message']).group(1) + now = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) + body = NOTE % (t['create'].get('model', {}).get('modelId', 'default'), skill, step, now) + with open(self.tracker) as f: + tracker = json.load(f) + if t['note'] is None: + t['note'] = 1 + max([c['id'] for c in tracker['comments']], default=0) + tracker['comments'].append({'id': t['note'], 'author': 'example-bot[bot]', 'updated_at': now, + 'body': body}) + else: + for c in tracker['comments']: + if c['id'] == t['note']: + c.update(body=body, updated_at=now) + with open(self.tracker + '.new', 'w') as f: + json.dump(tracker, f) + os.replace(self.tracker + '.new', self.tracker) + + def _thread(self, t): + return {'id': t['id'], 'projectId': t['create']['projectId'], 'authorId': 'user_synthetic', + 'previousAuthorId': None, 'title': t['create'].get('title'), 'titleCustom': True, + 'status': 'archived' if t['archived'] else t['status'], 'archived': t['archived'], + 'lastModelId': t['create'].get('model', {}).get('modelId'), 'queuedAt': None, 'linearIssue': None, + 'pullRequestAuthor': None, + 'usage': {'llmCredits': 0, 'imageCredits': 0, 'vmCredits': 0, 'totalCredits': 0}, + 'createdAt': '2030-01-01T00:00:00Z', 'updatedAt': '2030-01-01T00:00:00Z', 'lastActivityAt': None, + 'hasUnreads': False, 'mentionCount': 0, 'owed': False, 'member': True} + + def _receipt(self, t): + t['events'] += 1 + return {'id': '01SYNTHETIC%015d' % (len(self.threads) * 1000 + t['events']), 'deduped': False} + + def route(self, method, target, body): + path = target.partition('?')[0] + for m, pattern, code, reply in self.answers: + if m == method and re.fullmatch(pattern, path): + return code, reply + if method == 'GET' and path == '/api/v1/projects': + return 200, {'items': self.projects} + if method == 'GET' and path == '/api/v1/models': + return 200, {'items': self.models, 'default': {'modelId': self.models[0]['id'], 'source': 'org', + 'skipped': []}} + if method == 'POST' and path == '/api/v1/threads': + if not isinstance(body, dict) or set(body) - CREATE or not {'requestId', 'projectId', 'message'} <= set( + body): + return 400, tag('InvalidRequest', message='synthetic: not a CreateThreadRequest') + if body['projectId'] not in [p['id'] for p in self.projects]: + return 404, tag('ProjectNotFound', projectId=body['projectId']) + model = body.get('model') + if model is not None and model.get('reasoningMode', 'none') not in REASONING: + return 400, tag('InvalidRequest', message='synthetic: not a ModelSelection') + if model is not None: + found = [m for m in self.models if m['id'] == model.get('modelId')] + if not found or model.get('reasoningMode', found[0]['reasoningModes'][0]) not in found[0][ + 'reasoningModes']: + return 400, {'_tag': 'ModelSelection.Rejected', 'message': 'synthetic: cannot run', + 'candidates': [], 'modelId': model.get('modelId')} + t = self.by_request.get(body['requestId']) + if t is None: + t = {'id': 'jam_01SYNTHETIC%013d' % len(self.threads), 'create': body, 'status': 'working', + 'archived': False, 'messages': [], 'interrupts': 0, 'note': None, 'events': 0} + self.threads[t['id']] = self.by_request[body['requestId']] = t + self._note(t, 'started the throwaway ticket') + if self.lose_creates: + self.lose_creates -= 1 + return 503, {'_tag': 'synthetic/Unavailable'} + return 200, self._thread(t) + m = re.fullmatch(r'/api/v1/threads/([^/]+)(/message|/interrupt|/archive)?', path) + t = self.threads.get(m.group(1)) if m else None + if m and t is None: + return 404, tag('ThreadNotFound', threadId=m.group(1)) + if method == 'GET' and m and not m.group(2): + return 200, self._thread(t) + if method == 'POST' and m and m.group(2) == '/message': + if not isinstance(body, dict) or set(body) - SEND or not isinstance(body.get('text'), str): + return 400, tag('InvalidRequest', message='synthetic: not a SendMessageRequest') + t['messages'].append(body) + t['archived'], t['status'] = False, 'working' + self._note(t, 'woke and read the ticket again') + return 200, self._receipt(t) + if method == 'POST' and m and m.group(2) == '/interrupt': + t['interrupts'] += 1 + t['status'] = 'idle' + return 200, self._receipt(t) + if method == 'POST' and m and m.group(2) == '/archive': + t['archived'] = True + return 200, dict(self._thread(t), automation=None) + return 404, {'_tag': 'synthetic/RouteNotFound'} diff --git a/adapters/capy/fixtures/kit-host.json b/adapters/capy/fixtures/kit-host.json new file mode 100644 index 000000000..ee061d48c --- /dev/null +++ b/adapters/capy/fixtures/kit-host.json @@ -0,0 +1,110 @@ +{ + "answers": [ + { + "method": "POST", + "path": "/api/v1/threads", + "status": 200, + "body": { + "id": "jam_01KITTHREAD0000000000000", + "projectId": null, + "authorId": null, + "previousAuthorId": null, + "title": "OpenWiz: kit", + "titleCustom": true, + "status": "working", + "archived": false, + "lastModelId": null, + "queuedAt": null, + "linearIssue": null, + "pullRequestAuthor": null, + "usage": { + "llmCredits": 0, + "imageCredits": 0, + "vmCredits": 0, + "totalCredits": 0 + }, + "createdAt": "2030-01-01T00:00:00Z", + "updatedAt": "2030-01-01T00:00:00Z", + "lastActivityAt": null, + "hasUnreads": false, + "mentionCount": 0, + "owed": false, + "member": true + } + }, + { + "method": "GET", + "path": "/api/v1/threads/[A-Za-z0-9_-]+", + "status": 200, + "body": { + "id": "jam_01KITTHREAD0000000000000", + "projectId": null, + "authorId": null, + "previousAuthorId": null, + "title": "OpenWiz: kit", + "titleCustom": true, + "status": "idle", + "archived": false, + "lastModelId": null, + "queuedAt": null, + "linearIssue": null, + "pullRequestAuthor": null, + "usage": { + "llmCredits": 0, + "imageCredits": 0, + "vmCredits": 0, + "totalCredits": 0 + }, + "createdAt": "2030-01-01T00:00:00Z", + "updatedAt": "2030-01-01T00:00:00Z", + "lastActivityAt": null, + "hasUnreads": false, + "mentionCount": 0, + "owed": false, + "member": true + } + }, + { + "method": "POST", + "path": "/api/v1/threads/[A-Za-z0-9_-]+/(message|interrupt)", + "status": 200, + "body": { + "id": "01KITEVENT0000000000000000", + "deduped": false + } + }, + { + "method": "POST", + "path": "/api/v1/threads/[A-Za-z0-9_-]+/archive", + "status": 200, + "body": { + "id": "jam_01KITTHREAD0000000000000", + "projectId": null, + "authorId": null, + "previousAuthorId": null, + "title": "OpenWiz: kit", + "titleCustom": true, + "status": "archived", + "archived": true, + "lastModelId": null, + "queuedAt": null, + "linearIssue": null, + "pullRequestAuthor": null, + "usage": { + "llmCredits": 0, + "imageCredits": 0, + "vmCredits": 0, + "totalCredits": 0 + }, + "createdAt": "2030-01-01T00:00:00Z", + "updatedAt": "2030-01-01T00:00:00Z", + "lastActivityAt": null, + "hasUnreads": false, + "mentionCount": 0, + "owed": false, + "member": true, + "automation": null + } + } + ] +} diff --git a/adapters/capy/release.json b/adapters/capy/release.json new file mode 100644 index 000000000..53c7e031a --- /dev/null +++ b/adapters/capy/release.json @@ -0,0 +1 @@ +{"extra_files": ["README.md", "fixtures/kit-host.json"]} diff --git a/adapters/capy/schema.json b/adapters/capy/schema.json new file mode 100644 index 000000000..891e2a315 --- /dev/null +++ b/adapters/capy/schema.json @@ -0,0 +1,219 @@ +{ + "contract": "openwiz:driver v1", + "commands": { + "version": { + "input": null, + "output": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "required": [ + "driver", + "records", + "can" + ], + "additionalProperties": false, + "properties": { + "driver": { + "type": "string", + "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$", + "maxLength": 40 + }, + "records": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^openwiz:records v[1-9][0-9]{0,2}$" + } + }, + "can": { + "type": "array", + "uniqueItems": true, + "items": { + "enum": [ + "start", + "wake", + "stop", + "many-at-once", + "own-sandbox", + "effort" + ] + }, + "allOf": [ + { + "contains": { + "const": "start" + } + }, + { + "contains": { + "const": "wake" + } + }, + { + "contains": { + "const": "stop" + } + } + ] + } + } + } + }, + "schema": { + "input": null, + "output": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object" + } + }, + "start": { + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "required": [ + "repository", + "ticket", + "skill", + "harness", + "model" + ], + "additionalProperties": false, + "properties": { + "repository": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}$" + }, + "ticket": { + "type": "integer", + "minimum": 1 + }, + "skill": { + "type": "string", + "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$", + "maxLength": 60 + }, + "harness": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9._-]{0,59}$" + }, + "model": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9 ._:@+-]*(/[A-Za-z0-9][A-Za-z0-9 ._:@+-]*)*$", + "maxLength": 100 + }, + "effort": { + "type": "string", + "pattern": "^[a-z][a-z0-9-]{0,19}$" + } + } + }, + "output": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "required": [ + "run" + ], + "additionalProperties": false, + "properties": { + "run": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$" + } + } + } + }, + "wake": { + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "required": [ + "run" + ], + "additionalProperties": false, + "properties": { + "run": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$" + } + } + }, + "output": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "required": [ + "run", + "woke" + ], + "additionalProperties": false, + "properties": { + "run": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$" + }, + "woke": { + "const": true + } + } + } + }, + "stop": { + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "required": [ + "run" + ], + "additionalProperties": false, + "properties": { + "run": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$" + } + } + }, + "output": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "required": [ + "run", + "stopped" + ], + "additionalProperties": false, + "properties": { + "run": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$" + }, + "stopped": { + "const": true + } + } + } + } + }, + "error": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "required": [ + "error", + "next" + ], + "additionalProperties": false, + "properties": { + "error": { + "type": "string", + "minLength": 1, + "maxLength": 300, + "pattern": "^[^\\u0000-\\u001f]*$" + }, + "next": { + "type": "string", + "minLength": 1, + "maxLength": 300, + "pattern": "^[^\\u0000-\\u001f]*$" + } + } + } +} diff --git a/adapters/capy/test_driver.py b/adapters/capy/test_driver.py new file mode 100755 index 000000000..fcc689a37 --- /dev/null +++ b/adapters/capy/test_driver.py @@ -0,0 +1,345 @@ +#!/usr/bin/env python3 +import importlib.machinery +import importlib.util +import json +import os +import re +import secrets +import shutil +import signal +import subprocess +import sys +import tempfile +import unittest + +sys.dont_write_bytecode = True +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.join(HERE, '..', '..') +DRIVER = os.path.join(HERE, 'driver') +KIT = os.path.join(ROOT, 'kernel', 'driver-kit', 'kit.py') +KEY = 'synthetic-capy-' + 'Kit0Value' * 2 +START = {'repository': 'example/site', 'ticket': 7, 'skill': 'build-ticket', 'harness': 'claude-code', + 'model': 'claude-synthetic-1'} +PROMPT = 'Build the ticket: example/site#7, with the build-ticket skill.' +WOKEN = 'You were woken: read the ticket again and carry on.' +NO_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") +UUID = r'[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}' +KEYCHAIN_TOOLS_SPELLED_IN_PARTS = re.compile(rb'(?\nagent: builder\nstate: stopped\nharness: Fake\nmodel: m\n' \ + 'skills: build-ticket@0.1.2\nstep: an earlier run\ntime: 2030-01-02T03:04:05Z\n' + with open(path, 'w') as f: + json.dump({'record_authors': ['Example-Bot[bot]'], 'comments': [ + {'id': 1, 'author': 'example-bot[bot]', 'updated_at': '2030-01-02T03:04:05Z', 'body': old}]}, f) + return path + + +class Driver(unittest.TestCase): + def setUp(self): + self.folder = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.folder, True) + self.mark = secrets.token_hex(8) + self.tracker = tracker(self.folder) + self.env = dict(os.environ, KIT_TEST=self.mark, OPENWIZ_CAPY_POLL='0.01') + self.use() + + def use(self, **kw): + self.host = fake.FakeCapy(KEY, self.tracker, **kw) + self.addCleanup(self.host.close) + self.env['OPENWIZ_HOSTKEY_TEST_ORIGIN'] = self.host.origin + + def tearDown(self): + for pid in filter(str.isdigit, os.listdir('/proc')): + try: + with open('/proc/%s/environ' % pid, 'rb') as f: + if ('KIT_TEST=' + self.mark).encode() in f.read().split(b'\0'): + os.kill(int(pid), signal.SIGKILL) + except OSError: + pass + + def driver(self, cmd, request=None): + p = subprocess.run([DRIVER, cmd], input='' if request is None else json.dumps(request), env=self.env, + capture_output=True, text=True, timeout=120) + self.assertEqual(p.stderr, '') + self.assertIn(p.returncode, (0, 1)) + out = json.loads(p.stdout) + if p.returncode: + self.assertEqual(set(out), {'error', 'next'}, out) + for line in out.values(): + self.assertTrue(isinstance(line, str) and 1 <= len(line) <= 300 and '\n' not in line, out) + return p.returncode, out + + def refused(self, cmd, request, shows=None): + code, out = self.driver(cmd, request) + self.assertEqual(code, 1, (request, self.host.answers, out)) + if shows: + self.assertIn(shows, out['error']) + return out + + def started(self, **kw): + code, out = self.driver('start', dict(START, **kw)) + self.assertEqual(code, 0, out) + return out['run'] + + def notes(self): + with open(self.tracker) as f: + return [c for c in json.load(f)['comments'] if 'state: working' in c['body']] + + def posts(self): + return [p for m, p in self.host.calls() if m == 'POST'] + + def test_kit_passes_all_five_on_the_fake_host(self): + p = subprocess.run([sys.executable, '-I', KIT, '--driver', DRIVER, '--repo', 'example/site', '--ticket', '7', + '--harness', 'claude-code', '--model', 'claude-synthetic-1', '--tracker', self.tracker, + '--wait', '8'], env=dict(self.env, CAPY_PROJECT_ID='project_synthetic1'), + capture_output=True, text=True, timeout=300) + self.assertEqual((p.stdout.splitlines(), p.stderr), (KIT_PASS, '')) + self.assertEqual(p.returncode, 0) + + def test_every_request_reaches_the_host_with_the_key_header_only(self): + run = self.started() + self.driver('wake', {'run': run}) + self.driver('stop', {'run': run}) + self.assertTrue(self.host.requests) + for method, path, body, auth in self.host.requests: + self.assertEqual(auth, 'Bearer ' + KEY) + self.assertNotIn(KEY, path + body.decode()) + + def test_start_creates_one_thread_in_the_repository_project_on_the_harness_model(self): + run = self.started() + self.assertEqual(list(self.host.threads), [run]) + [sent] = self.host.bodies('POST', '/api/v1/threads') + self.assertRegex(sent.pop('requestId'), UUID) + self.assertEqual(sent, {'projectId': 'project_synthetic1', 'title': 'OpenWiz: example/site#7', + 'message': PROMPT, 'model': {'modelId': 'anthropic/claude-synthetic-1'}}) + self.assertEqual(self.host.calls(), [('GET', '/api/v1/projects'), ('POST', '/api/v1/threads')]) + self.assertEqual(len(self.notes()), 1) + run = self.started(harness='codex', model='gpt-synthetic-2', repository='example/other') + self.assertEqual(self.host.threads[run]['create']['model'], {'modelId': 'openai/gpt-synthetic-2'}) + self.assertEqual(self.host.threads[run]['create']['projectId'], 'project_synthetic2') + + def test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses(self): + self.use(projects=fake.PROJECTS[1:]) + code, out = self.driver('start', START) + self.assertEqual((code, out), (1, { + 'error': 'no Capy project lists example/site', + 'next': 'add the repository to one Capy project (Settings, Projects & setup), or set CAPY_PROJECT_ID ' + 'to the project to run it in, then start again'})) + self.use(projects=fake.PROJECTS * 2) + self.assertEqual(self.driver('start', START)[1]['error'], 'more than one Capy project lists example/site') + self.assertEqual(self.posts(), []) + self.host.requests.clear() + self.env['CAPY_PROJECT_ID'] = 'project_synthetic2' + run = self.started() + self.assertEqual(self.host.threads[run]['create']['projectId'], 'project_synthetic2') + self.assertEqual(self.host.calls(), [('POST', '/api/v1/threads')]) + self.env['CAPY_PROJECT_ID'] = 'project synthetic"2' + self.assertEqual(self.driver('start', START), (1, {'error': 'CAPY_PROJECT_ID is not a Capy project id', + 'next': 'set CAPY_PROJECT_ID to a project id from ' + 'Capy\'s Settings, Projects & setup, or unset it'})) + self.assertEqual(len(self.host.requests), 1) + + def test_start_refuses_a_harness_capy_has_no_subscription_for(self): + code, out = self.driver('start', dict(START, harness='gemini-cli')) + self.assertEqual(out, {'error': 'harness gemini-cli is not one Capy runs for OpenWiz', + 'next': 'use claude-code (or claude) or codex'}) + self.assertEqual(self.host.requests, []) + + def test_effort_reaches_the_host_as_the_model_reasoning_mode(self): + run = self.started(effort='high') + self.assertEqual(self.host.threads[run]['create']['model'], + {'modelId': 'anthropic/claude-synthetic-1', 'reasoningMode': 'high'}) + + def test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing(self): + code, out = self.driver('start', dict(START, effort='xhigh')) + self.assertEqual((code, out), (1, {'error': 'Capy cannot run claude-code (model claude-synthetic-1) at ' + 'effort xhigh', + 'next': NO_EFFORT})) + self.assertEqual((self.host.threads, self.notes()), ({}, [])) + code, out = self.driver('start', dict(START, model='claude-synthetic-9', effort='high')) + self.assertEqual(out, {'error': 'Capy cannot run model anthropic/claude-synthetic-9 for this key', + 'next': "pick a model Capy lists for your key (Settings, Models), or connect the " + "subscription that serves it, then start again"}) + + def test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread(self): + self.use(lose_creates=1) + run = self.started() + first, second = self.host.bodies('POST', '/api/v1/threads') + self.assertEqual(first, second) + self.assertEqual(list(self.host.threads), [run]) + self.use(lose_creates=2) + code, out = self.driver('start', START) + self.assertEqual(out, {'error': 'Capy answered 503 to POST /api/v1/threads, so a thread may have started', + 'next': 'archive the Capy thread titled OpenWiz: example/site#7 if it is there, ' + 'then start again'}) + + def test_wake_steers_a_message_into_the_same_thread_and_its_note_is_edited(self): + run = self.started() + self.host.requests.clear() + self.assertEqual(self.driver('wake', {'run': run}), (0, {'run': run, 'woke': True})) + self.assertEqual(self.host.calls(), [('GET', '/api/v1/threads/' + run), + ('POST', '/api/v1/threads/%s/message' % run)]) + self.assertEqual(self.host.threads[run]['messages'], [{'text': WOKEN, 'delivery': 'steer'}]) + self.assertEqual(len(self.notes()), 1) + + def test_stop_interrupts_then_archives_and_a_wake_after_it_is_refused(self): + run = self.started() + self.host.requests.clear() + self.assertEqual(self.driver('stop', {'run': run}), (0, {'run': run, 'stopped': True})) + self.assertEqual(self.posts(), ['/api/v1/threads/%s/interrupt' % run, '/api/v1/threads/%s/archive' % run]) + self.assertTrue(self.host.threads[run]['archived']) + self.assertEqual(self.driver('wake', {'run': run}), (1, {'error': 'run %s is stopped' % run, + 'next': 'start a new run'})) + self.assertEqual(self.driver('stop', {'run': run}), (0, {'run': run, 'stopped': True})) + self.assertEqual((len(self.posts()), self.host.threads[run]['messages']), (2, [])) + + def test_an_unknown_run_is_refused_by_wake_and_stop(self): + for cmd in ('wake', 'stop'): + self.assertEqual(self.driver(cmd, {'run': 'jam_01UNKNOWN'}), + (1, {'error': 'Capy has no run jam_01UNKNOWN', 'next': 'start a new run'})) + self.assertEqual(self.posts(), []) + + def test_an_unreadable_or_mismatched_thread_read_refuses_wake_and_stop_before_any_write(self): + run = self.started() + t = self.host.threads[run] + good = self.host._thread(t) + for code, body in ((200, None), (200, {'archived': True}), (404, None), (404, {'_tag': 'capy/Unrelated'}), + (404, {'_tag': 'capy/ThreadNotFound', 'threadId': 'jam_other'}), (201, good), + (200, dict(good, id='jam_other')), (200, dict(good, archived='yes')), + (200, dict(good, status='paused')), (200, dict(good, status='archived')), + (200, dict(good, archived=True, status='working')), (200, dict(good, extra=1)), + (200, {k: v for k, v in good.items() if k != 'usage'})): + self.host.answers[:] = [('GET', '/api/v1/threads/' + run, code, body)] + for cmd in ('wake', 'stop'): + self.assertNotEqual(self.refused(cmd, {'run': run}, run)['next'], 'start a new run') + self.assertEqual(self.posts(), ['/api/v1/threads']) + self.assertEqual((t['archived'], t['status'], t['messages'], t['interrupts']), (False, 'working', [], 0)) + + def test_wake_and_stop_refuse_unless_capy_confirms_each_write(self): + run = self.started() + receipt = {'id': '01SYNTHETIC' + '0' * 15, 'deduped': False} + for code, body in ((200, None), (200, {}), (200, dict(receipt, id='01SHORT')), (202, receipt), + (200, dict(receipt, deduped='no')), (200, dict(receipt, extra=1))): + for cmd, route in (('wake', 'message'), ('stop', 'interrupt')): + self.host.answers[:] = [('POST', '/api/v1/threads/%s/%s' % (run, route), code, body)] + self.host.requests.clear() + self.refused(cmd, {'run': run}, run) + self.assertEqual(self.posts(), ['/api/v1/threads/%s/%s' % (run, route)]) + archived = dict(self.host._thread(self.host.threads[run]), automation=None, archived=True, status='archived') + for body in (None, dict(archived, archived=False, status='idle'), dict(archived, id='jam_other'), + dict(archived, status='working'), {k: v for k, v in archived.items() if k != 'automation'}): + self.host.answers[:] = [('POST', '/api/v1/threads/%s/archive' % run, 200, body)] + self.refused('stop', {'run': run}, run) + self.assertFalse(self.host.threads[run]['archived']) + + def test_a_project_list_off_its_documented_shape_is_refused_before_any_create(self): + good, other = fake.PROJECTS + for body in (None, {}, {'items': None}, {'items': [good], 'more': 1}, {'items': [good, None]}, + {'items': [dict(good, repos=None)]}, {'items': [{k: v for k, v in good.items() if k != 'repos'}]}, + {'items': [dict(good, id=7)]}, {'items': [dict(good, id='')]}, {'items': [dict(good, extra=1)]}, + {'items': [dict(good, repos=[{'repoFullName': 'Example/Site'}])]}, + {'items': [good, dict(other, repos='example/other')]}): + self.host.answers[:] = [('GET', '/api/v1/projects', 200, body)] + self.assertIn('CAPY_PROJECT_ID', self.refused('start', START)['next']) + self.assertEqual(self.posts(), []) + + def test_a_create_receipt_off_its_shape_or_for_another_project_is_a_possible_start(self): + run = self.started() + good = self.host._thread(self.host.threads[run]) + for body, shows in ((dict(good, id='jam_other', projectId='project_other'), 'jam_other'), (None, None), + (dict(good, archived=True, status='archived'), run), (dict(good, id='x/y'), None), + ({'id': run}, run), (dict(good, status='paused'), run)): + self.host.answers[:] = [('POST', '/api/v1/threads', 200, body)] + out = self.refused('start', START, shows) + self.assertIn('may have started', out['error']) + self.assertIn('archive', out['next']) + + def test_an_effort_outside_capys_reasoning_modes_is_refused_before_any_request(self): + for effort in ('ultra', 'extra-high', 'maximum'): + self.assertEqual(self.driver('start', dict(START, effort=effort)), (1, { + 'error': 'Capy cannot run claude-code (model claude-synthetic-1) at effort ' + effort, + 'next': NO_EFFORT})) + self.assertEqual(self.host.requests, []) + + def test_a_rejected_effort_needs_a_readable_model_list_to_say_the_model_cannot_set_it(self): + default = {'modelId': fake.MODELS[0]['id'], 'source': 'org', 'skipped': []} + for body in (None, {'items': None, 'default': default}, {'items': fake.MODELS}, + {'items': [dict(fake.MODELS[0], reasoningModes=None)], 'default': default}, + {'items': fake.MODELS + fake.MODELS[:1], 'default': default}, + {'items': [dict(fake.MODELS[0], reasoningModes=['low', 7])], 'default': default}): + self.host.answers[:] = [('GET', '/api/v1/models', 200, body)] + self.assertNotEqual(self.refused('start', dict(START, effort='xhigh'), 'xhigh')['next'], NO_EFFORT) + self.assertEqual(self.host.threads, {}) + + def test_every_refusal_fits_d3_even_for_the_longest_repository_and_ticket(self): + repo = 'o' * 100 + '/' + 'r' * 100 + self.refused('start', dict(START, repository=repo), repo) + self.use(lose_creates=2) + self.env['CAPY_PROJECT_ID'] = 'project_synthetic1' + self.assertIn('may have started', self.refused('start', dict(START, repository=repo, ticket=10 ** 40))['error']) + + def test_inputs_off_the_schema_are_refused_before_any_request(self): + for bad in (dict(START, token='kit-probe-not-a-login'), {k: v for k, v in START.items() if k != 'model'}, + dict(START, ticket='7'), dict(START, repository='https://example.com/x'), + dict(START, effort='High')): + self.assertEqual(self.driver('start', bad)[0], 1) + for bad in ({'run': '../x'}, {'run': 'jam_01?x=1'}, {'run': 'jam_01', 'x': 1}, {'run': 'a' * 101}): + for cmd in ('wake', 'stop'): + self.assertEqual(self.driver(cmd, bad)[0], 1) + self.assertEqual(self.host.requests, []) + + def test_a_host_error_is_a_fixed_refusal(self): + self.use(served_key='synthetic-wrong-' + 'Kit0Value' * 2) + code, out = self.driver('start', START) + self.assertEqual((code, out), (1, {'error': 'Capy answered 401 to GET /api/v1/projects', + 'next': "check your key and Capy's status, then retry"})) + self.assertNotIn('Unauthorized', json.dumps(out)) + + def test_no_driver_file_names_the_key_or_the_keychain(self): + with open(os.path.join(ROOT, 'kernel', 'driver-kit', 'hosts.json')) as f: + host = json.load(f)['capy'] + names = [host['variable'].encode(), host['keychain'].encode()] + with open(os.path.join(HERE, 'README.md'), 'rb') as f: + [key_line] = [line for line in f.read().split(b'\n') if all(n in line for n in names)] + for folder, _, files in os.walk(HERE): + for n in files: + with open(os.path.join(folder, n), 'rb') as f: + lines = f.read().split(b'\n') + rel = os.path.relpath(os.path.join(folder, n), HERE) + for line in lines: + if rel == 'README.md' and line == key_line: + continue + for name in names: + self.assertNotIn(name, line, rel) + self.assertIsNone(KEYCHAIN_TOOLS_SPELLED_IN_PARTS.search(line), rel) + + def test_version_lists_effort_and_the_schema_is_the_kernels(self): + self.assertEqual(self.driver('version'), (0, {'driver': 'capy', 'records': ['openwiz:records v1'], + 'can': ['start', 'wake', 'stop', 'effort']})) + with open(os.path.join(ROOT, 'kernel', 'driver-kit', 'schema.json'), 'rb') as a, \ + open(os.path.join(HERE, 'schema.json'), 'rb') as b: + self.assertEqual(a.read(), b.read()) + + +if __name__ == '__main__': + unittest.main() diff --git a/changes/2579.md b/changes/2579.md new file mode 100644 index 000000000..9537d9eca --- /dev/null +++ b/changes/2579.md @@ -0,0 +1,3 @@ +kind: added + +OpenWiz can run agents on Capy with Claude Code or Codex models, reaching it only through the key helper so your Capy API key stays in your keychain or environment; it is proven on a fake host until its live check on the real host passes. diff --git a/kernel/driver-kit/hosts.json b/kernel/driver-kit/hosts.json index b43d997b0..846718788 100644 --- a/kernel/driver-kit/hosts.json +++ b/kernel/driver-kit/hosts.json @@ -4,5 +4,11 @@ "variable": "DEVIN_API_KEY", "keychain": "openwiz-devin", "header": "authorization-bearer" + }, + "capy": { + "origin": "https://api.capy.ai", + "variable": "CAPY_API_KEY", + "keychain": "openwiz-capy", + "header": "authorization-bearer" } } From 88d2e960c974fea04342eadb1b89f4dc7ad4c45d Mon Sep 17 00:00:00 2001 From: OpenWiz Builder Date: Fri, 27 Nov 2026 14:26:20 +0000 Subject: [PATCH 2/2] #2579: fix the ddf4537 review: model ids, unresolved retries, wake/stop lock - start takes the schema's model syntax (up to 100 characters, provider-qualified), keeps an anthropic/ or openai/ id that matches the harness, prefixes only a bare one, and refuses the other provider before any call. - a retry that fails after an unanswered create keeps the possible-start guidance; a start the key helper refused before sending keeps the helper's own setup advice. - wake and stop of one run take turns on a per-run lock file, so a wake can't unarchive a thread a stop just archived. - answers may carry fields Capy adds later; a 429 waits Capy's retryAfterSeconds (up to 30) before the one retry; an effort on an unsupported harness gets driver v1's effort refusal. Red receipt: evidence/red-review-ddf4537.txt (7 new proofs fail on ddf4537); green: evidence/green-review-ddf4537.txt (27 of 27). --- adapters/capy/README.md | 7 +- adapters/capy/driver | 94 ++++++++++++++----- .../capy/evidence/green-review-ddf4537.txt | 39 ++++++++ adapters/capy/evidence/red-review-ddf4537.txt | 91 ++++++++++++++++++ adapters/capy/fixtures/fake_capy.py | 24 ++++- adapters/capy/test_driver.py | 87 +++++++++++++++-- 6 files changed, 304 insertions(+), 38 deletions(-) create mode 100644 adapters/capy/evidence/green-review-ddf4537.txt create mode 100644 adapters/capy/evidence/red-review-ddf4537.txt diff --git a/adapters/capy/README.md b/adapters/capy/README.md index d49378f49..16c0b8fdb 100644 --- a/adapters/capy/README.md +++ b/adapters/capy/README.md @@ -2,7 +2,7 @@ Login: held by Capy -Effort: passed as the run's Capy `reasoningMode`; an effort the run's model doesn't offer is refused with driver v1's effort refusal, and nothing starts +Effort: passed as the run's Capy `reasoningMode` for `claude`, `claude-code` and `codex`; an effort the run's model doesn't offer, or any effort on another harness, is refused with driver v1's effort refusal, and nothing starts The key is your `CAPY_API_KEY`, or the keychain entry `openwiz-capy`; only the kit's key helper reads it. @@ -12,11 +12,12 @@ The key is your `CAPY_API_KEY`, or the keychain entry `openwiz-capy`; only the k A [driver v1](../../kernel/driver.v1.md) for [Capy](https://capy.ai). **Platforms:** Linux and macOS, Python 3.9 or later, standard library only. Every call to Capy goes through the [key helper](../../kernel/driver-kit/README.md#key-hosts) (driver v1 N4), as host `capy` of `kernel/driver-kit/hosts.json`: the driver sends only a method, a path and a body, never a key or an address. -- **`start`** runs the ticket in the Capy project `CAPY_PROJECT_ID` names, when you set it (a project id from Capy's Settings, Projects & setup; not a credential), or else in the one project that lists the repository (`GET /api/v1/projects`). With neither, or with more than one project listing it, it refuses and names `CAPY_PROJECT_ID`; it never guesses a project. It creates a thread there (`POST /api/v1/threads`) with the ticket's prompt and the model `anthropic/` for `claude` or `claude-code`, or `openai/` for `codex`, and answers the thread's id as the run. A create whose answer is lost is sent once more with the same `requestId`, which Capy turns into the same thread. An effort outside Capy's `reasoningMode` values (`none`, `instant`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`) is refused with driver v1's effort refusal before any call. When Capy refuses the model, the driver reads your models (`GET /api/v1/models`) to say why, and says it is unsure when that list is unreadable. +- **`start`** runs the ticket in the Capy project `CAPY_PROJECT_ID` names, when you set it (a project id from Capy's Settings, Projects & setup; not a credential), or else in the one project that lists the repository (`GET /api/v1/projects`). With neither, or with more than one project listing it, it refuses and names `CAPY_PROJECT_ID`; it never guesses a project. It creates a thread there (`POST /api/v1/threads`) with the ticket's prompt and the model `anthropic/` for `claude` or `claude-code`, or `openai/` for `codex`, and answers the thread's id as the run. A model already named `anthropic/…` (or `openai/…` for `codex`) is sent as it is; one named for the other provider is refused before any call. A create whose answer is lost is sent once more with the same `requestId`, which Capy turns into the same thread; if that second try fails too, however it fails, the driver still says a thread may have started. A create Capy rate-limits (429) is sent once more after the seconds Capy asks for, up to 30; a longer wait is refused. A start the key helper refused before sending anything (no key, say) answers the helper's own advice. An effort outside Capy's `reasoningMode` values (`none`, `instant`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`) is refused with driver v1's effort refusal before any call. When Capy refuses the model, the driver reads your models (`GET /api/v1/models`) to say why, and says it is unsure when that list is unreadable. - **`wake`** reads the thread (`GET /api/v1/threads/`) and steers a follow-up into it (`POST /api/v1/threads//message`). A message would unarchive a stopped thread, so a wake of an archived one is refused before anything is sent. - **`stop`** interrupts the thread (`POST /api/v1/threads//interrupt`), then archives it (`POST /api/v1/threads//archive`). Stopping an archived thread answers again. +- A wake and a stop of one run take turns on a lock file, `.lock` in `OPENWIZ_CAPY_STATE` (default `~/.local/state/openwiz/capy`), so a wake that read the thread before a stop archived it can't send its message after the archive and unarchive it. The lock holds only on this computer. -The driver keeps no state of its own: Capy holds every run. It reads each Capy answer only in the shape [Capy's OpenAPI document](https://docs.capy.ai/openapi.json) gives it (every required field, no unlisted one, the thread's own id, its documented status and a Boolean `archived`). Any other answer is refused, and the error names the run when one may exist: a run is unknown only on Capy's own `ThreadNotFound` for that id, a wake or a stop succeeds only on Capy's receipt for each write, a project is picked only from a readable project list, and a start answers only a thread for the project it sent (or none named). +The driver keeps no run state of its own, only those lock files: Capy holds every run. It reads each Capy answer only in the shape [Capy's OpenAPI document](https://docs.capy.ai/openapi.json) gives it (every required field, the thread's own id, its documented status and a Boolean `archived`; a field Capy adds later is ignored). Any other answer is refused, and the error names the run when one may exist: a run is unknown only on Capy's own `ThreadNotFound` for that id, a wake or a stop succeeds only on Capy's receipt for each write, a project is picked only from a readable project list, and a start answers only a thread for the project it sent (or none named). Keep `schema.json` byte for byte the kit's `kernel/driver-kit/schema.json`: the kit checks it. diff --git a/adapters/capy/driver b/adapters/capy/driver index db6698940..fb77e0cc0 100755 --- a/adapters/capy/driver +++ b/adapters/capy/driver @@ -2,7 +2,7 @@ # SECURITY: driver v1 N4. Every Capy call goes through the kit's key helper, which alone reads the key and picks the # address; this driver sends it only a host name, a method, a path and a body, and never names, reads or prints the # key. It shows no text the host answered: each error names only the status, the method and the path. -import json, os, re, subprocess, sys, time, uuid +import fcntl, json, os, re, subprocess, sys, time, uuid sys.dont_write_bytecode = True HERE = os.path.dirname(os.path.abspath(__file__)) @@ -11,28 +11,30 @@ HOST = 'capy' VERSION = {'driver': 'capy', 'records': ['openwiz:records v1'], 'can': ['start', 'wake', 'stop', 'effort']} START = {'repository': r'[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}', 'ticket': None, 'skill': r'(?=.{1,60}$)[a-z0-9]+(-[a-z0-9]+)*', 'harness': r'[a-z0-9][a-z0-9._-]{0,59}', - 'model': r'[A-Za-z0-9][A-Za-z0-9 ._:@+-]{0,59}'} + 'model': r'(?=.{1,100}$)[A-Za-z0-9][A-Za-z0-9 ._:@+-]*(/[A-Za-z0-9][A-Za-z0-9 ._:@+-]*)*'} RUN = {'run': r'[A-Za-z0-9][A-Za-z0-9_-]{0,99}'} EFFORT = r'[a-z][a-z0-9-]{0,19}' PROJECT = r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,190}' PROVIDERS = {'claude': 'anthropic', 'claude-code': 'anthropic', 'codex': 'openai'} POLL = float(os.environ.get('OPENWIZ_CAPY_POLL') or 3) +WAIT_AT_MOST = 30 +STATE = os.environ.get('OPENWIZ_CAPY_STATE') or os.path.expanduser('~/.local/state/openwiz/capy') +UNSENT = tuple('the key helper refused: ' + why for why in ( + 'no key in either ', 'the key in ', "the kit's fake host gave no test key", 'the request holds the key', + 'OPENWIZ_HOSTKEY_TEST_ORIGIN is not')) NO_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") WOKEN = 'You were woken: read the ticket again and carry on.' STOPPED = 'start a new run' UNSURE = 'open the run in Capy to see its state, then retry' # External: the shapes below are Capy's documented answers (https://docs.capy.ai/openapi.json): every field a -# schema requires, and no field it doesn't list. An answer off its shape is never read as success or absence. +# schema requires; a field Capy adds later is ignored. An answer off its shape is never read as success or absence. REASONING = ('none', 'instant', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max') STATUSES = ('working', 'waiting', 'idle', 'failed', 'archived') THREAD = set('id projectId authorId previousAuthorId title titleCustom status archived lastModelId queuedAt linearIssue ' 'pullRequestAuthor usage createdAt updatedAt lastActivityAt hasUnreads mentionCount owed member'.split()) -THREAD_MAY = set('modelDefault needsYou ask crewNeedsYou participated crewMentionCount captain crewCount subscribed ' - 'personal visibility'.split()) PROJECT_KEYS = set('id name description code visibility repos createdAt updatedAt'.split()) MODEL_KEYS = set('id name billing route reasoningModes fast pro ultrafast'.split()) -REJECTED_MAY = {'rejection', 'modelId', 'service', 'health'} class Refused(Exception): @@ -85,8 +87,8 @@ def obj(value): return value if isinstance(value, dict) else {} -def shaped(value, required, may=()): - return isinstance(value, dict) and set(required) <= set(value) <= set(required) | set(may) +def shaped(value, required): + return isinstance(value, dict) and set(required) <= set(value) def fit(line, fallback): @@ -96,7 +98,7 @@ def fit(line, fallback): def a_thread(value, run, receipt=()): # External: an archived thread doesn't run (https://docs.capy.ai/threads#archive-a-thread), so a running archived one # is not a state the driver can read. - if not (shaped(value, THREAD | set(receipt), THREAD_MAY) and value['id'] == run and value['status'] in STATUSES + if not (shaped(value, THREAD | set(receipt)) and value['id'] == run and value['status'] in STATUSES and type(value['archived']) is bool and (value['projectId'] is None or isinstance(value['projectId'], str))): return None if value['archived'] and value['status'] in ('working', 'waiting') or value['status'] == 'archived' and not value[ @@ -161,8 +163,28 @@ def rejected(req, model): 'it, then start again') +def model_id(req): + provider = PROVIDERS[req['harness']] + if '/' not in req['model']: + return provider + '/' + req['model'] + if req['model'].partition('/')[0] != provider: + raise Refused('model %s is not an %s model, as harness %s needs' % (req['model'], provider, req['harness']), + 'name the model bare, or as %s/' % provider) + return req['model'] + + +def waited(got): + if not (shaped(got, {'_tag', 'retryAfterSeconds'}) and got['_tag'] == 'capy/RateLimited' + and type(got['retryAfterSeconds']) is int and got['retryAfterSeconds'] >= 0): + return POLL + if got['retryAfterSeconds'] > WAIT_AT_MOST: + raise Refused('Capy answered 429 to POST /api/v1/threads and asked to wait %d seconds' + % got['retryAfterSeconds'], 'wait that long, then start again') + return got['retryAfterSeconds'] + + def create(req): - model = {'modelId': '%s/%s' % (PROVIDERS[req['harness']], req['model'])} + model = {'modelId': model_id(req)} if 'effort' in req: if req['effort'] not in REASONING: raise no_effort(req) @@ -175,23 +197,30 @@ def create(req): 'model': model} lost = fit('archive the Capy thread titled %s if it is there, then start again' % title, 'archive the Capy thread titled OpenWiz: # if it is there, then start again') + unsure = None for attempt in (1, 2): try: status, got = ask('POST', '/api/v1/threads', body, also=tuple(range(400, 600))) except Refused as e: - status, why = None, e.args[0] - if status == 400 and shaped(got, {'_tag', 'message', 'candidates'}, REJECTED_MAY) and got[ - '_tag'] == 'ModelSelection.Rejected': - rejected(req, model) + if not unsure and e.args[0].startswith(UNSENT): + raise + status, got, unsure = None, None, unsure or e.args[0] if status is not None and status < 300: break - if status is not None and status != 429 and status < 500: - raise Refused('Capy answered %d to POST /api/v1/threads' % status, - 'check your key, your Capy project and the start\'s fields, then start again') - why = why if status is None else 'Capy answered %d to POST /api/v1/threads' % status - if attempt == 2: - raise Refused(why + ', so a thread may have started', lost) - time.sleep(POLL) + if status is not None and status >= 500: + unsure = unsure or 'Capy answered %d to POST /api/v1/threads' % status + if unsure and attempt == 2: + raise Refused(unsure + ', so a thread may have started', lost) + if status == 429 and attempt == 2: + raise Refused('Capy answered 429 to POST /api/v1/threads twice', 'wait a minute, then start again') + if unsure or status == 429: + time.sleep(POLL if unsure else waited(got)) + continue + if status == 400 and shaped(got, {'_tag', 'message', 'candidates'}) and got[ + '_tag'] == 'ModelSelection.Rejected': + rejected(req, model) + raise Refused('Capy answered %d to POST /api/v1/threads' % status, + 'check your key, your Capy project and the start\'s fields, then start again') run = obj(got).get('id') run = run if isinstance(run, str) and re.fullmatch(RUN['run'], run) else None found = a_thread(got, run) if run and status == 200 else None @@ -203,7 +232,8 @@ def create(req): def thread(run): status, found = ask('GET', '/api/v1/threads/' + run, also=(404,)) - if status == 404 and found == {'_tag': 'capy/ThreadNotFound', 'threadId': run}: + if status == 404 and shaped(found, {'_tag', 'threadId'}) and (found['_tag'], found['threadId']) == ( + 'capy/ThreadNotFound', run): raise Refused('Capy has no run ' + run, STOPPED) if status != 200 or not a_thread(found, run): raise Refused('Capy answered %d to GET /api/v1/threads/%s in a shape the driver cannot read' % (status, run), @@ -211,6 +241,17 @@ def thread(run): return found +def lock(run): + # External: a message unarchives and wakes an archived Capy thread + # (https://docs.capy.ai/threads#archive-is-dormant), so a wake and a stop of one run take turns on its lock. + try: + os.makedirs(STATE, mode=0o700, exist_ok=True) + fcntl.flock(os.open(os.path.join(STATE, run + '.lock'), os.O_RDONLY | os.O_CREAT, 0o600), fcntl.LOCK_EX) + except OSError: + raise Refused('the driver cannot lock run ' + run, + 'make OPENWIZ_CAPY_STATE (or ~/.local/state/openwiz/capy) a folder you can write') + + def answer(cmd): if cmd == 'version': return VERSION @@ -219,16 +260,16 @@ def answer(cmd): return json.load(f) if cmd == 'start': req = read(START) + if req['harness'] not in PROVIDERS and 'effort' in req: + raise no_effort(req) if req['harness'] not in PROVIDERS: raise Refused('harness %s is not one Capy runs for OpenWiz' % req['harness'], 'use claude-code (or claude) or codex') return {'run': create(req)} if cmd == 'wake': run = read(RUN)['run'] - found = thread(run) - # External: a message unarchives and wakes an archived Capy thread - # (https://docs.capy.ai/threads#archive-is-dormant). - if found['archived']: + lock(run) + if thread(run)['archived']: raise Refused('run %s is stopped' % run, STOPPED) if not admitted(*ask('POST', '/api/v1/threads/%s/message' % run, {'text': WOKEN, 'delivery': 'steer'})): raise Refused('Capy did not confirm it took the wake for run ' + run, @@ -236,6 +277,7 @@ def answer(cmd): return {'run': run, 'woke': True} if cmd == 'stop': run = read(RUN)['run'] + lock(run) if not thread(run)['archived']: if not admitted(*ask('POST', '/api/v1/threads/%s/interrupt' % run)): raise Refused('Capy did not confirm it interrupted run %s, so it may still be running' % run, diff --git a/adapters/capy/evidence/green-review-ddf4537.txt b/adapters/capy/evidence/green-review-ddf4537.txt new file mode 100644 index 000000000..7761fdadd --- /dev/null +++ b/adapters/capy/evidence/green-review-ddf4537.txt @@ -0,0 +1,39 @@ +$ python3 -I adapters/capy/test_driver.py -v (the proofs of the review at ddf4537, after the fix; synthetic fake Capy on loopback) +test_a_capy_qualified_model_is_kept_and_only_a_bare_one_gets_the_harness_prefix (__main__.Driver.test_a_capy_qualified_model_is_kept_and_only_a_bare_one_gets_the_harness_prefix) ... ok +test_a_create_receipt_off_its_shape_or_for_another_project_is_a_possible_start (__main__.Driver.test_a_create_receipt_off_its_shape_or_for_another_project_is_a_possible_start) ... ok +test_a_host_error_is_a_fixed_refusal (__main__.Driver.test_a_host_error_is_a_fixed_refusal) ... ok +test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread (__main__.Driver.test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread) ... ok +test_a_project_list_off_its_documented_shape_is_refused_before_any_create (__main__.Driver.test_a_project_list_off_its_documented_shape_is_refused_before_any_create) ... ok +test_a_rate_limited_create_waits_the_seconds_capy_asks_then_sends_it_once_more (__main__.Driver.test_a_rate_limited_create_waits_the_seconds_capy_asks_then_sends_it_once_more) ... ok +test_a_rejected_effort_needs_a_readable_model_list_to_say_the_model_cannot_set_it (__main__.Driver.test_a_rejected_effort_needs_a_readable_model_list_to_say_the_model_cannot_set_it) ... ok +test_a_start_the_key_helper_never_sent_keeps_the_helpers_setup_advice (__main__.Driver.test_a_start_the_key_helper_never_sent_keeps_the_helpers_setup_advice) ... ok +test_a_stop_during_a_wake_of_the_same_run_waits_for_it_and_leaves_the_run_stopped (__main__.Driver.test_a_stop_during_a_wake_of_the_same_run_waits_for_it_and_leaves_the_run_stopped) ... /usr/lib/python3.11/unittest/case.py:579: ResourceWarning: unclosed file <_io.TextIOWrapper name=6 encoding='UTF-8'> + if method() is not None: +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.11/unittest/case.py:579: ResourceWarning: unclosed file <_io.TextIOWrapper name=8 encoding='UTF-8'> + if method() is not None: +ResourceWarning: Enable tracemalloc to get the object allocation traceback +ok +test_an_effort_outside_capys_reasoning_modes_is_refused_before_any_request (__main__.Driver.test_an_effort_outside_capys_reasoning_modes_is_refused_before_any_request) ... ok +test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing (__main__.Driver.test_an_effort_the_model_does_not_offer_is_the_exact_refusal_and_starts_nothing) ... ok +test_an_unknown_run_is_refused_by_wake_and_stop (__main__.Driver.test_an_unknown_run_is_refused_by_wake_and_stop) ... ok +test_an_unreadable_or_mismatched_thread_read_refuses_wake_and_stop_before_any_write (__main__.Driver.test_an_unreadable_or_mismatched_thread_read_refuses_wake_and_stop_before_any_write) ... ok +test_effort_reaches_the_host_as_the_model_reasoning_mode (__main__.Driver.test_effort_reaches_the_host_as_the_model_reasoning_mode) ... ok +test_every_refusal_fits_d3_even_for_the_longest_repository_and_ticket (__main__.Driver.test_every_refusal_fits_d3_even_for_the_longest_repository_and_ticket) ... ok +test_every_request_reaches_the_host_with_the_key_header_only (__main__.Driver.test_every_request_reaches_the_host_with_the_key_header_only) ... ok +test_fields_capy_adds_to_its_answers_change_nothing (__main__.Driver.test_fields_capy_adds_to_its_answers_change_nothing) ... ok +test_inputs_off_the_schema_are_refused_before_any_request (__main__.Driver.test_inputs_off_the_schema_are_refused_before_any_request) ... ok +test_kit_passes_all_five_on_the_fake_host (__main__.Driver.test_kit_passes_all_five_on_the_fake_host) ... ok +test_no_driver_file_names_the_key_or_the_keychain (__main__.Driver.test_no_driver_file_names_the_key_or_the_keychain) ... ok +test_start_creates_one_thread_in_the_repository_project_on_the_harness_model (__main__.Driver.test_start_creates_one_thread_in_the_repository_project_on_the_harness_model) ... ok +test_start_refuses_a_harness_capy_has_no_subscription_for (__main__.Driver.test_start_refuses_a_harness_capy_has_no_subscription_for) ... ok +test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses (__main__.Driver.test_start_takes_capy_project_id_else_the_project_listing_the_repository_else_refuses) ... ok +test_stop_interrupts_then_archives_and_a_wake_after_it_is_refused (__main__.Driver.test_stop_interrupts_then_archives_and_a_wake_after_it_is_refused) ... ok +test_version_lists_effort_and_the_schema_is_the_kernels (__main__.Driver.test_version_lists_effort_and_the_schema_is_the_kernels) ... ok +test_wake_and_stop_refuse_unless_capy_confirms_each_write (__main__.Driver.test_wake_and_stop_refuse_unless_capy_confirms_each_write) ... ok +test_wake_steers_a_message_into_the_same_thread_and_its_note_is_edited (__main__.Driver.test_wake_steers_a_message_into_the_same_thread_and_its_note_is_edited) ... ok + +---------------------------------------------------------------------- +Ran 27 tests in 31.881s + +OK diff --git a/adapters/capy/evidence/red-review-ddf4537.txt b/adapters/capy/evidence/red-review-ddf4537.txt new file mode 100644 index 000000000..2ad496188 --- /dev/null +++ b/adapters/capy/evidence/red-review-ddf4537.txt @@ -0,0 +1,91 @@ +$ python3 -I adapters/capy/test_driver.py (the proofs of the review at ddf4537, before the fix; the key variable and keychain entry the helper named are shown as and ) +F..F.F.FF/usr/lib/python3.11/unittest/case.py:622: ResourceWarning: unclosed file <_io.TextIOWrapper name=6 encoding='UTF-8'> + with outcome.testPartExecutor(self): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.11/unittest/case.py:622: ResourceWarning: unclosed file <_io.TextIOWrapper name=8 encoding='UTF-8'> + with outcome.testPartExecutor(self): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +.......F....F..... +====================================================================== +FAIL: test_a_capy_qualified_model_is_kept_and_only_a_bare_one_gets_the_harness_prefix (__main__.Driver.test_a_capy_qualified_model_is_kept_and_only_a_bare_one_gets_the_harness_prefix) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 173, in test_a_capy_qualified_model_is_kept_and_only_a_bare_one_gets_the_harness_prefix + run = self.started(model='anthropic/claude-synthetic-1') + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "adapters/capy/test_driver.py", line 103, in started + self.assertEqual(code, 0, out) +AssertionError: 1 != 0 : {'error': 'model is not valid', 'next': 'fix model as `driver schema` shows'} + +====================================================================== +FAIL: test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread (__main__.Driver.test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 211, in test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread + self.assertEqual(self.driver('start', START)[1], out) +AssertionError: {'err[15 chars]ered 401 to POST /api/v1/threads', 'next': "ch[69 chars]ain"} != {'err[15 chars]ered 503 to POST /api/v1/threads, so a thread [112 chars]ain'} +- {'error': 'Capy answered 401 to POST /api/v1/threads', +? ^ ^ - + ++ {'error': 'Capy answered 503 to POST /api/v1/threads, so a thread may have ' +? ^ ^ +++++++++++++++++++++++ + +- 'next': "check your key, your Capy project and the start's fields, then start " +- 'again'} ++ 'started', ++ 'next': 'archive the Capy thread titled OpenWiz: example/site#7 if it is ' ++ 'there, then start again'} + +====================================================================== +FAIL: test_a_rate_limited_create_waits_the_seconds_capy_asks_then_sends_it_once_more (__main__.Driver.test_a_rate_limited_create_waits_the_seconds_capy_asks_then_sends_it_once_more) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 225, in test_a_rate_limited_create_waits_the_seconds_capy_asks_then_sends_it_once_more + self.assertGreaterEqual(time.monotonic() - began, 1) +AssertionError: 0.14918409008532763 not greater than or equal to 1 + +====================================================================== +FAIL: test_a_start_the_key_helper_never_sent_keeps_the_helpers_setup_advice (__main__.Driver.test_a_start_the_key_helper_never_sent_keeps_the_helpers_setup_advice) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 218, in test_a_start_the_key_helper_never_sent_keeps_the_helpers_setup_advice + self.assertTrue(out['next'].startswith('unset OPENWIZ_HOSTKEY_TEST_ORIGIN'), out) +AssertionError: False is not true : {'error': "the key helper refused: the kit's fake host gave no test key; under OPENWIZ_HOSTKEY_TEST_ORIGIN the helper never reads or the keychain entry , so a thread may have started", 'next': 'archive the Capy thread titled OpenWiz: example/site#7 if it is there, then start again'} + +====================================================================== +FAIL: test_a_stop_during_a_wake_of_the_same_run_waits_for_it_and_leaves_the_run_stopped (__main__.Driver.test_a_stop_during_a_wake_of_the_same_run_waits_for_it_and_leaves_the_run_stopped) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 273, in test_a_stop_during_a_wake_of_the_same_run_waits_for_it_and_leaves_the_run_stopped + self.assertTrue(self.host.threads[run]['archived']) +AssertionError: False is not true + +====================================================================== +FAIL: test_fields_capy_adds_to_its_answers_change_nothing (__main__.Driver.test_fields_capy_adds_to_its_answers_change_nothing) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 277, in test_fields_capy_adds_to_its_answers_change_nothing + run = self.started() + ^^^^^^^^^^^^^^ + File "adapters/capy/test_driver.py", line 103, in started + self.assertEqual(code, 0, out) +AssertionError: 1 != 0 : {'error': 'Capy answered GET /api/v1/projects in a shape the driver cannot read', 'next': 'set CAPY_PROJECT_ID to the project to run it in (Settings, Projects & setup), then start again'} + +====================================================================== +FAIL: test_start_refuses_a_harness_capy_has_no_subscription_for (__main__.Driver.test_start_refuses_a_harness_capy_has_no_subscription_for) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "adapters/capy/test_driver.py", line 168, in test_start_refuses_a_harness_capy_has_no_subscription_for + self.assertEqual(self.driver('start', dict(START, harness='gemini-cli', effort='high'))[1], { +AssertionError: {'error': 'harness gemini-cli is not one Capy runs f[55 chars]dex'} != {'error': 'Capy cannot run gemini-cli (model claude-[161 chars]ult"} +- {'error': 'harness gemini-cli is not one Capy runs for OpenWiz', +- 'next': 'use claude-code (or claude) or codex'} ++ {'error': 'Capy cannot run gemini-cli (model claude-synthetic-1) at effort ' ++ 'high', ++ '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"} + +---------------------------------------------------------------------- +Ran 27 tests in 27.731s + +FAILED (failures=7) diff --git a/adapters/capy/fixtures/fake_capy.py b/adapters/capy/fixtures/fake_capy.py index f0e043e4a..d77b2395d 100644 --- a/adapters/capy/fixtures/fake_capy.py +++ b/adapters/capy/fixtures/fake_capy.py @@ -38,11 +38,13 @@ def tag(name, **fields): class FakeCapy: - def __init__(self, key, tracker, projects=PROJECTS, models=MODELS, lose_creates=0, served_key=None, answers=()): + def __init__(self, key, tracker, projects=PROJECTS, models=MODELS, lose_creates=0, served_key=None, answers=(), + replay=None, throttle=(), widen=None): self.key, self.tracker, self.projects, self.models = key, tracker, projects, models self.answers = list(answers) self.served_key = key if served_key is None else served_key - self.lose_creates = lose_creates + self.lose_creates, self.replay, self.throttle, self.widen = lose_creates, replay, list(throttle), widen + self.hold, self.held, self.release = None, threading.Event(), threading.Event() self.requests, self.threads, self.by_request = [], {}, {} self.lock = threading.Lock() host = self @@ -64,7 +66,12 @@ def handle_one(self): code, body = host.route(self.command, self.path, json.loads(raw) if raw else None) except ValueError: code, body = 400, tag('InvalidRequest', message='synthetic: unreadable JSON') - self.reply(code, body) + held = host.hold == (self.command, self.path) + host.hold = None if held else host.hold + if held: + host.held.set() + host.release.wait(60) + self.reply(code, host.widened(body)) def reply(self, code, body): data = json.dumps(body).encode() @@ -85,6 +92,13 @@ def close(self): self.server.shutdown() self.server.server_close() + def widened(self, value): + if isinstance(value, list): + return [self.widened(v) for v in value] + if isinstance(value, dict) and self.widen: + return dict({k: self.widened(v) for k, v in value.items()}, **self.widen) + return value + def calls(self): return [(m, p) for m, p, _, _ in self.requests] @@ -137,6 +151,10 @@ def route(self, method, target, body): if not isinstance(body, dict) or set(body) - CREATE or not {'requestId', 'projectId', 'message'} <= set( body): return 400, tag('InvalidRequest', message='synthetic: not a CreateThreadRequest') + if self.throttle: + return 429, tag('RateLimited', retryAfterSeconds=self.throttle.pop(0)) + if self.replay and body['requestId'] in self.by_request: + return self.replay if body['projectId'] not in [p['id'] for p in self.projects]: return 404, tag('ProjectNotFound', projectId=body['projectId']) model = body.get('model') diff --git a/adapters/capy/test_driver.py b/adapters/capy/test_driver.py index fcc689a37..253910948 100755 --- a/adapters/capy/test_driver.py +++ b/adapters/capy/test_driver.py @@ -10,6 +10,7 @@ import subprocess import sys import tempfile +import time import unittest sys.dont_write_bytecode = True @@ -60,7 +61,8 @@ def setUp(self): self.addCleanup(shutil.rmtree, self.folder, True) self.mark = secrets.token_hex(8) self.tracker = tracker(self.folder) - self.env = dict(os.environ, KIT_TEST=self.mark, OPENWIZ_CAPY_POLL='0.01') + self.env = dict(os.environ, KIT_TEST=self.mark, OPENWIZ_CAPY_POLL='0.01', + OPENWIZ_CAPY_STATE=os.path.join(self.folder, 'state')) self.use() def use(self, **kw): @@ -163,6 +165,19 @@ def test_start_refuses_a_harness_capy_has_no_subscription_for(self): code, out = self.driver('start', dict(START, harness='gemini-cli')) self.assertEqual(out, {'error': 'harness gemini-cli is not one Capy runs for OpenWiz', 'next': 'use claude-code (or claude) or codex'}) + self.assertEqual(self.driver('start', dict(START, harness='gemini-cli', effort='high'))[1], { + 'error': 'Capy cannot run gemini-cli (model claude-synthetic-1) at effort high', 'next': NO_EFFORT}) + self.assertEqual(self.host.requests, []) + + def test_a_capy_qualified_model_is_kept_and_only_a_bare_one_gets_the_harness_prefix(self): + run = self.started(model='anthropic/claude-synthetic-1') + self.assertEqual(self.host.threads[run]['create']['model'], {'modelId': 'anthropic/claude-synthetic-1'}) + run = self.started(harness='codex', model='openai/gpt-synthetic-2', repository='example/other') + self.assertEqual(self.host.threads[run]['create']['model'], {'modelId': 'openai/gpt-synthetic-2'}) + self.host.requests.clear() + self.assertEqual(self.driver('start', dict(START, model='openai/gpt-synthetic-2')), (1, { + 'error': 'model openai/gpt-synthetic-2 is not an anthropic model, as harness claude-code needs', + 'next': 'name the model bare, or as anthropic/'})) self.assertEqual(self.host.requests, []) def test_effort_reaches_the_host_as_the_model_reasoning_mode(self): @@ -192,6 +207,32 @@ def test_a_lost_create_is_retried_with_the_same_request_id_and_starts_one_thread self.assertEqual(out, {'error': 'Capy answered 503 to POST /api/v1/threads, so a thread may have started', 'next': 'archive the Capy thread titled OpenWiz: example/site#7 if it is there, ' 'then start again'}) + self.use(lose_creates=1, replay=(401, fake.tag('Unauthorized'))) + self.assertEqual(self.driver('start', START)[1], out) + self.assertEqual(len(self.host.threads), 1) + + def test_a_start_the_key_helper_never_sent_keeps_the_helpers_setup_advice(self): + self.use(served_key='') + self.env['CAPY_PROJECT_ID'] = 'project_synthetic1' + out = self.refused('start', START, "the key helper refused: the kit's fake host gave no test key") + self.assertTrue(out['next'].startswith('unset OPENWIZ_HOSTKEY_TEST_ORIGIN'), out) + self.assertEqual(self.host.requests, []) + + def test_a_rate_limited_create_waits_the_seconds_capy_asks_then_sends_it_once_more(self): + self.use(throttle=[1]) + began = time.monotonic() + run = self.started() + self.assertGreaterEqual(time.monotonic() - began, 1) + first, second = self.host.bodies('POST', '/api/v1/threads') + self.assertEqual((first, list(self.host.threads)), (second, [run])) + self.use(throttle=[600]) + self.assertEqual(self.driver('start', START), (1, { + 'error': 'Capy answered 429 to POST /api/v1/threads and asked to wait 600 seconds', + 'next': 'wait that long, then start again'})) + self.assertEqual((len(self.host.bodies('POST', '/api/v1/threads')), self.host.threads), (1, {})) + self.use(throttle=[0, 0]) + self.assertEqual(self.driver('start', START)[1], {'error': 'Capy answered 429 to POST /api/v1/threads twice', + 'next': 'wait a minute, then start again'}) def test_wake_steers_a_message_into_the_same_thread_and_its_note_is_edited(self): run = self.started() @@ -213,6 +254,40 @@ def test_stop_interrupts_then_archives_and_a_wake_after_it_is_refused(self): self.assertEqual(self.driver('stop', {'run': run}), (0, {'run': run, 'stopped': True})) self.assertEqual((len(self.posts()), self.host.threads[run]['messages']), (2, [])) + def test_a_stop_during_a_wake_of_the_same_run_waits_for_it_and_leaves_the_run_stopped(self): + run = self.started() + self.host.hold = ('GET', '/api/v1/threads/' + run) + + def begin(cmd): + p = subprocess.Popen([DRIVER, cmd], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=self.env, text=True) + p.stdin.write(json.dumps({'run': run})) + p.stdin.close() + return p + wake = begin('wake') + self.assertTrue(self.host.held.wait(30)) + stop = begin('stop') + try: + stop.wait(1.5) + except subprocess.TimeoutExpired: + pass + self.host.release.set() + self.assertEqual([(json.loads(p.stdout.read()), p.wait(60)) for p in (wake, stop)], + [({'run': run, 'woke': True}, 0), ({'run': run, 'stopped': True}, 0)]) + self.assertTrue(self.host.threads[run]['archived']) + self.env['OPENWIZ_CAPY_STATE'] = self.tracker + self.host.requests.clear() + for cmd in ('wake', 'stop'): + self.assertEqual(self.driver(cmd, {'run': run})[1]['error'], 'the driver cannot lock run ' + run) + self.assertEqual(self.host.requests, []) + + def test_fields_capy_adds_to_its_answers_change_nothing(self): + self.use(widen={'addedLater': [1]}) + run = self.started() + self.assertEqual(self.driver('wake', {'run': run}), (0, {'run': run, 'woke': True})) + self.assertEqual(self.driver('stop', {'run': run}), (0, {'run': run, 'stopped': True})) + self.assertEqual(self.driver('start', dict(START, effort='xhigh'))[1]['next'], NO_EFFORT) + self.assertEqual(self.driver('wake', {'run': 'jam_01UNKNOWN'})[1]['next'], 'start a new run') + def test_an_unknown_run_is_refused_by_wake_and_stop(self): for cmd in ('wake', 'stop'): self.assertEqual(self.driver(cmd, {'run': 'jam_01UNKNOWN'}), @@ -227,7 +302,7 @@ def test_an_unreadable_or_mismatched_thread_read_refuses_wake_and_stop_before_an (404, {'_tag': 'capy/ThreadNotFound', 'threadId': 'jam_other'}), (201, good), (200, dict(good, id='jam_other')), (200, dict(good, archived='yes')), (200, dict(good, status='paused')), (200, dict(good, status='archived')), - (200, dict(good, archived=True, status='working')), (200, dict(good, extra=1)), + (200, dict(good, archived=True, status='working')), (200, {k: v for k, v in good.items() if k != 'usage'})): self.host.answers[:] = [('GET', '/api/v1/threads/' + run, code, body)] for cmd in ('wake', 'stop'): @@ -239,7 +314,7 @@ def test_wake_and_stop_refuse_unless_capy_confirms_each_write(self): run = self.started() receipt = {'id': '01SYNTHETIC' + '0' * 15, 'deduped': False} for code, body in ((200, None), (200, {}), (200, dict(receipt, id='01SHORT')), (202, receipt), - (200, dict(receipt, deduped='no')), (200, dict(receipt, extra=1))): + (200, dict(receipt, deduped='no'))): for cmd, route in (('wake', 'message'), ('stop', 'interrupt')): self.host.answers[:] = [('POST', '/api/v1/threads/%s/%s' % (run, route), code, body)] self.host.requests.clear() @@ -254,9 +329,9 @@ def test_wake_and_stop_refuse_unless_capy_confirms_each_write(self): def test_a_project_list_off_its_documented_shape_is_refused_before_any_create(self): good, other = fake.PROJECTS - for body in (None, {}, {'items': None}, {'items': [good], 'more': 1}, {'items': [good, None]}, + for body in (None, {}, {'items': None}, {'items': [good, None]}, {'items': [dict(good, repos=None)]}, {'items': [{k: v for k, v in good.items() if k != 'repos'}]}, - {'items': [dict(good, id=7)]}, {'items': [dict(good, id='')]}, {'items': [dict(good, extra=1)]}, + {'items': [dict(good, id=7)]}, {'items': [dict(good, id='')]}, {'items': [dict(good, repos=[{'repoFullName': 'Example/Site'}])]}, {'items': [good, dict(other, repos='example/other')]}): self.host.answers[:] = [('GET', '/api/v1/projects', 200, body)] @@ -301,7 +376,7 @@ def test_every_refusal_fits_d3_even_for_the_longest_repository_and_ticket(self): def test_inputs_off_the_schema_are_refused_before_any_request(self): for bad in (dict(START, token='kit-probe-not-a-login'), {k: v for k, v in START.items() if k != 'model'}, dict(START, ticket='7'), dict(START, repository='https://example.com/x'), - dict(START, effort='High')): + dict(START, effort='High'), dict(START, model='m' * 101)): self.assertEqual(self.driver('start', bad)[0], 1) for bad in ({'run': '../x'}, {'run': 'jam_01?x=1'}, {'run': 'jam_01', 'x': 1}, {'run': 'a' * 101}): for cmd in ('wake', 'stop'):