Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(contracts): add the contract registry and generate it per language (CHOO-1865)
Louis Amaudruzb35368bc841b
diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.ymlindex 79367ab2a..b300f6e18 100644--- a/.github/workflows/pr-ci.yml+++ b/.github/workflows/pr-ci.yml@@ -46,6 +46,7 @@ jobs:backend: ${{ steps.filter.outputs.backend }}dash: ${{ steps.filter.outputs.dash }}gateway: ${{ steps.filter.outputs.gateway }}+ contracts: ${{ steps.filter.outputs.contracts }}steps:- name: Checkoutuses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4@@ -69,6 +70,15 @@ jobs:gateway:- *shared- 'gateway/**'+ # Spans core/ and dash/, so it gets its own filter rather than+ # riding either tree's.+ contracts:+ - *shared+ - 'contracts.yaml'+ - 'scripts/gen_contracts.py'+ - 'core/switch_core/contracts.py'+ - 'dash/packages/shared/src/contracts.ts'+ - 'dash/packages/switch-agent-runtime/src/contracts.ts'backend:name: Backend (core)@@ -151,6 +161,32 @@ jobs:- name: Test (vitest)run: pnpm -r run test+ contracts:+ name: Contract registry+ # Every artifact carries a compiled-in copy of contracts.yaml, so the copies+ # can drift two ways: editing the source without regenerating, and+ # hand-editing a generated module. `--check` catches both. It needs no+ # formatter or Node toolchain, which is why this is its own small job rather+ # than a step inside the backend or dash trees.+ needs: changes+ if: ${{ needs.changes.outputs.contracts == 'true' || github.event_name == 'push' }}+ runs-on: ubuntu-latest+ steps:+ - name: Checkout+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4++ - name: Set up uv+ uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5+ with:+ python-version: '3.12'+ enable-cache: true++ - name: Sync dependencies+ run: uv sync --project core++ - name: Generated contract modules are current+ run: uv run --project core python scripts/gen_contracts.py --check+gateway:name: Gateway UIneeds: changesdiff --git a/contracts.yaml b/contracts.yamlnew file mode 100644index 000000000..b0371b7a8--- /dev/null+++ b/contracts.yaml@@ -0,0 +1,70 @@+# The contract registry.+#+# A *contract* is a named interface between two Switch artifacts, carrying one+# integer revision. Every artifact that participates in a contract declares two+# numbers for it:+#+# speaks — the newest revision it implements+# accepts — the oldest revision it still handles+#+# Two peers are compatible when their [accepts, speaks] ranges overlap. They+# then operate at the lower of the two `speaks`.+#+# Artifact versions and contract revisions answer different questions and must+# never be derived from one another:+#+# the artifact's semver says WHERE it is (which release you are running)+# the contract revision says WHETHER it talks (can these two interoperate)+#+# Raise `speaks` when you change an interface. Raise `accepts` only when+# dropping support for an older revision — that is a breaking change for every+# peer still on it, and it can never be raised past what is running in the+# field.+#+# This file is the only thing a human edits. The per-language modules are+# generated from it by `just contracts`; CI fails if they are stale or+# hand-edited. Never edit a generated file.++contracts:+ agent-protocol:+ description: >-+ The wire protocol between switch-core's agent bridge and an agent+ runtime: the event stream, its frame shapes, the resume cursor, and the+ tool-call channel.+ artifacts:+ switch-core: { speaks: 1, accepts: 1 }+ agent-runtime: { speaks: 1, accepts: 1 }++ gateway-api:+ description: >-+ The HTTP API switch-core serves to first-party UI clients. Excludes the+ authentication surface, which is deliberately frozen and unversioned so+ that a client can always authenticate far enough to be told what is+ wrong.+ artifacts:+ switch-core: { speaks: 1, accepts: 1 }+ switchdash: { speaks: 1, accepts: 1 }++ stack-compose:+ description: >-+ The interface of the published standalone compose artifact — its service+ names, profiles, and environment variables — which switchdash's+ local-server mode drives.+ artifacts:+ switchdash: { speaks: 1, accepts: 1 }+ compose: { speaks: 1, accepts: 1 }++ sidecar-control:+ description: >-+ How switchdash controls a deployed sidecar on a remote host: the ready+ file it reads, and the control channel it opens.+ artifacts:+ switchdash: { speaks: 1, accepts: 1 }+ sidecar: { speaks: 1, accepts: 1 }++ db-schema:+ description: >-+ The database schema switch-core expects. Internal to switch-core — this+ contract is never disclosed in an externally facing response.+ artifacts:+ switch-core: { speaks: 1, accepts: 1 }diff --git a/core/switch_core/contracts.py b/core/switch_core/contracts.pynew file mode 100644index 000000000..0e170e103--- /dev/null+++ b/core/switch_core/contracts.py@@ -0,0 +1,61 @@+"""Generated from contracts.yaml by scripts/gen_contracts.py.++Do NOT edit this file. Edit contracts.yaml and run `just contracts`.+"""++from typing import Final, NamedTuple+++class ContractRange(NamedTuple):+ """The revisions of one contract an artifact implements.++ Two peers are compatible when their ranges overlap; they then+ operate at the lower of the two `speaks`.+ """++ speaks: int+ accepts: int+++CONTRACTS: Final[dict[str, dict[str, ContractRange]]] = {+ # The wire protocol between switch-core's agent bridge and an agent runtime: the event stream, its frame shapes, the resume cursor, and the tool-call channel.+ "agent-protocol": {+ "switch-core": ContractRange(speaks=1, accepts=1),+ "agent-runtime": ContractRange(speaks=1, accepts=1),+ },+ # The HTTP API switch-core serves to first-party UI clients. Excludes the authentication surface, which is deliberately frozen and unversioned so that a client can always authenticate far enough to be told what is wrong.+ "gateway-api": {+ "switch-core": ContractRange(speaks=1, accepts=1),+ "switchdash": ContractRange(speaks=1, accepts=1),+ },+ # The interface of the published standalone compose artifact — its service names, profiles, and environment variables — which switchdash's local-server mode drives.+ "stack-compose": {+ "switchdash": ContractRange(speaks=1, accepts=1),+ "compose": ContractRange(speaks=1, accepts=1),+ },+ # How switchdash controls a deployed sidecar on a remote host: the ready file it reads, and the control channel it opens.+ "sidecar-control": {+ "switchdash": ContractRange(speaks=1, accepts=1),+ "sidecar": ContractRange(speaks=1, accepts=1),+ },+ # The database schema switch-core expects. Internal to switch-core — this contract is never disclosed in an externally facing response.+ "db-schema": {+ "switch-core": ContractRange(speaks=1, accepts=1),+ },+}+++def contract_range(contract: str, artifact: str) -> ContractRange:+ """Return an artifact's declared range for a contract.++ Raises KeyError for a pair the registry does not know. An+ unregistered pair is a bug in the caller, never a reason to+ assume a default — a wrong default reads as compatible.+ """+ try:+ return CONTRACTS[contract][artifact]+ except KeyError:+ raise KeyError(+ f"contracts.yaml declares no range for artifact {artifact!r} "+ f"in contract {contract!r}"+ ) from Nonediff --git a/core/tests/test_gen_contracts.py b/core/tests/test_gen_contracts.pynew file mode 100644index 000000000..e8c0b6903--- /dev/null+++ b/core/tests/test_gen_contracts.py@@ -0,0 +1,179 @@+"""Tests for the contract registry and the generator that compiles it in.++The registry is the root of every compatibility answer the system will give,+so a malformed entry must fail at build time rather than reach a running+artifact — where a wrong number reads as "compatible".+"""++from __future__ import annotations++import importlib.util+import sys+from pathlib import Path+from types import ModuleType++import pytest+import yaml++from switch_core.contracts import CONTRACTS, contract_range++REPO_ROOT = Path(__file__).resolve().parents[2]+++def _load_generator() -> ModuleType:+ """Import scripts/gen_contracts.py, which is not an installed package."""+ path = REPO_ROOT / "scripts" / "gen_contracts.py"+ spec = importlib.util.spec_from_file_location("gen_contracts", path)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ # Register before executing: dataclasses resolve annotations through+ # sys.modules, and a module absent from it fails to build its fields.+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return module+++gen_contracts = _load_generator()+++def _write_registry(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, body: object+) -> None:+ source = tmp_path / "contracts.yaml"+ source.write_text(yaml.safe_dump({"contracts": body}))+ monkeypatch.setattr(gen_contracts, "SOURCE", source)+++def test_generated_modules_are_current() -> None:+ """The committed modules match what the generator would write.++ CI runs the same check; having it here too means `just test` catches a+ forgotten regeneration before the push rather than after.+ """+ assert gen_contracts.main.__module__ # generator imported cleanly+ contracts = gen_contracts.load_contracts()+ for target in gen_contracts.TARGETS:+ assert target.path.read_text() == target.render(contracts), (+ f"{target.path.relative_to(REPO_ROOT)} is stale — run `just contracts`"+ )+++def test_every_contract_declares_at_least_one_artifact() -> None:+ for name, artifacts in CONTRACTS.items():+ assert artifacts, f"contract {name} declares no artifacts"+++def test_accepts_never_exceeds_speaks() -> None:+ for name, artifacts in CONTRACTS.items():+ for artifact, declared in artifacts.items():+ assert declared.accepts <= declared.speaks, (+ f"{name}/{artifact} declares an empty range"+ )+++def test_contract_range_returns_the_declared_pair() -> None:+ declared = contract_range("agent-protocol", "switch-core")+ assert declared.speaks >= 1+ assert declared.accepts >= 1+++ ("contract", "artifact"),+ [+ ("agent-protocol", "not-an-artifact"),+ ("not-a-contract", "switch-core"),+ # switch-core plays no part in sidecar-control, so asking is a bug.+ ("sidecar-control", "switch-core"),+ ],+)+def test_contract_range_refuses_unregistered_pairs(+ contract: str, artifact: str+) -> None:+ """An unregistered pair raises rather than returning a default.++ Any default here would be a number nobody chose, silently reported as if+ someone had.+ """+ with pytest.raises(KeyError, match="declares no range"):+ contract_range(contract, artifact)+++def test_db_schema_is_declared_only_by_switch_core() -> None:+ """db-schema is internal, and must never gain an external peer.++ It is excluded from every externally facing response; a second artifact+ appearing here would mean that exclusion had stopped being true.+ """+ assert set(CONTRACTS["db-schema"]) == {"switch-core"}+++def test_registry_rejects_an_empty_range(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _write_registry(+ tmp_path,+ monkeypatch,+ {"demo": {"description": "d", "artifacts": {"a": {"speaks": 1, "accepts": 2}}}},+ )+ with pytest.raises(ValueError, match="is above speaks"):+ gen_contracts.load_contracts()+++def test_registry_rejects_a_non_integer_revision(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _write_registry(+ tmp_path,+ monkeypatch,+ {+ "demo": {+ "description": "d",+ "artifacts": {"a": {"speaks": "1", "accepts": 1}},+ }+ },+ )+ with pytest.raises(ValueError, match="must be an integer"):+ gen_contracts.load_contracts()+++def test_registry_rejects_a_zero_revision(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Revisions start at 1 so that a missing or zero-valued field is distinct."""+ _write_registry(+ tmp_path,+ monkeypatch,+ {"demo": {"description": "d", "artifacts": {"a": {"speaks": 0, "accepts": 0}}}},+ )+ with pytest.raises(ValueError, match="must be an integer"):+ gen_contracts.load_contracts()+++def test_registry_rejects_a_missing_description(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _write_registry(+ tmp_path,+ monkeypatch,+ {"demo": {"artifacts": {"a": {"speaks": 1, "accepts": 1}}}},+ )+ with pytest.raises(ValueError, match="description is required"):+ gen_contracts.load_contracts()+++def test_registry_rejects_extra_declaration_keys(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Only speaks and accepts. A stray key is a misunderstanding, not an extra."""+ _write_registry(+ tmp_path,+ monkeypatch,+ {+ "demo": {+ "description": "d",+ "artifacts": {"a": {"speaks": 1, "accepts": 1, "version": "1.2.3"}},+ }+ },+ )+ with pytest.raises(ValueError, match="expected exactly"):+ gen_contracts.load_contracts()diff --git a/dash/packages/shared/src/contracts.ts b/dash/packages/shared/src/contracts.tsnew file mode 100644index 000000000..6d3baedd4--- /dev/null+++ b/dash/packages/shared/src/contracts.ts@@ -0,0 +1,63 @@+/**+ * Generated from contracts.yaml by scripts/gen_contracts.py.+ *+ * Do NOT edit this file. Edit contracts.yaml and run `just contracts`.+ */++/**+ * The revisions of one contract an artifact implements.+ *+ * Two peers are compatible when their ranges overlap; they then+ * operate at the lower of the two `speaks`.+ */+export interface ContractRange {+ readonly speaks: number;+ readonly accepts: number;+}++export const CONTRACTS = {+ // The wire protocol between switch-core's agent bridge and an agent runtime: the event stream, its frame shapes, the resume cursor, and the tool-call channel.+ 'agent-protocol': {+ 'switch-core': { speaks: 1, accepts: 1 },+ 'agent-runtime': { speaks: 1, accepts: 1 },+ },+ // The HTTP API switch-core serves to first-party UI clients. Excludes the authentication surface, which is deliberately frozen and unversioned so that a client can always authenticate far enough to be told what is wrong.+ 'gateway-api': {+ 'switch-core': { speaks: 1, accepts: 1 },+ switchdash: { speaks: 1, accepts: 1 },+ },+ // The interface of the published standalone compose artifact — its service names, profiles, and environment variables — which switchdash's local-server mode drives.+ 'stack-compose': {+ switchdash: { speaks: 1, accepts: 1 },+ compose: { speaks: 1, accepts: 1 },+ },+ // How switchdash controls a deployed sidecar on a remote host: the ready file it reads, and the control channel it opens.+ 'sidecar-control': {+ switchdash: { speaks: 1, accepts: 1 },+ sidecar: { speaks: 1, accepts: 1 },+ },+ // The database schema switch-core expects. Internal to switch-core — this contract is never disclosed in an externally facing response.+ 'db-schema': {+ 'switch-core': { speaks: 1, accepts: 1 },+ },+} as const satisfies Record<string, Record<string, ContractRange>>;++export type ContractName = keyof typeof CONTRACTS;++/**+ * Return an artifact's declared range for a contract.+ *+ * Throws for a pair the registry does not know. An unregistered pair+ * is a bug in the caller, never a reason to assume a default — a wrong+ * default reads as compatible.+ */+export function contractRange(contract: string, artifact: string): ContractRange {+ const registry = CONTRACTS as Record<string, Record<string, ContractRange>>;+ const declared = registry[contract]?.[artifact];+ if (declared === undefined) {+ throw new Error(+ `contracts.yaml declares no range for artifact '${artifact}' in contract '${contract}'`+ );+ }+ return declared;+}diff --git a/dash/packages/shared/src/index.ts b/dash/packages/shared/src/index.tsindex 6b8d58af9..09f4524d3 100644--- a/dash/packages/shared/src/index.ts+++ b/dash/packages/shared/src/index.ts@@ -8,6 +8,7 @@ export {type Ok,type Result,} from './result';+export { CONTRACTS, contractRange, type ContractName, type ContractRange } from './contracts';export { Emitter } from './emitter';export { isDeepEqual } from './deep-equal';export type { IDisposable, IInitializable, ILifecycle, Lease, Unsubscribe } from './lifecycle';diff --git a/dash/packages/switch-agent-runtime/src/contracts.ts b/dash/packages/switch-agent-runtime/src/contracts.tsnew file mode 100644index 000000000..6d3baedd4--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/contracts.ts@@ -0,0 +1,63 @@+/**+ * Generated from contracts.yaml by scripts/gen_contracts.py.+ *+ * Do NOT edit this file. Edit contracts.yaml and run `just contracts`.+ */++/**+ * The revisions of one contract an artifact implements.+ *+ * Two peers are compatible when their ranges overlap; they then+ * operate at the lower of the two `speaks`.+ */+export interface ContractRange {+ readonly speaks: number;+ readonly accepts: number;+}++export const CONTRACTS = {+ // The wire protocol between switch-core's agent bridge and an agent runtime: the event stream, its frame shapes, the resume cursor, and the tool-call channel.+ 'agent-protocol': {+ 'switch-core': { speaks: 1, accepts: 1 },+ 'agent-runtime': { speaks: 1, accepts: 1 },+ },+ // The HTTP API switch-core serves to first-party UI clients. Excludes the authentication surface, which is deliberately frozen and unversioned so that a client can always authenticate far enough to be told what is wrong.+ 'gateway-api': {+ 'switch-core': { speaks: 1, accepts: 1 },+ switchdash: { speaks: 1, accepts: 1 },+ },+ // The interface of the published standalone compose artifact — its service names, profiles, and environment variables — which switchdash's local-server mode drives.+ 'stack-compose': {+ switchdash: { speaks: 1, accepts: 1 },+ compose: { speaks: 1, accepts: 1 },+ },+ // How switchdash controls a deployed sidecar on a remote host: the ready file it reads, and the control channel it opens.+ 'sidecar-control': {+ switchdash: { speaks: 1, accepts: 1 },+ sidecar: { speaks: 1, accepts: 1 },+ },+ // The database schema switch-core expects. Internal to switch-core — this contract is never disclosed in an externally facing response.+ 'db-schema': {+ 'switch-core': { speaks: 1, accepts: 1 },+ },+} as const satisfies Record<string, Record<string, ContractRange>>;++export type ContractName = keyof typeof CONTRACTS;++/**+ * Return an artifact's declared range for a contract.+ *+ * Throws for a pair the registry does not know. An unregistered pair+ * is a bug in the caller, never a reason to assume a default — a wrong+ * default reads as compatible.+ */+export function contractRange(contract: string, artifact: string): ContractRange {+ const registry = CONTRACTS as Record<string, Record<string, ContractRange>>;+ const declared = registry[contract]?.[artifact];+ if (declared === undefined) {+ throw new Error(+ `contracts.yaml declares no range for artifact '${artifact}' in contract '${contract}'`+ );+ }+ return declared;+}diff --git a/dash/packages/switch-agent-runtime/src/index.ts b/dash/packages/switch-agent-runtime/src/index.tsindex 9d2a6f3ba..81ae9cf69 100644--- a/dash/packages/switch-agent-runtime/src/index.ts+++ b/dash/packages/switch-agent-runtime/src/index.ts@@ -16,6 +16,7 @@* does not drag in the MCP SDK.*/+export { CONTRACTS, contractRange, type ContractName, type ContractRange } from './contracts';export {BEAT_INTERVAL_MS,SwitchEventStream,diff --git a/justfile b/justfileindex 908f60854..4c974d778 100644--- a/justfile+++ b/justfile@@ -78,6 +78,19 @@ check:typecheck:uv run --project core mypy --config-file core/pyproject.toml core/switch_core/ connectors/+# ── Regenerate the contract-registry modules ──────────────────────────────────+# contracts.yaml is the only authored copy of which contract revisions each+# artifact speaks and accepts. Each artifact needs it compiled in, so the+# per-language modules are generated rather than kept in step by hand.+contracts:+ uv run --project core python scripts/gen_contracts.py++# ── Verify the generated contract modules are current ─────────────────────────+# Fails both when contracts.yaml changed without regenerating and when a+# generated module was hand-edited.+contracts-check:+ uv run --project core python scripts/gen_contracts.py --check+# ── Run alembic migrations ─────────────────────────────────────────────────────migrate:uv run --project core alembic -c core/alembic.ini upgrade headdiff --git a/scripts/gen_contracts.py b/scripts/gen_contracts.pynew file mode 100644index 000000000..8a8df4e22--- /dev/null+++ b/scripts/gen_contracts.py@@ -0,0 +1,293 @@+#!/usr/bin/env python3+"""Generate the per-language contract-registry modules from contracts.yaml.++`contracts.yaml` is the only authored copy of which contract revisions each+Switch artifact speaks and accepts. Artifacts are written in different+languages and ship independently, so each needs the registry compiled in —+a running artifact cannot ask a file on someone else's disk what it speaks.++Rather than maintain one copy per language by hand, they are generated. The+alternative is already in the tree and already broken: COMPATIBLE_SWITCH_VERSION+is hand-copied into app-identity.canary.ts, held in step by a comment reading+"keep in sync" and nothing else.++Usage:+ python scripts/gen_contracts.py # write the generated modules+ python scripts/gen_contracts.py --check # fail if any is stale or edited++`--check` regenerates in memory and compares, so it catches both failure modes:+editing contracts.yaml without regenerating, and hand-editing a generated file.+It needs no formatter or toolchain, so CI can run it anywhere.+"""++from __future__ import annotations++import argparse+import sys+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import yaml++REPO_ROOT = Path(__file__).resolve().parent.parent+SOURCE = REPO_ROOT / "contracts.yaml"++BANNER_LINES = [+ "Generated from contracts.yaml by scripts/gen_contracts.py.",+ "",+ "Do NOT edit this file. Edit contracts.yaml and run `just contracts`.",+]+++@dataclass(frozen=True)+class Target:+ path: Path+ render: Any+++@dataclass(frozen=True)+class Contract:+ name: str+ description: str+ artifacts: dict[str, tuple[int, int]]+++def load_contracts() -> list[Contract]:+ """Parse and validate contracts.yaml.++ Validation is strict: a malformed registry is a build-time error, never a+ default. Every downstream compatibility answer rests on these numbers.+ """+ raw = yaml.safe_load(SOURCE.read_text())+ if not isinstance(raw, dict) or "contracts" not in raw:+ raise ValueError(f"{SOURCE} must have a top-level 'contracts' mapping")++ contracts: list[Contract] = []+ for name, body in raw["contracts"].items():+ if not isinstance(body, dict):+ raise ValueError(f"contract {name!r}: expected a mapping")+ description = body.get("description")+ if not description:+ raise ValueError(f"contract {name!r}: a description is required")+ artifacts_raw = body.get("artifacts")+ if not artifacts_raw:+ raise ValueError(f"contract {name!r}: at least one artifact is required")++ artifacts: dict[str, tuple[int, int]] = {}+ for artifact, decl in artifacts_raw.items():+ if not isinstance(decl, dict) or set(decl) != {"speaks", "accepts"}:+ raise ValueError(+ f"contract {name!r}, artifact {artifact!r}: "+ "expected exactly 'speaks' and 'accepts'"+ )+ speaks, accepts = decl["speaks"], decl["accepts"]+ for label, value in (("speaks", speaks), ("accepts", accepts)):+ if not isinstance(value, int) or isinstance(value, bool) or value < 1:+ raise ValueError(+ f"contract {name!r}, artifact {artifact!r}: "+ f"{label} must be an integer >= 1, got {value!r}"+ )+ if accepts > speaks:+ raise ValueError(+ f"contract {name!r}, artifact {artifact!r}: "+ f"accepts ({accepts}) is above speaks ({speaks}), "+ "which declares an empty range"+ )+ artifacts[artifact] = (speaks, accepts)++ contracts.append(+ Contract(+ name=name,+ description=" ".join(str(description).split()),+ artifacts=artifacts,+ )+ )+ return contracts+++def render_python(contracts: list[Contract]) -> str:+ lines = ['"""' + BANNER_LINES[0], ""]+ lines.extend(BANNER_LINES[2:])+ lines.append('"""')+ lines.append("")+ lines.append("from typing import Final, NamedTuple")+ lines.append("")+ lines.append("")+ lines.append("class ContractRange(NamedTuple):")+ lines.append(' """The revisions of one contract an artifact implements.')+ lines.append("")+ lines.append(" Two peers are compatible when their ranges overlap; they then")+ lines.append(" operate at the lower of the two `speaks`.")+ lines.append(' """')+ lines.append("")+ lines.append(" speaks: int")+ lines.append(" accepts: int")+ lines.append("")+ lines.append("")+ lines.append("CONTRACTS: Final[dict[str, dict[str, ContractRange]]] = {")+ for contract in contracts:+ lines.append(f" # {contract.description}")+ lines.append(f' "{contract.name}": {{')+ for artifact, (speaks, accepts) in contract.artifacts.items():+ lines.append(+ f' "{artifact}": ContractRange(speaks={speaks}, accepts={accepts}),'+ )+ lines.append(" },")+ lines.append("}")+ lines.append("")+ lines.append("")+ lines.append("def contract_range(contract: str, artifact: str) -> ContractRange:")+ lines.append(' """Return an artifact\'s declared range for a contract.')+ lines.append("")+ lines.append(" Raises KeyError for a pair the registry does not know. An")+ lines.append(" unregistered pair is a bug in the caller, never a reason to")+ lines.append(" assume a default — a wrong default reads as compatible.")+ lines.append(' """')+ lines.append(" try:")+ lines.append(" return CONTRACTS[contract][artifact]")+ lines.append(" except KeyError:")+ lines.append(" raise KeyError(")+ lines.append(+ ' f"contracts.yaml declares no range for artifact {artifact!r} "'+ )+ lines.append(' f"in contract {contract!r}"')+ lines.append(" ) from None")+ lines.append("")+ return "\n".join(lines)+++def ts_key(name: str) -> str:+ """Quote an object key only when it is not a bare JS identifier.++ Matches what the repo's formatter would produce, so the generated file is+ a fixed point of `oxfmt` and `--check` needs no formatter to run.+ """+ if name.isidentifier() and name.isascii():+ return name+ return f"'{name}'"+++def render_typescript(contracts: list[Contract]) -> str:+ lines = ["/**"]+ for banner in BANNER_LINES:+ lines.append(f" * {banner}".rstrip())+ lines.append(" */")+ lines.append("")+ lines.append("/**")+ lines.append(" * The revisions of one contract an artifact implements.")+ lines.append(" *")+ lines.append(" * Two peers are compatible when their ranges overlap; they then")+ lines.append(" * operate at the lower of the two `speaks`.")+ lines.append(" */")+ lines.append("export interface ContractRange {")+ lines.append(" readonly speaks: number;")+ lines.append(" readonly accepts: number;")+ lines.append("}")+ lines.append("")+ lines.append("export const CONTRACTS = {")+ for contract in contracts:+ lines.append(f" // {contract.description}")+ lines.append(f" {ts_key(contract.name)}: {{")+ for artifact, (speaks, accepts) in contract.artifacts.items():+ lines.append(+ f" {ts_key(artifact)}: {{ speaks: {speaks}, accepts: {accepts} }},"+ )+ lines.append(" },")+ lines.append("} as const satisfies Record<string, Record<string, ContractRange>>;")+ lines.append("")+ lines.append("export type ContractName = keyof typeof CONTRACTS;")+ lines.append("")+ lines.append("/**")+ lines.append(" * Return an artifact's declared range for a contract.")+ lines.append(" *")+ lines.append(+ " * Throws for a pair the registry does not know. An unregistered pair"+ )+ lines.append(+ " * is a bug in the caller, never a reason to assume a default — a wrong"+ )+ lines.append(" * default reads as compatible.")+ lines.append(" */")+ lines.append(+ "export function contractRange(contract: string, artifact: string): ContractRange {"+ )+ lines.append(+ " const registry = CONTRACTS as Record<string, Record<string, ContractRange>>;"+ )+ lines.append(" const declared = registry[contract]?.[artifact];")+ lines.append(" if (declared === undefined) {")+ lines.append(" throw new Error(")+ lines.append(+ " `contracts.yaml declares no range for artifact '${artifact}' in contract '${contract}'`"+ )+ lines.append(" );")+ lines.append(" }")+ lines.append(" return declared;")+ lines.append("}")+ lines.append("")+ return "\n".join(lines)+++TARGETS = [+ # switch-core: the agent bridge, the gateway API, and the schema check.+ Target(REPO_ROOT / "core" / "switch_core" / "contracts.py", render_python),+ # switchdash: the desktop app and the sidecar it bundles and deploys.+ Target(+ REPO_ROOT / "dash" / "packages" / "shared" / "src" / "contracts.ts",+ render_typescript,+ ),+ # agent-runtime: published to a registry, so it cannot depend on the+ # unpublished workspace package above and carries its own copy.+ Target(+ REPO_ROOT+ / "dash"+ / "packages"+ / "switch-agent-runtime"+ / "src"+ / "contracts.ts",+ render_typescript,+ ),+]+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--check",+ action="store_true",+ help="fail if any generated module differs from what would be written",+ )+ args = parser.parse_args()++ contracts = load_contracts()+ stale: list[Path] = []++ for target in TARGETS:+ expected = target.render(contracts)+ relative = target.path.relative_to(REPO_ROOT)+ if args.check:+ actual = target.path.read_text() if target.path.exists() else None+ if actual != expected:+ stale.append(relative)+ continue+ target.path.parent.mkdir(parents=True, exist_ok=True)+ target.path.write_text(expected)+ print(f"wrote {relative}")++ if stale:+ print(+ "Generated contract modules are out of date:\n"+ + "\n".join(f" {path}" for path in stale)+ + "\n\nEither contracts.yaml changed without regenerating, or a generated\n"+ "file was hand-edited. Run `just contracts` and commit the result.",+ file=sys.stderr,+ )+ return 1+ if args.check:+ print("Generated contract modules are up to date.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())