Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

refactor: make artifacts.yaml the one source for versions and contracts (CHOO-1865)

Louis Amaudruz2982beff9ee5
diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.yml
index 13733a50b..d294deda2 100644
--- a/.github/workflows/pr-ci.yml
+++ b/.github/workflows/pr-ci.yml
@@ -46,7 +46,7 @@ jobs:
backend: ${{ steps.filter.outputs.backend }}
dash: ${{ steps.filter.outputs.dash }}
gateway: ${{ steps.filter.outputs.gateway }}
- contracts: ${{ steps.filter.outputs.contracts }}
+ artifacts: ${{ steps.filter.outputs.artifacts }}
steps:
- name: Checkout
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
@@ -74,15 +74,21 @@ jobs:
gateway:
- *shared
- 'gateway/**'
- # Spans core/ and dash/, so it gets its own filter rather than
- # riding either tree's.
- contracts:
+ # Spans every tree, so it gets its own filter rather than riding
+ # any one of them. Includes the files whose versions the registry is
+ # checked against, so a release bump cannot land without the check.
+ artifacts:
- *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'
+ - 'artifacts.yaml'
+ - 'scripts/gen_artifacts.py'
+ - 'core/switch_core/artifacts.py'
+ - 'core/pyproject.toml'
+ - 'dash/packages/shared/src/artifacts.ts'
+ - 'dash/packages/switch-agent-runtime/src/artifacts.ts'
+ - 'dash/apps/switchdash-desktop/package.json'
+ - 'dash/apps/switchdash-desktop/src/shared/app-identity*.ts'
+ - 'dash/packages/switch-agent-runtime/package.json'
+ - 'connectors/**/plugin.json'
backend:
name: Backend (core)
@@ -172,15 +178,16 @@ 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
+ artifacts:
+ name: Artifact registry
+ # Every artifact carries a compiled-in copy of artifacts.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.
+ # hand-editing a generated module. The same check compares the registry
+ # against the version files packaging ecosystems own. 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' }}
+ if: ${{ needs.changes.outputs.artifacts == 'true' || github.event_name == 'push' }}
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -195,8 +202,8 @@ jobs:
- 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
+ - name: Registry, generated modules and declared versions agree
+ run: uv run --project core python scripts/gen_artifacts.py --check
gateway:
name: Gateway UI
diff --git a/.github/workflows/switch-release.yml b/.github/workflows/switch-release.yml
index c2f6f5d5d..1b830bba0 100644
--- a/.github/workflows/switch-release.yml
+++ b/.github/workflows/switch-release.yml
@@ -35,6 +35,8 @@ jobs:
outputs:
version: ${{ steps.version.outputs.version }}
push: ${{ steps.version.outputs.push }}
+ compose_speaks: ${{ steps.contract.outputs.speaks }}
+ compose_accepts: ${{ steps.contract.outputs.accepts }}
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -59,6 +61,20 @@ jobs:
fi
echo "Resolved version=$pkg_version (push on tag only)"
+ # The published compose artifact declares its stack-compose range twice:
+ # in the file (for whoever has already downloaded it) and as an OCI
+ # annotation here — which a consumer can read off the registry WITHOUT
+ # pulling it, to decide whether pulling is worth it (CHOO-1865).
+ - name: Read the stack-compose contract
+ id: contract
+ run: |
+ python3 - <<'PY' >> "$GITHUB_OUTPUT"
+ import yaml
+ declared = yaml.safe_load(open("artifacts.yaml"))["contracts"]["stack-compose"]["artifacts"]["compose"]
+ print(f"speaks={declared['speaks']}")
+ print(f"accepts={declared['accepts']}")
+ PY
+
images:
name: Build & publish image (${{ matrix.image }})
needs: prep
@@ -180,4 +196,6 @@ jobs:
--artifact-type application/vnd.switch.compose.v1+yaml \
--annotation "org.opencontainers.image.version=${{ needs.prep.outputs.version }}" \
--annotation "org.opencontainers.image.source=https://github.com/${{ github.repository }}" \
+ --annotation "com.switch.contract.stack-compose.speaks=${{ needs.prep.outputs.compose_speaks }}" \
+ --annotation "com.switch.contract.stack-compose.accepts=${{ needs.prep.outputs.compose_accepts }}" \
standalone-docker-compose.yml:application/yaml
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 58421e8e9..317b0b67a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,7 +11,7 @@ and a changelog, without exception (CHOO-1865).
A version says **where an artifact is** — which release you are running. It says
nothing about what that release can talk to. Compatibility is carried separately
-by the contract revisions in [`contracts.yaml`](contracts.yaml), which move
+by the contract revisions in [`artifacts.yaml`](artifacts.yaml), which move
independently: a release that changes nothing on the wire bumps its version and
leaves its contracts alone.
@@ -43,7 +43,7 @@ version of their own to them without also giving them a release of their own.
#### Added
- Cross-artifact version compatibility, part 1 — every artifact declares what it
- is and what it speaks (CHOO-1865). `contracts.yaml` is the one authored
+ is and what it speaks (CHOO-1865). `artifacts.yaml` is the one authored
registry of contract revisions; per-language modules are generated from it and
CI fails if they are stale or hand-edited. switch-core reads its own release
version, discloses it and its ranges on authenticated surfaces only (the
@@ -758,18 +758,25 @@ The remote runtime switchdash deploys to an agent host. Versioned in
`dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts` and deployed by
switchdash rather than published on its own.
-### [Unreleased]
+### [1.8.0]
+
+#### Added
+- Declares its `sidecar-control` range in the ready file switchdash already
+ reads (CHOO-1865).
#### Changed
-- Three-part semver: `1.7` becomes `1.7.0`. **The major stays at 1** — every
+- Three-part semver: `1.7` becomes `1.8.0`. **The major stays at 1** — every
switchdash already in the field judges compatibility on the major and parses
- two parts, so `1.7` and `1.7.0` read as the same version and neither side
+ two parts, so `1.7` and `1.8.0` order correctly and neither side
replaces the other. `2.0.0` would have every existing install treat this
sidecar as incompatible and replace it while a newer install replaces it back
(CHOO-1937, CHOO-1865).
- The version no longer carries compatibility. It says which release is running;
what the sidecar can speak is the `sidecar-control` range it now declares in
its ready file (CHOO-1865).
+- The version is declared in `artifacts.yaml` and generated into the code.
+ Nothing else declares it — the sidecar is deployed by switchdash rather than
+ published, so it has no packaging file of its own.
### [1.7]
diff --git a/RELEASING.md b/RELEASING.md
index 3fe8da394..936b8b53a 100644
--- a/RELEASING.md
+++ b/RELEASING.md
@@ -16,7 +16,7 @@ standalone Docker Compose file. The switchdash desktop app releases separately
**A version says where an artifact is, not what it can talk to.** Compatibility
is carried separately, by the contract revisions in
-[`contracts.yaml`](contracts.yaml). The two move independently: a release that
+[`artifacts.yaml`](artifacts.yaml). The two move independently: a release that
changes nothing on the wire bumps its version and leaves its contracts alone.
Never derive one from the other.
@@ -37,8 +37,8 @@ agent-runtime package, the sidecar, and the two connector plugins.
### Bumping a contract
-When you change an interface named in `contracts.yaml`, raise that artifact's
-`speaks` for the contract and run `just contracts`. Raise `accepts` only when
+When you change an interface named in `artifacts.yaml`, raise that artifact's
+`speaks` for the contract and run `just artifacts`. 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.
diff --git a/artifacts.yaml b/artifacts.yaml
new file mode 100644
index 000000000..b49b79c5c
--- /dev/null
+++ b/artifacts.yaml
@@ -0,0 +1,131 @@
+# The artifact registry — one place to see what every Switch artifact is, and
+# what it can talk to.
+#
+# Two questions, kept deliberately separate, because conflating them is the
+# problem this file exists to solve:
+#
+# `artifacts` — WHERE each thing is. Its release version. Says nothing
+# whatsoever about compatibility.
+# `contracts` — WHETHER two things can talk. Named interfaces, each carrying
+# one integer revision.
+#
+# They move independently. A release that changes nothing on the wire bumps its
+# version and leaves its contracts alone. Never derive one from the other.
+#
+# ── Editing this file ────────────────────────────────────────────────────────
+#
+# It is the only place a human declares any of this. Run `just artifacts` after
+# editing. CI fails if the generated modules are stale, if one has been
+# hand-edited, or if a `declared_in` file disagrees with what is written here.
+#
+# ── About `declared_in` ──────────────────────────────────────────────────────
+#
+# Some versions have a mandatory home that a packaging ecosystem owns and reads:
+# `importlib.metadata` reads pyproject, `npm publish` reads package.json, and
+# both release workflows verify the git tag against them. Those files stay
+# authoritative for their tooling; `declared_in` records where, and the registry
+# is CHECKED against them rather than generating into them.
+#
+# An artifact with no `declared_in` has no such home — nothing but this file
+# declares it, so this file is its source and the constant is generated.
+#
+# ── Contract revisions ───────────────────────────────────────────────────────
+#
+# speaks — the newest revision the artifact 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`.
+#
+# 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.
+
+artifacts:
+ switch-core:
+ description: The backend service, and the gateway API it serves.
+ version: 0.12.3
+ declared_in: core/pyproject.toml
+
+ switchdash:
+ description: The desktop app.
+ version: 0.19.2
+ declared_in: dash/apps/switchdash-desktop/package.json
+ # Which switch-core release this app build bundles and pulls for
+ # local-server mode. DELIBERATELY NOT switch-core's version above.
+ #
+ # They coincide today, and must not be wired together: bumping
+ # core/pyproject.toml is the first step of cutting a switch-core release, so
+ # a derived pin would immediately point switchdash at images that do not
+ # exist on the registry yet and break local-server mode for everyone on
+ # main. This moves only when switchdash is ready to bundle that release —
+ # in lockstep with the bundled compose.
+ pins:
+ switch-core: 0.12.3
+
+ agent-runtime:
+ description: The Switch protocol client and MCP runtime, published to a registry.
+ version: 0.1.5
+ declared_in: dash/packages/switch-agent-runtime/package.json
+
+ sidecar:
+ description: >-
+ The remote runtime switchdash deploys to an agent host. Deployed rather
+ than published, so nothing else declares its version — this file is its
+ only source and the constant is generated from it.
+ version: 1.8.0
+
+ switch-connector:
+ description: The Claude Code connector plugin.
+ version: 0.7.8
+ declared_in: connectors/claude-code-plugin/.claude-plugin/plugin.json
+
+ switch-connector-codex:
+ description: The Codex connector plugin.
+ version: 0.2.0
+ declared_in: connectors/codex-plugin/.codex-plugin/plugin.json
+
+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/contracts.yaml b/contracts.yaml
deleted file mode 100644
index b0371b7a8..000000000
--- a/contracts.yaml
+++ /dev/null
@@ -1,70 +0,0 @@
-# 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/artifacts.py
similarity index 80%
rename from core/switch_core/contracts.py
rename to core/switch_core/artifacts.py
index 0e170e103..07d5446ef 100644
--- a/core/switch_core/contracts.py
+++ b/core/switch_core/artifacts.py
@@ -1,6 +1,6 @@
-"""Generated from contracts.yaml by scripts/gen_contracts.py.
+"""Generated from artifacts.yaml by scripts/gen_artifacts.py.
-Do NOT edit this file. Edit contracts.yaml and run `just contracts`.
+Do NOT edit this file. Edit artifacts.yaml and run `just artifacts`.
"""
from typing import Final, NamedTuple
@@ -17,6 +17,17 @@ class ContractRange(NamedTuple):
accepts: int
+# Where each artifact is. Says nothing about compatibility — that is
+# CONTRACTS below. The two must never be derived from one another.
+ARTIFACT_VERSIONS: Final[dict[str, str]] = {
+ "switch-core": "0.12.3",
+ "switchdash": "0.19.2",
+ "agent-runtime": "0.1.5",
+ "sidecar": "1.8.0",
+ "switch-connector": "0.7.8",
+ "switch-connector-codex": "0.2.0",
+}
+
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": {
@@ -56,6 +67,6 @@ def contract_range(contract: str, artifact: str) -> ContractRange:
return CONTRACTS[contract][artifact]
except KeyError:
raise KeyError(
- f"contracts.yaml declares no range for artifact {artifact!r} "
+ f"artifacts.yaml declares no range for artifact {artifact!r} "
f"in contract {contract!r}"
) from None
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index 99f9d955d..1ba318e3e 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -768,7 +768,7 @@ async def _open_event_stream(
# After the connection is open, so a bookkeeping failure can never be the
# reason an agent could not connect.
- await protocol.record_client_declaration(agent.id, declaration)
+ await protocol.record_client_declaration(agent.id, connection_id, declaration)
# Rooms are claimed before the stream starts, not after it opens. A client
# reconnecting already knows which room it was in; making it re-subscribe
diff --git a/core/switch_core/bridges/agent/protocol/connections.py b/core/switch_core/bridges/agent/protocol/connections.py
index c68bb2599..a37fa6206 100644
--- a/core/switch_core/bridges/agent/protocol/connections.py
+++ b/core/switch_core/bridges/agent/protocol/connections.py
@@ -29,7 +29,7 @@ from collections.abc import Iterable
from dataclasses import dataclass, field
from typing import Literal
-from switch_core.contracts import contract_range
+from switch_core.artifacts import contract_range
logger = logging.getLogger(__name__)
@@ -46,7 +46,7 @@ HEARTBEAT_TTL_SECONDS = 6.0
# in ways neither side can see. The runtime lives on the user's machine and
# Switch moves independently.
#
-# Both numbers come from contracts.yaml, the one place a human declares them
+# Both numbers come from artifacts.yaml, the one place a human declares them
# (CHOO-1865). PROTOCOL_VERSION is the newest revision this server implements;
# PROTOCOL_ACCEPTS is the oldest it still handles. They are equal today, and
# the range is what compatibility is judged on so that they need not stay so.
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 0b86a787c..a683c29c9 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -456,7 +456,7 @@ class ProtocolService:
)
async def record_client_declaration(
- self, agent_id: str, declaration: ClientDeclaration
+ self, agent_id: str, connection_id: str, declaration: ClientDeclaration
) -> None:
"""Persist what a client last said about itself (CHOO-1865).
@@ -467,7 +467,11 @@ class ProtocolService:
Without it the question "what would this break?" has no answer but a
guess.
- Last write wins, per agent. Nothing acts on it yet.
+ One record per agent, last write wins, stamped with the connection it
+ came from. The connection id is what makes it interpretable: an agent
+ may hold many connections at once, so without it a second connection
+ declaring less looks like the first client having forgotten what it is,
+ rather than a different client answering.
A failure here is logged and swallowed: this is bookkeeping about a
connection, and losing a version record must never stop an agent
@@ -479,6 +483,7 @@ class ProtocolService:
return
record = declaration.as_dict()
+ record["connection_id"] = connection_id
record["recorded_at"] = datetime.now(UTC).isoformat()
try:
async with self.session_factory() as session:
diff --git a/core/switch_core/version.py b/core/switch_core/version.py
index a03376df8..54d6692bb 100644
--- a/core/switch_core/version.py
+++ b/core/switch_core/version.py
@@ -7,7 +7,7 @@ to keep in step by hand, which is the drift this ticket exists to end.
An artifact's semver says *where it is* — which release you are running. It
says nothing about whether it can talk to anything; that is what the contract
-revisions in `switch_core.contracts` are for. The two move independently and
+revisions in `switch_core.artifacts` are for. The two move independently and
must never be derived from one another.
When the version cannot be read it is reported as `None`, meaning *unknown*,
@@ -22,7 +22,7 @@ from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as distribution_version
from typing import Any
-from switch_core.contracts import contract_range
+from switch_core.artifacts import contract_range
logger = logging.getLogger(__name__)
diff --git a/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py b/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py
index 2b2017948..6e5563d2a 100644
--- a/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py
+++ b/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py
@@ -31,12 +31,12 @@ class _Protocol:
self.event_buffer = EventBuffer()
self.connections = ConnectionRegistry()
self.polled = False
- self.recorded: list[tuple[str, ClientDeclaration]] = []
+ self.recorded: list[tuple[str, str, ClientDeclaration]] = []
async def record_client_declaration(
- self, agent_id: str, declaration: ClientDeclaration
+ self, agent_id: str, connection_id: str, declaration: ClientDeclaration
) -> None:
- self.recorded.append((agent_id, declaration))
+ self.recorded.append((agent_id, connection_id, declaration))
async def poll_events(self, agent_id: str, timeout: float) -> list[Any]:
self.polled = True
@@ -209,7 +209,7 @@ async def test_a_declared_client_is_recorded_in_full() -> None:
assert conn.declaration == declared
# Also persisted, since connections die with the process and an accepts
# floor is raised offline against what is actually deployed.
- assert protocol.recorded == [(AGENT_ID, declared)]
+ assert protocol.recorded == [(AGENT_ID, "c1", declared)]
async def test_a_refused_client_is_not_recorded() -> None:
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.py b/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.py
index d8b4b3ac8..b5d7d0a23 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_record_client_declaration.py
@@ -19,6 +19,7 @@ from switch_core.bridges.agent.protocol.connections import ClientDeclaration
from switch_core.bridges.agent.protocol.service import ProtocolService
AGENT_ID = "agent-1"
+CONNECTION_ID = "conn-1"
class _Session:
@@ -70,6 +71,7 @@ async def test_a_declaration_is_written_to_agent_metadata() -> None:
store = _AgentStore({})
await _service(store).record_client_declaration(
AGENT_ID,
+ CONNECTION_ID,
ClientDeclaration(
speaks=1, accepts=1, artifact="agent-runtime", version="0.1.5"
),
@@ -91,7 +93,7 @@ async def test_the_record_is_timestamped() -> None:
"""
store = _AgentStore({})
await _service(store).record_client_declaration(
- AGENT_ID, ClientDeclaration(speaks=1, version="0.1.5")
+ AGENT_ID, CONNECTION_ID, ClientDeclaration(speaks=1, version="0.1.5")
)
(update,) = store.updates
@@ -102,7 +104,7 @@ async def test_existing_metadata_is_preserved() -> None:
"""Agent.metadata_ is shared with known_agent_options and others."""
store = _AgentStore({"known_agent_options": {"repo_dir": "/w"}})
await _service(store).record_client_declaration(
- AGENT_ID, ClientDeclaration(speaks=1, version="0.1.5")
+ AGENT_ID, CONNECTION_ID, ClientDeclaration(speaks=1, version="0.1.5")
)
(update,) = store.updates
@@ -116,7 +118,9 @@ async def test_a_client_that_declared_nothing_writes_nothing() -> None:
connected and answered.
"""
store = _AgentStore({})
- await _service(store).record_client_declaration(AGENT_ID, ClientDeclaration())
+ await _service(store).record_client_declaration(
+ AGENT_ID, CONNECTION_ID, ClientDeclaration()
+ )
assert store.updates == []
@@ -125,7 +129,7 @@ async def test_a_client_declaring_only_its_version_is_still_recorded() -> None:
"""The artifact version is worth having even with no protocol range."""
store = _AgentStore({})
await _service(store).record_client_declaration(
- AGENT_ID, ClientDeclaration(version="0.1.5")
+ AGENT_ID, CONNECTION_ID, ClientDeclaration(version="0.1.5")
)
(update,) = store.updates
@@ -135,7 +139,7 @@ async def test_a_client_declaring_only_its_version_is_still_recorded() -> None:
async def test_a_missing_agent_writes_nothing() -> None:
store = _AgentStore(None, missing=True)
await _service(store).record_client_declaration(
- AGENT_ID, ClientDeclaration(speaks=1, version="0.1.5")
+ AGENT_ID, CONNECTION_ID, ClientDeclaration(speaks=1, version="0.1.5")
)
assert store.updates == []
@@ -159,17 +163,33 @@ async def test_a_write_failure_is_warned_about_but_not_raised(
with caplog.at_level(logging.WARNING):
await _service(store).record_client_declaration(
- AGENT_ID, ClientDeclaration(speaks=1, version="0.1.5")
+ AGENT_ID, CONNECTION_ID, ClientDeclaration(speaks=1, version="0.1.5")
)
assert any(record.levelno == logging.WARNING for record in caplog.records)
+async def test_the_record_names_the_connection_it_came_from() -> None:
+ """Found by running it against a real server (CHOO-1865).
+
+ An agent may hold many connections at once, so without the connection id a
+ second connection declaring less looks like the first client having
+ forgotten what it is, rather than a different client answering.
+ """
+ store = _AgentStore({})
+ await _service(store).record_client_declaration(
+ AGENT_ID, "conn-xyz", ClientDeclaration(speaks=1, version="0.1.5")
+ )
+
+ (update,) = store.updates
+ assert update["metadata_"]["client_declaration"]["connection_id"] == "conn-xyz"
+
+
async def test_the_latest_declaration_replaces_the_previous_one() -> None:
"""Last write wins: an upgraded client is not a second client."""
store = _AgentStore({"client_declaration": {"version": "0.1.4", "speaks": 1}})
await _service(store).record_client_declaration(
- AGENT_ID, ClientDeclaration(speaks=1, version="0.1.5")
+ AGENT_ID, CONNECTION_ID, ClientDeclaration(speaks=1, version="0.1.5")
)
(update,) = store.updates
diff --git a/core/tests/test_gen_artifacts.py b/core/tests/test_gen_artifacts.py
new file mode 100644
index 000000000..98cfd4a5c
--- /dev/null
+++ b/core/tests/test_gen_artifacts.py
@@ -0,0 +1,270 @@
+"""Tests for the artifact registry and the generator that compiles it in.
+
+The registry is the root of every version and compatibility answer the system
+gives, so a malformed entry must fail at build time rather than reach a running
+artifact — where a wrong number reads as "compatible", or as a release that was
+never cut.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import re
+import sys
+from pathlib import Path
+from types import ModuleType
+
+import pytest
+import yaml
+
+from switch_core.artifacts import ARTIFACT_VERSIONS, CONTRACTS, contract_range
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+MINIMAL_ARTIFACTS = {"demo": {"description": "d", "version": "1.0.0"}}
+MINIMAL_CONTRACTS = {
+ "demo-contract": {
+ "description": "d",
+ "artifacts": {"demo": {"speaks": 1, "accepts": 1}},
+ }
+}
+
+
+def _load_generator() -> ModuleType:
+ """Import scripts/gen_artifacts.py, which is not an installed package."""
+ path = REPO_ROOT / "scripts" / "gen_artifacts.py"
+ spec = importlib.util.spec_from_file_location("gen_artifacts", 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 = _load_generator()
+
+
+def _write_registry(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ artifacts: object = None,
+ contracts: object = None,
+) -> None:
+ source = tmp_path / "artifacts.yaml"
+ source.write_text(
+ yaml.safe_dump(
+ {
+ "artifacts": MINIMAL_ARTIFACTS if artifacts is None else artifacts,
+ "contracts": MINIMAL_CONTRACTS if contracts is None else contracts,
+ }
+ )
+ )
+ monkeypatch.setattr(gen, "SOURCE", source)
+
+
+# ── The committed state ──────────────────────────────────────────────────────
+
+
+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.
+ """
+ registry = gen.load_registry()
+ for target in gen.TARGETS:
+ assert target.path.read_text() == target.render(registry), (
+ f"{target.path.relative_to(REPO_ROOT)} is stale — run `just artifacts`"
+ )
+
+
+def test_the_registry_agrees_with_every_file_it_records() -> None:
+ """pyproject, the package.jsons, the plugin.jsons and both app-identity twins.
+
+ These are owned by their packaging ecosystems, so the registry is checked
+ against them rather than generating into them.
+ """
+ assert gen.check_declared_versions(gen.load_registry()) == []
+
+
+def test_every_artifact_version_is_three_part_semver() -> None:
+ for name, version in ARTIFACT_VERSIONS.items():
+ assert re.fullmatch(r"\d+\.\d+\.\d+", version), f"{name} is {version}"
+
+
+def test_the_switchdash_pin_is_not_wired_to_switch_cores_version() -> None:
+ """They coincide today, and must stay separately declared.
+
+ Bumping core/pyproject.toml is the first step of cutting a switch-core
+ release. A derived pin would immediately point local-server mode at images
+ that are not on the registry yet, breaking it for everyone on main.
+ """
+ registry = gen.load_registry()
+ switchdash = next(a for a in registry.artifacts if a.name == "switchdash")
+ assert "switch-core" in switchdash.pins
+
+
+def test_the_sidecar_has_no_declared_in_so_the_registry_owns_it() -> None:
+ """Nothing else declares the sidecar's version — it is deployed, not published."""
+ registry = gen.load_registry()
+ sidecar = next(a for a in registry.artifacts if a.name == "sidecar")
+ assert sidecar.declared_in is None
+
+
+# ── Contract lookups ─────────────────────────────────────────────────────────
+
+
+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"
+ )
+
+
+ ("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"}
+
+
+# ── Validation ───────────────────────────────────────────────────────────────
+
+
+def test_registry_rejects_a_two_part_version(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Every artifact carries three parts, without exception."""
+ _write_registry(
+ tmp_path,
+ monkeypatch,
+ artifacts={"demo": {"description": "d", "version": "1.7"}},
+ )
+ with pytest.raises(ValueError, match="three-part semver"):
+ gen.load_registry()
+
+
+def test_registry_rejects_a_pin_of_something_it_does_not_know(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A pin naming a typo'd artifact would silently never be checked."""
+ _write_registry(
+ tmp_path,
+ monkeypatch,
+ artifacts={
+ "demo": {
+ "description": "d",
+ "version": "1.0.0",
+ "pins": {"switch-corp": "1.0.0"},
+ }
+ },
+ )
+ with pytest.raises(ValueError, match="not an artifact in this registry"):
+ gen.load_registry()
+
+
+def test_registry_rejects_an_empty_range(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _write_registry(
+ tmp_path,
+ monkeypatch,
+ contracts={
+ "demo-contract": {
+ "description": "d",
+ "artifacts": {"a": {"speaks": 1, "accepts": 2}},
+ }
+ },
+ )
+ with pytest.raises(ValueError, match="is above speaks"):
+ gen.load_registry()
+
+
+def test_registry_rejects_a_non_integer_revision(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _write_registry(
+ tmp_path,
+ monkeypatch,
+ contracts={
+ "demo-contract": {
+ "description": "d",
+ "artifacts": {"a": {"speaks": "1", "accepts": 1}},
+ }
+ },
+ )
+ with pytest.raises(ValueError, match="must be an integer"):
+ gen.load_registry()
+
+
+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,
+ contracts={
+ "demo-contract": {
+ "description": "d",
+ "artifacts": {"a": {"speaks": 0, "accepts": 0}},
+ }
+ },
+ )
+ with pytest.raises(ValueError, match="must be an integer"):
+ gen.load_registry()
+
+
+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,
+ contracts={
+ "demo-contract": {
+ "description": "d",
+ "artifacts": {"a": {"speaks": 1, "accepts": 1, "version": "1.2.3"}},
+ }
+ },
+ )
+ with pytest.raises(ValueError, match="expected exactly"):
+ gen.load_registry()
+
+
+def test_registry_rejects_a_missing_section(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ source = tmp_path / "artifacts.yaml"
+ source.write_text(yaml.safe_dump({"contracts": MINIMAL_CONTRACTS}))
+ monkeypatch.setattr(gen, "SOURCE", source)
+ with pytest.raises(ValueError, match="'artifacts'"):
+ gen.load_registry()
diff --git a/core/tests/test_gen_contracts.py b/core/tests/test_gen_contracts.py
deleted file mode 100644
index e8c0b6903..000000000
--- a/core/tests/test_gen_contracts.py
+++ /dev/null
@@ -1,179 +0,0 @@
-"""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/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts
index dafe6de3c..e1dc1076b 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -12,6 +12,7 @@ import type {
RemoteRoomSummary,
SwitchAuthConfig,
SwitchServer,
+ SwitchServerDeclaration,
SwitchUser,
} from '@shared/core/switch-servers/switch-servers';
import { reauthenticateManagedServer, refreshSession } from './auth';
@@ -206,10 +207,42 @@ export async function fetchAuthConfig(server: SwitchServer): Promise<SwitchAuthC
};
}
-type UserResponseJson = { id: string; name: string; email: string; role: string };
+type ServerDeclarationJson = {
+ version: string | null;
+ contracts: Record<string, { speaks: number; accepts: number }>;
+};
+
+type UserResponseJson = {
+ id: string;
+ name: string;
+ email: string;
+ role: string;
+ server?: ServerDeclarationJson | null;
+};
+
+/**
+ * A server declaration, or null when this server did not make one.
+ *
+ * Validated rather than trusted: a malformed block reads as *unknown* instead
+ * of a half-populated declaration, because a version we invented is worse than
+ * one we admit we do not have (CHOO-1865).
+ */
+function mapServerDeclaration(raw: unknown): SwitchServerDeclaration | null {
+ if (raw === null || typeof raw !== 'object') return null;
+ const candidate = raw as Partial<ServerDeclarationJson>;
+ if (typeof candidate.contracts !== 'object' || candidate.contracts === null) return null;
+ const version = typeof candidate.version === 'string' ? candidate.version : null;
+ return { version, contracts: candidate.contracts };
+}
function mapUser(json: UserResponseJson): SwitchUser {
- return { id: json.id, name: json.name, email: json.email, role: json.role };
+ return {
+ id: json.id,
+ name: json.name,
+ email: json.email,
+ role: json.role,
+ server: mapServerDeclaration(json.server ?? null),
+ };
}
export async function fetchMe(server: SwitchServer): Promise<SwitchUser> {
diff --git a/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts b/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts
index bac511da3..b9fb74e79 100644
--- a/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts
+++ b/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts
@@ -11,5 +11,8 @@ export const ARTIFACT_PREFIX = 'switchdash-canary';
export const RELEASE_REPO_OWNER = 'sandbox-quantum';
export const RELEASE_REPO_NAME = 'switch';
-// Keep in sync with COMPATIBLE_SWITCH_VERSION in ./app-identity.ts.
+// Mirrors COMPATIBLE_SWITCH_VERSION in ./app-identity.ts. Both are checked
+// against `switchdash.pins.switch-core` in artifacts.yaml by `just artifacts`,
+// so they can no longer drift apart — this used to say "keep in sync" and rely
+// on whoever edited one remembering the other (CHOO-1865).
export const COMPATIBLE_SWITCH_VERSION = '0.12.3';
diff --git a/dash/apps/switchdash-desktop/src/shared/app-identity.ts b/dash/apps/switchdash-desktop/src/shared/app-identity.ts
index 1d7f2d69a..a08298a7c 100644
--- a/dash/apps/switchdash-desktop/src/shared/app-identity.ts
+++ b/dash/apps/switchdash-desktop/src/shared/app-identity.ts
@@ -27,4 +27,16 @@ export const RELEASE_REPO_NAME = 'switch';
// artifact. Bump it in lockstep with the bundled compose
// (src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml)
// so a switchdash release pins a known-good switch-core stack.
+//
+// Declared in artifacts.yaml under `switchdash.pins.switch-core`, and CHECKED
+// against it by `just artifacts` (CHOO-1865). A literal rather than an import
+// because electron-builder loads this module under bare Node, where
+// extensionless ESM specifiers do not resolve — so it cannot import anything.
+// The check is what makes the literal safe; it is also mirrored in
+// app-identity.canary.ts, which is checked the same way.
+//
+// Deliberately NOT switch-core's own version from that file: bumping
+// core/pyproject.toml is the first step of cutting a switch-core release, and a
+// derived pin would immediately point local-server mode at images that are not
+// on the registry yet.
export const COMPATIBLE_SWITCH_VERSION = '0.12.3';
diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts
index 0fc155df6..c840f55a5 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -101,12 +101,30 @@ export type SwitchAuthConfig = {
oidcProviderLabel: string | null;
};
+/** What a switch-core says about itself to an authenticated client (CHOO-1865).
+ *
+ * `version` is null when the server cannot read its own version. Null means
+ * unknown and must be rendered as such, never as current. */
+export type SwitchServerDeclaration = {
+ version: string | null;
+ contracts: Record<string, { speaks: number; accepts: number }>;
+};
+
/** The authenticated user, as returned by `GET /gateway/auth/me`. */
export type SwitchUser = {
id: string;
name: string;
email: string;
role: string;
+ /**
+ * What the server declared on this session response.
+ *
+ * Null when the server predates version disclosure — which is the honest
+ * reading, not a defect. This is the only version signal available for a
+ * server switchdash does not manage: `readDeployedVersion` needs host access
+ * to read an image tag, so a BYO server used to report nothing at all, ever.
+ */
+ server: SwitchServerDeclaration | null;
};
/** Connection status for a server: whether switchdash holds a valid session. */
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts
index 516ac4ab2..254db97ce 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts
@@ -1,11 +1,11 @@
-import { contractRange } from '@switchdash/shared';
+import { artifactVersion, contractRange } from '@switchdash/shared';
/**
* The sidecar's release version, `MAJOR.MINOR.PATCH`.
*
* It says **where** this sidecar is — which release you are running — and
* nothing about what it can talk to. Compatibility lives in the
- * `sidecar-control` contract (see `contracts.yaml`), which the sidecar declares
+ * `sidecar-control` contract (see `artifacts.yaml`), which the sidecar declares
* in its ready file (CHOO-1865). The two move independently: a release that
* changes nothing on the wire bumps this and leaves the contract alone.
*
@@ -16,6 +16,10 @@ import { contractRange } from '@switchdash/shared';
* iterations) still redeploy correctly. The full identity a user sees is
* `MAJOR.MINOR.PATCH+<shorthash>` — semver build metadata.
*
+ * Derived from `artifacts.yaml`, which is the only place it is written. Nothing
+ * else declares the sidecar's version: it is deployed by switchdash rather than
+ * published, so it has no packaging file of its own.
+ *
* **The major must stay at 1 through this transition.** switchdash installs
* already in the field judge compatibility on the major and parse only `x.y`,
* so `1.7` → `1.7.0` reads as the same version to them and nothing is replaced.
@@ -29,7 +33,7 @@ import { contractRange } from '@switchdash/shared';
* and when an older sidecar 404s it, fail the operation with a message naming
* the upgrade rather than continuing without whatever the endpoint was for.
*/
-export const SIDECAR_VERSION = '1.7.0';
+export const SIDECAR_VERSION = artifactVersion('sidecar');
/** The artifact name the sidecar declares itself as. */
export const SIDECAR_ARTIFACT = 'sidecar';
diff --git a/dash/packages/switch-agent-runtime/src/contracts.ts b/dash/packages/shared/src/artifacts.ts
similarity index 74%
rename from dash/packages/switch-agent-runtime/src/contracts.ts
rename to dash/packages/shared/src/artifacts.ts
index 6d3baedd4..db6108372 100644
--- a/dash/packages/switch-agent-runtime/src/contracts.ts
+++ b/dash/packages/shared/src/artifacts.ts
@@ -1,7 +1,7 @@
/**
- * Generated from contracts.yaml by scripts/gen_contracts.py.
+ * Generated from artifacts.yaml by scripts/gen_artifacts.py.
*
- * Do NOT edit this file. Edit contracts.yaml and run `just contracts`.
+ * Do NOT edit this file. Edit artifacts.yaml and run `just artifacts`.
*/
/**
@@ -15,6 +15,26 @@ export interface ContractRange {
readonly accepts: number;
}
+/**
+ * Where each artifact is. Says nothing about compatibility — that is
+ * `CONTRACTS` below. The two must never be derived from one another.
+ */
+export const ARTIFACT_VERSIONS = {
+ 'switch-core': '0.12.3',
+ switchdash: '0.19.2',
+ 'agent-runtime': '0.1.5',
+ sidecar: '1.8.0',
+ 'switch-connector': '0.7.8',
+ 'switch-connector-codex': '0.2.0',
+} as const satisfies Record<string, string>;
+
+export type ArtifactName = keyof typeof ARTIFACT_VERSIONS;
+
+/** The release version of an artifact. */
+export function artifactVersion(artifact: ArtifactName): string {
+ return ARTIFACT_VERSIONS[artifact];
+}
+
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': {
@@ -56,7 +76,7 @@ export function contractRange(contract: string, artifact: string): ContractRange
const declared = registry[contract]?.[artifact];
if (declared === undefined) {
throw new Error(
- `contracts.yaml declares no range for artifact '${artifact}' in contract '${contract}'`
+ `artifacts.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.ts
index 09f4524d3..37608e9ed 100644
--- a/dash/packages/shared/src/index.ts
+++ b/dash/packages/shared/src/index.ts
@@ -8,7 +8,15 @@ export {
type Ok,
type Result,
} from './result';
-export { CONTRACTS, contractRange, type ContractName, type ContractRange } from './contracts';
+export {
+ ARTIFACT_VERSIONS,
+ artifactVersion,
+ CONTRACTS,
+ contractRange,
+ type ArtifactName,
+ type ContractName,
+ type ContractRange,
+} from './artifacts';
export { Emitter } from './emitter';
export { isDeepEqual } from './deep-equal';
export type { IDisposable, IInitializable, ILifecycle, Lease, Unsubscribe } from './lifecycle';
diff --git a/dash/packages/shared/src/contracts.ts b/dash/packages/switch-agent-runtime/src/artifacts.ts
similarity index 74%
rename from dash/packages/shared/src/contracts.ts
rename to dash/packages/switch-agent-runtime/src/artifacts.ts
index 6d3baedd4..db6108372 100644
--- a/dash/packages/shared/src/contracts.ts
+++ b/dash/packages/switch-agent-runtime/src/artifacts.ts
@@ -1,7 +1,7 @@
/**
- * Generated from contracts.yaml by scripts/gen_contracts.py.
+ * Generated from artifacts.yaml by scripts/gen_artifacts.py.
*
- * Do NOT edit this file. Edit contracts.yaml and run `just contracts`.
+ * Do NOT edit this file. Edit artifacts.yaml and run `just artifacts`.
*/
/**
@@ -15,6 +15,26 @@ export interface ContractRange {
readonly accepts: number;
}
+/**
+ * Where each artifact is. Says nothing about compatibility — that is
+ * `CONTRACTS` below. The two must never be derived from one another.
+ */
+export const ARTIFACT_VERSIONS = {
+ 'switch-core': '0.12.3',
+ switchdash: '0.19.2',
+ 'agent-runtime': '0.1.5',
+ sidecar: '1.8.0',
+ 'switch-connector': '0.7.8',
+ 'switch-connector-codex': '0.2.0',
+} as const satisfies Record<string, string>;
+
+export type ArtifactName = keyof typeof ARTIFACT_VERSIONS;
+
+/** The release version of an artifact. */
+export function artifactVersion(artifact: ArtifactName): string {
+ return ARTIFACT_VERSIONS[artifact];
+}
+
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': {
@@ -56,7 +76,7 @@ export function contractRange(contract: string, artifact: string): ContractRange
const declared = registry[contract]?.[artifact];
if (declared === undefined) {
throw new Error(
- `contracts.yaml declares no range for artifact '${artifact}' in contract '${contract}'`
+ `artifacts.yaml declares no range for artifact '${artifact}' in contract '${contract}'`
);
}
return declared;
diff --git a/dash/packages/switch-agent-runtime/src/event-stream.ts b/dash/packages/switch-agent-runtime/src/event-stream.ts
index a9e457e97..33904a721 100644
--- a/dash/packages/switch-agent-runtime/src/event-stream.ts
+++ b/dash/packages/switch-agent-runtime/src/event-stream.ts
@@ -1,4 +1,4 @@
-import { contractRange } from './contracts';
+import { contractRange } from './artifacts';
import { readSse, type SseFrame } from './sse';
import type { AgentBridgeEvent, SwitchCredentials } from './types';
import { RUNTIME_ARTIFACT, RUNTIME_VERSION } from './version';
diff --git a/dash/packages/switch-agent-runtime/src/index.ts b/dash/packages/switch-agent-runtime/src/index.ts
index 81ae9cf69..e8147e36d 100644
--- a/dash/packages/switch-agent-runtime/src/index.ts
+++ b/dash/packages/switch-agent-runtime/src/index.ts
@@ -16,7 +16,15 @@
* does not drag in the MCP SDK.
*/
-export { CONTRACTS, contractRange, type ContractName, type ContractRange } from './contracts';
+export {
+ ARTIFACT_VERSIONS,
+ artifactVersion,
+ CONTRACTS,
+ contractRange,
+ type ArtifactName,
+ type ContractName,
+ type ContractRange,
+} from './artifacts';
export {
BEAT_INTERVAL_MS,
SwitchEventStream,
diff --git a/dash/packages/switch-agent-runtime/src/version.test.ts b/dash/packages/switch-agent-runtime/src/version.test.ts
index 10b8ff836..a84489b8e 100644
--- a/dash/packages/switch-agent-runtime/src/version.test.ts
+++ b/dash/packages/switch-agent-runtime/src/version.test.ts
@@ -1,7 +1,7 @@
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
-import { CONTRACTS } from './contracts';
+import { CONTRACTS } from './artifacts';
import { RUNTIME_ARTIFACT, RUNTIME_VERSION } from './version';
const manifest = JSON.parse(
@@ -10,10 +10,10 @@ const manifest = JSON.parse(
describe('the runtime declares its own version', () => {
it('matches package.json', () => {
- // The number is written twice because package.json cannot be imported
- // without inlining the manifest into the bundle. This is what makes that
- // safe: a release bump that misses one side fails here rather than
- // shipping a runtime that lies about which release it is.
+ // RUNTIME_VERSION is now derived from artifacts.yaml rather than written
+ // here, and the registry is checked against package.json by
+ // `just artifacts`. This asserts the same thing from the other side, in the
+ // ecosystem that actually publishes the package.
expect(RUNTIME_VERSION).toBe(manifest.version);
});
diff --git a/dash/packages/switch-agent-runtime/src/version.ts b/dash/packages/switch-agent-runtime/src/version.ts
index 5165aa97e..c954b1756 100644
--- a/dash/packages/switch-agent-runtime/src/version.ts
+++ b/dash/packages/switch-agent-runtime/src/version.ts
@@ -1,17 +1,18 @@
+import { artifactVersion } from './artifacts';
+
/**
* This artifact's own release version (CHOO-1865).
*
* A semver says *where* an artifact is — which release you are running. It says
* nothing about whether it can talk to anything; that is what the contract
- * revisions in `./contracts` are for. The two move independently and must never
+ * revisions in `./artifacts` are for. The two move independently and must never
* be derived from one another.
*
- * package.json cannot be imported here without inlining the whole manifest into
- * the bundle, so the number is written twice. `version.test.ts` fails if the two
- * disagree, which is the part that makes the duplication safe — a comment
- * reading "keep in sync" is what let COMPATIBLE_SWITCH_VERSION drift.
+ * Derived from `artifacts.yaml` rather than written here, so it cannot drift
+ * from package.json. It used to be a literal kept honest by a test, which is
+ * better than the comment it replaced but still a second copy to get wrong.
*/
-export const RUNTIME_VERSION = '0.1.5';
+export const RUNTIME_VERSION = artifactVersion('agent-runtime');
/** The artifact name this package declares itself as to Switch. */
export const RUNTIME_ARTIFACT = 'agent-runtime';
diff --git a/justfile b/justfile
index 4c974d778..cf8a79a15 100644
--- a/justfile
+++ b/justfile
@@ -78,18 +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
+# ── Regenerate everything declared in artifacts.yaml ──────────────────────────
+# artifacts.yaml is the only authored copy of what each artifact is and what it
+# speaks. Each artifact needs it compiled in, so the per-language modules are
+# generated rather than kept in step by hand.
+artifacts:
+ uv run --project core python scripts/gen_artifacts.py
+
+# ── Verify the registry, the generated modules and the declared versions ──────
+# Fails when artifacts.yaml changed without regenerating, when a generated
+# module was hand-edited, or when a file a packaging ecosystem owns (pyproject,
+# package.json, plugin.json) disagrees with the registry.
+artifacts-check:
+ uv run --project core python scripts/gen_artifacts.py --check
# ── Run alembic migrations ─────────────────────────────────────────────────────
migrate:
diff --git a/scripts/gen_artifacts.py b/scripts/gen_artifacts.py
new file mode 100644
index 000000000..3a6065d40
--- /dev/null
+++ b/scripts/gen_artifacts.py
@@ -0,0 +1,495 @@
+#!/usr/bin/env python3
+"""Generate and verify everything declared in artifacts.yaml.
+
+`artifacts.yaml` is the only authored copy of what each Switch artifact is and
+what it speaks. Artifacts ship independently and in different languages, so each
+needs the registry compiled in — a running artifact cannot ask a file on someone
+else's disk what it is.
+
+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. uv.lock drifted to a
+switch-core version two patches behind pyproject, with nothing to notice.
+
+Two jobs, and the split matters:
+
+* **Generate** the constants nothing else owns. Anything derived from the
+ registry is written from it, so it cannot be edited into disagreement.
+* **Verify** the ones a packaging ecosystem owns. `importlib.metadata` reads
+ pyproject, `npm publish` reads package.json, and both release workflows verify
+ the git tag against them. Those files stay authoritative for their tooling —
+ generating into them would fight the ecosystem for no gain. The registry is
+ checked against them instead, which is enough to stop silent drift.
+
+Usage:
+ python scripts/gen_artifacts.py # write the generated modules
+ python scripts/gen_artifacts.py --check # verify everything, write nothing
+
+`--check` regenerates in memory and compares, so it catches both drift
+directions: editing the registry 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 json
+import re
+import sys
+import tomllib
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+SOURCE = REPO_ROOT / "artifacts.yaml"
+
+BANNER_LINES = [
+ "Generated from artifacts.yaml by scripts/gen_artifacts.py.",
+ "",
+ "Do NOT edit this file. Edit artifacts.yaml and run `just artifacts`.",
+]
+
+SEMVER = re.compile(r"^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$")
+
+
+@dataclass(frozen=True)
+class Target:
+ path: Path
+ render: Any
+
+
+@dataclass(frozen=True)
+class Artifact:
+ name: str
+ description: str
+ version: str
+ declared_in: str | None
+ pins: dict[str, str]
+
+
+@dataclass(frozen=True)
+class Contract:
+ name: str
+ description: str
+ artifacts: dict[str, tuple[int, int]]
+
+
+@dataclass(frozen=True)
+class Registry:
+ artifacts: list[Artifact]
+ contracts: list[Contract]
+
+
+def _squash(text: object) -> str:
+ return " ".join(str(text).split())
+
+
+def load_registry() -> Registry:
+ """Parse and validate artifacts.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):
+ raise ValueError(f"{SOURCE} must be a mapping")
+ for section in ("artifacts", "contracts"):
+ if section not in raw:
+ raise ValueError(f"{SOURCE} must have a top-level {section!r} mapping")
+
+ artifacts = [_parse_artifact(name, body) for name, body in raw["artifacts"].items()]
+ known = {artifact.name for artifact in artifacts}
+ for artifact in artifacts:
+ for pinned in artifact.pins:
+ if pinned not in known:
+ raise ValueError(
+ f"artifact {artifact.name!r} pins {pinned!r}, which is not "
+ "an artifact in this registry"
+ )
+
+ contracts = [_parse_contract(name, body) for name, body in raw["contracts"].items()]
+ return Registry(artifacts=artifacts, contracts=contracts)
+
+
+def _parse_artifact(name: str, body: object) -> Artifact:
+ if not isinstance(body, dict):
+ raise ValueError(f"artifact {name!r}: expected a mapping")
+ description = body.get("description")
+ if not description:
+ raise ValueError(f"artifact {name!r}: a description is required")
+
+ version = body.get("version")
+ if not isinstance(version, str) or not SEMVER.fullmatch(version):
+ raise ValueError(
+ f"artifact {name!r}: version must be three-part semver, got {version!r}"
+ )
+
+ declared_in = body.get("declared_in")
+ if declared_in is not None and not isinstance(declared_in, str):
+ raise ValueError(f"artifact {name!r}: declared_in must be a path")
+
+ pins_raw = body.get("pins") or {}
+ if not isinstance(pins_raw, dict):
+ raise ValueError(f"artifact {name!r}: pins must be a mapping")
+ pins: dict[str, str] = {}
+ for pinned, pinned_version in pins_raw.items():
+ if not isinstance(pinned_version, str) or not SEMVER.fullmatch(pinned_version):
+ raise ValueError(
+ f"artifact {name!r}: pin of {pinned!r} must be three-part semver, "
+ f"got {pinned_version!r}"
+ )
+ pins[pinned] = pinned_version
+
+ return Artifact(
+ name=name,
+ description=_squash(description),
+ version=version,
+ declared_in=declared_in,
+ pins=pins,
+ )
+
+
+def _parse_contract(name: str, body: object) -> Contract:
+ 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)
+
+ return Contract(name=name, description=_squash(description), artifacts=artifacts)
+
+
+# ── Reading the versions other ecosystems own ────────────────────────────────
+
+
+def read_declared_version(relative_path: str) -> str:
+ """The version as the owning ecosystem's own file states it."""
+ path = REPO_ROOT / relative_path
+ if not path.exists():
+ raise ValueError(f"declared_in points at {relative_path}, which does not exist")
+ if path.suffix == ".toml":
+ return str(tomllib.loads(path.read_text())["project"]["version"])
+ if path.suffix == ".json":
+ return str(json.loads(path.read_text())["version"])
+ raise ValueError(f"don't know how to read a version out of {relative_path}")
+
+
+# Constants that must equal a registry value but cannot be generated, because
+# the file holding them is loaded without module resolution — electron-builder
+# reads app-identity*.ts under bare Node, where extensionless ESM specifiers do
+# not resolve, so those files carry no imports by design. Verified instead,
+# which is all that is needed to stop them drifting.
+LITERAL_CHECKS: list[tuple[str, str, str]] = [
+ (
+ "dash/apps/switchdash-desktop/src/shared/app-identity.ts",
+ "COMPATIBLE_SWITCH_VERSION",
+ "switchdash.pins.switch-core",
+ ),
+ (
+ "dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts",
+ "COMPATIBLE_SWITCH_VERSION",
+ "switchdash.pins.switch-core",
+ ),
+]
+
+
+def read_ts_literal(relative_path: str, name: str) -> str:
+ path = REPO_ROOT / relative_path
+ match = re.search(
+ rf"export const {re.escape(name)}\s*=\s*['\"]([^'\"]+)['\"]", path.read_text()
+ )
+ if match is None:
+ raise ValueError(f"{relative_path} declares no {name}")
+ return match.group(1)
+
+
+# ── Emitters ─────────────────────────────────────────────────────────────────
+
+
+def render_python(registry: Registry) -> 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("# Where each artifact is. Says nothing about compatibility — that is")
+ lines.append("# CONTRACTS below. The two must never be derived from one another.")
+ lines.append("ARTIFACT_VERSIONS: Final[dict[str, str]] = {")
+ for artifact in registry.artifacts:
+ lines.append(f' "{artifact.name}": "{artifact.version}",')
+ lines.append("}")
+ lines.append("")
+ lines.append("CONTRACTS: Final[dict[str, dict[str, ContractRange]]] = {")
+ for contract in registry.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"artifacts.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(registry: Registry) -> 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("/**")
+ lines.append(
+ " * Where each artifact is. Says nothing about compatibility — that is"
+ )
+ lines.append(
+ " * `CONTRACTS` below. The two must never be derived from one another."
+ )
+ lines.append(" */")
+ lines.append("export const ARTIFACT_VERSIONS = {")
+ for artifact in registry.artifacts:
+ lines.append(f" {ts_key(artifact.name)}: '{artifact.version}',")
+ lines.append("} as const satisfies Record<string, string>;")
+ lines.append("")
+ lines.append("export type ArtifactName = keyof typeof ARTIFACT_VERSIONS;")
+ lines.append("")
+ lines.append("/** The release version of an artifact. */")
+ lines.append("export function artifactVersion(artifact: ArtifactName): string {")
+ lines.append(" return ARTIFACT_VERSIONS[artifact];")
+ lines.append("}")
+ lines.append("")
+ lines.append("export const CONTRACTS = {")
+ for contract in registry.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(
+ " `artifacts.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" / "artifacts.py", render_python),
+ # switchdash: the desktop app and the sidecar it bundles and deploys.
+ Target(
+ REPO_ROOT / "dash" / "packages" / "shared" / "src" / "artifacts.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"
+ / "artifacts.ts",
+ render_typescript,
+ ),
+]
+
+
+def check_declared_versions(registry: Registry) -> list[str]:
+ """Compare the registry against the files packaging ecosystems own."""
+ problems: list[str] = []
+ for artifact in registry.artifacts:
+ if artifact.declared_in is None:
+ continue
+ try:
+ actual = read_declared_version(artifact.declared_in)
+ except (ValueError, KeyError) as exc:
+ problems.append(f" {artifact.name}: {exc}")
+ continue
+ if actual != artifact.version:
+ problems.append(
+ f" {artifact.name}: artifacts.yaml says {artifact.version}, "
+ f"{artifact.declared_in} says {actual}"
+ )
+
+ by_name = {artifact.name: artifact for artifact in registry.artifacts}
+ for relative_path, constant, source in LITERAL_CHECKS:
+ owner, _, pinned = source.partition(".pins.")
+ expected = by_name[owner].pins[pinned]
+ try:
+ actual = read_ts_literal(relative_path, constant)
+ except ValueError as exc:
+ problems.append(f" {exc}")
+ continue
+ if actual != expected:
+ problems.append(
+ f" {relative_path}: {constant} is {actual}, but artifacts.yaml "
+ f"pins {expected}"
+ )
+ return problems
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--check",
+ action="store_true",
+ help="verify everything and write nothing",
+ )
+ args = parser.parse_args()
+
+ registry = load_registry()
+ stale: list[Path] = []
+
+ for target in TARGETS:
+ expected = target.render(registry)
+ 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}")
+
+ problems = check_declared_versions(registry)
+
+ if stale:
+ print(
+ "Generated modules are out of date:\n"
+ + "\n".join(f" {path}" for path in stale)
+ + "\n\nEither artifacts.yaml changed without regenerating, or a generated\n"
+ "file was hand-edited. Run `just artifacts` and commit the result.",
+ file=sys.stderr,
+ )
+ if problems:
+ print(
+ "\nartifacts.yaml disagrees with the files it records:\n"
+ + "\n".join(problems)
+ + "\n\nThese files are owned by their packaging ecosystem, so the registry\n"
+ "is checked against them rather than generating into them. Bring the two\n"
+ "into agreement — usually by editing artifacts.yaml to match the release.",
+ file=sys.stderr,
+ )
+ if stale or problems:
+ return 1
+
+ if args.check:
+ print("Registry, generated modules and declared versions all agree.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/gen_contracts.py b/scripts/gen_contracts.py
deleted file mode 100644
index 8a8df4e22..000000000
--- a/scripts/gen_contracts.py
+++ /dev/null
@@ -1,293 +0,0 @@
-#!/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())