diff --git a/.env.example b/.env.example index b393267..54b04c7 100644 --- a/.env.example +++ b/.env.example @@ -75,15 +75,25 @@ COMPANION_SESSION_KEY= COMPANION_TASK_KEY= COMPANION_DB_PASSWORD= -# ---- the local model (plan step 5): llama.cpp's server on the GPU, behind the gateway as provider `local` -# the folder holding GGUF files (mounted read-only) and the file to serve; empty LLM_MODEL: no local model +# ---- the local models (plan step 5, S-169): llama.cpp's server, behind the gateway. Two of them: a slow capable one on +# the CPU and in RAM (provider `local`), and a small fast one wholly on the GPU (provider `fast`) for what must answer at +# once; the GPU is left to the fast models (a slow model's GPU work slowed the fast one by a quarter, S-169) +# the folder holding GGUF files (mounted read-only) and the file to serve; empty LLM_MODEL: no slow model LLM_MODELS_DIR= LLM_MODEL= # its name at the gateway (local/) -LLM_ALIAS=gemma -# llama-server's options: all layers on the GPU, MoE experts in system RAM, 16k context, 4-bit KV cache -LLM_ARGS=-ngl 999 --cpu-moe -c 16384 -ctk q4_0 -ctv q4_0 -fa auto -LLM_IMAGE=ghcr.io/ggml-org/llama.cpp:server-cuda12-b12098 +LLM_ALIAS=slow +# llama-server's options: no layers on the GPU, 6 threads (memory bandwidth is the limit: 8 were no faster), 16k context, +# 4-bit KV cache; a machine with a free GPU may put layers there (-ngl 999 --cpu-moe, then -ot for experts) +LLM_ARGS=-ngl 0 --no-op-offload -t 6 -c 16384 -b 512 -ub 128 -ctk q4_0 -ctv q4_0 -fa on +# llama.cpp's server image, for both models (b12627: Inkling 2's architecture, inkling2_loop, arrived in b12591) +LLM_IMAGE=ghcr.io/ggml-org/llama.cpp:server-cuda12-b12627 +# the fast model: its folder and file (empty: none), its name at the gateway (fast/), its options; +# recommended: LFM3 1.7B (Q6_K GGUF), downloaded by you, under Liquid AI's LFM Open License v1.0 (read it; S-169, S-188) +LLM_FAST_MODELS_DIR= +LLM_FAST_MODEL= +LLM_FAST_ALIAS=fast +LLM_FAST_ARGS=-ngl 999 -t 2 -c 32768 -fa on -ctk q8_0 -ctv q8_0 # ---- the voice head (plan step 5): the companion's voice and face, at 127.0.0.1:VOICE_PORT VOICE_PORT=8110 @@ -92,6 +102,16 @@ VOICE_STYLE=af_heart VOICE_THREADS=4 VOICE_SILENCE_S=0.6 VOICE_KEY= +# the model the voice head answers with; empty: the slow model (local/); e.g. fast/fast +VOICE_MODEL= +# what decides between answering by talking and handing work to the worker (S-170): tools (the voice model calls talk, +# delegate or save_note), embed (a vote over example embeddings, by the store's embedding model) or off (the voice +# model's own HANDOFF line, to the companion) +VOICE_ROUTER=tools +# the time zone the voice head tells its model and sets reminders in (e.g. America/Los_Angeles); empty: UTC +TZ= +# signs the local SearXNG's sessions (the voice head's search tool; compose service search), generated once +SEARXNG_SECRET= # the avatar (S-158, S-159): a .vrm, .glb or .gltf under .state/avatar/ (never committed), e.g. .state/avatar/pixar-girl/scene.gltf; empty: the canvas face AVATAR_FILE= # Kokoro on the GPU (compose service tts, S-150): http://tts:8880; empty: Kokoro on the CPU in the voice head @@ -109,9 +129,13 @@ WORKER_BLOCKS= WORKER_DB_PASSWORD= # its kernel login (the memory profile), copied here by scripts/up.sh from .state/kernel/worker.env WORKER_KERNEL_URL= -# the model it asks for at the gateway; steps a task may take; tokens of context it keeps (the model has 16k); empty: the model's own + +# ---- the assistant's experience (S-182): one episode per model call the gate sees, its text encrypted under this key +# (made by scripts/settings.sh; keep a copy: without it the stored text cannot be read) +EXPERIENCE_KEY= +# the model it asks for at the gateway (empty: local/); steps a task may take; tokens of context it keeps (the model has 16k); empty: the model's own # reasoning setting, or none | low | medium | high -WORKER_MODEL=local/gemma +WORKER_MODEL= WORKER_MAX_STEPS=8 WORKER_CONTEXT_TOKENS=11000 WORKER_REASONING= diff --git a/CLAUDE.md b/CLAUDE.md index 75f0b70..464039b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,26 +1,34 @@ # Substrate -An agent framework: you put an environment on a system you need, run it, and watch and change it. Its shape is -`docs/framework.md`; what is built next is `docs/plan.md`, the one plan; every default and its reason is in -`DECISIONS.md` (append-only). Read the plan first. +An operating system for AI agents (S-185): a top-level orchestrator (an ordinary LLM harness given skills, MCP +servers and hooks) that maps, orchestrates and optimises a working system, on a kernel made of Postgres where +everything is an object. Its shape is `docs/framework.md`; what is built next is `docs/plan.md` ("Next, in order"), +the one plan; every default and its reason is in `DECISIONS.md` (append-only). Read the plan first. This is the **fresh tree** (S-137). v1 is tagged `v1-final` and its plans are in `docs/archive/`: history, not plans to work from. v1's databases are kept in the same Postgres volume (`workbench`, `gateway`) and dumped in `.state/backups/`; what people stated there comes back as data imported into the new store. -See `docs/repos.md` for what each repository (Kernel, Substrate, MetaSoar, Morphogen) owns. +The layers (S-185, `docs/framework.md`, `docs/repos.md`): **the Kernel** (Postgres made into a kernel), **Substrate** +(the orchestrator kit, the adapters, the reference stack), **Morphogen** (the optimiser, a Claude Code plugin), +**distributions** (folders in `distributions/` here for now), **MetaSoar** (the research). Every dependency is a +contract, never another project's code. Environments are OpenEnv environments (S-184). Name parts by their role and +models by their alias (`fast`, `slow`, `cloud`), never by model. **The table below is what is in the tree today:** +the companion, voice head, worker, blocks and the ladder's experience store are the assistant distribution's parts +and move into `distributions/assistant/` (plan step 3). | Part | Where | Role | | --- | --- | --- | -| The store | the Knowledge Kernel (S-153, S-154, S-156: the UI and the skills read it from the kernel's database `kernel`, the agent's tools are the kernel's MCP `substrate` profile; `scripts/kernel.sh`); the old `store` package is retired and its schema stays in database `substrate` until the owner drops it (S-156) | Wikibase's data model with OpenWiki's pinned evidence (S-135, S-138): entities, statements with ranks, references, spans, revisions, a page per entity; the agent's tools over MCP, and maps, roles, interfaces and catalogs (S-139; the `map` and `catalog` skills) | +| The store | the Knowledge Kernel (S-153, S-154, S-156: the UI and the skills read it from the kernel's database `kernel`, the agent's tools are the kernel's MCP `substrate` profile; `scripts/kernel.sh`); the old `store` package is retired and its schema was dropped on 2026-11-23 (S-191; a dump is in `.state/backups/`) | Wikibase's data model with OpenWiki's pinned evidence (S-135, S-138): entities, statements with ranks, references, spans, revisions, a page per entity; the agent's tools over MCP, and maps, roles, interfaces and catalogs (S-139; the `map` and `catalog` skills) | | envkit | `envkit/` (declarations in `envkit/declarations/`; tests: `python3 -m pytest envkit`) | The fast in-process scheduler (lockstep or realtime) for live play, one module contract with `environment/` (S-161); moved from MetaSoar | | The real-time environment | `environment/` (schema `env` in `environment/sql/`, migrated by `environment/db.py`, the channel in `environment/channel.py`) on pgmq in the same Postgres | signals logged whole and fanned out as topics, a queue per actuator behind its gate (`free`, `propose`, `deny`), the channel into Claude Code, archived only on `ack` (S-143) | | The model gateway | container `gateway` (Bifrost), `scripts/gateway.py` | every model call goes through it with its caller's key and is recorded there, not by the caller (S-77) | -| Local models | container `ollama`; container `llm` (llama.cpp, profile `llm`) | Ollama for the store's embeddings; the local chat model (Gemma 4 26B-A4B from `LLM_MODELS_DIR`) on llama.cpp, at the gateway as `local/gemma` (S-149) | +| Local models | container `ollama`; containers `llm` and `llm-fast` (llama.cpp, profile `llm`) | Ollama for the store's embeddings; two chat models (S-169): the slow capable one, Inkling 2 Mini on the CPU, at the gateway as `local/slow`; the fast one, LFM3 1.7B on the GPU, as `fast/fast` (the alias names the role, not the model; Gemma is retired) | | Tools | `bin/`, container `substrate-tools` | the scripts' Python and gitleaks, run in a container as you (S-19) | -| The companion | `deploy/companion` (compose service `companion`), `environment/companion.py` (service `environment`), the UI's `#/companion` | the first environment: Claude Code on Haiku through the gateway's pass-through route on the owner's login, fed by the channel; it replies, starts background tasks and proposes budget and model changes (S-136, S-144) | -| The voice head | `voice/` (compose service `voice`, profile `voice`) on 127.0.0.1:8110 | the companion's voice and face: microphone in over a WebSocket, Silero and Parakeet to text, the local model to answer, Kokoro to speak, a face that moves with it; hands real work to the companion (S-147, S-149) | -| The worker | `environment/worker.py` (environment `worker`), `deploy/worker/` (compose service `worker`, profile `llm`, the kernel's image plus `openai`), the UI's `#/worker` | an offline agent on the local model (`local/gemma` through the gateway as caller `worker:loop`): our own loop on `mcp` + `openai` (S-162); the kernel's `memory` profile over stdio and a few workspace tools; `gate(state)` before every model call is M-17's seam (S-163) | +| The gate (being built) | experience: `env.experience` (`environment/sql/008_experience.sql`, `environment/experience.py`, key `EXPERIENCE_KEY`; S-183); the decider's trial `scripts/trials/decider/`; the proxy next (`docs/plan.md` step 3) | System 1, in a proxy in front of the gateway: at every model call it recalls a response distilled from the assistant's experience (episodes of scenario, response, outcome): a skill, or a rung (`fast`, `slow`, `cloud`); TabICL over embeddings with outcome-labelled episodes from Postgres, the fast model's probabilities as cold start; impasses typed, outcomes attached later by episode id (S-178 to S-182) | +| The companion (to retire) | `deploy/companion` (compose service `companion`), `environment/companion.py` (service `environment`), the UI's `#/companion` | Claude Code on Haiku through the gateway's pass-through route on the owner's login, fed by the channel (S-136, S-144); becomes the assistant's `cloud` rung behind `propose`, then retires as a separate agent (S-181) | +| The voice head | `voice/` (compose service `voice`, profile `voice`) on 127.0.0.1:8110 | the companion's voice and face: microphone in over a WebSocket, Silero and Parakeet to text, the fast model deciding each turn by the tool it calls (talk, quick tools such as notes, reminders, lookup and SearXNG search, or delegate), Kokoro to speak, a face that moves with it; delegated work goes to the worker on the slow model, not the companion (S-147, S-170, S-171) | +| The worker (becoming the assistant) | `environment/worker.py` (environment `worker`), `deploy/worker/` (compose service `worker`, profile `llm`, the kernel's image plus `openai`), the UI's `#/worker` | the assistant's one loop (S-181); today an agent on the self-hosted slow model (`local/slow` through the gateway as caller `worker:loop`; S-165, S-169): our own loop on `mcp` + `openai` (S-162); the kernel's `memory` profile over stdio and a few workspace tools; `gate(state)` before every model call is M-17's seam (S-163) | | Blocks | `blocks/` (`block.yaml` blocks, JSON plans, `blocks/run.py` the default executor, `blocks/executor.yaml`; tests: `scripts/tests/test_blocks.py`) | what the agent compiles from what it solved: catalog entries with an interface and effects, assembled as P-Plan plans, run without the model; `skill_gate` plugs into the worker's `gate` (S-157, S-164) | | Components and the judge | `env.component` and `env.verdict` (`environment/sql/007_components.sql`), `environment/author.py`, `environment/judge.py` (compose service `judge`), `judge/cases` (the judge's only) | every version of a component with its card; an author proposes from the record, the judge tests it against the active one on cases the author cannot read, the owner activates (S-151) | | The UI | `ui/` (`ui/server.py`, `ui/static`), compose service `ui` on 127.0.0.1:8100 | the store's pages and maps as diagrams (S-140), read-only; v1's Workbench rebuilt, with no name of its own (S-141) | @@ -45,11 +53,13 @@ See `docs/repos.md` for what each repository (Kernel, Substrate, MetaSoar, Morph Claude Code. A tool goes into a container (`deploy/tools/Containerfile`, or the companion's). 7. **Licences:** permissive or LGPL for what the repository contains or links into Substrate's code. A GPL part may be a default when it is fetched at setup (never in the repository), runs unmodified in its own container and is - reached over a process boundary (S-146). Check before adding. + reached over a process boundary (S-146). Models and tools the user downloads themselves (never bundled or + committed) may be recommended whatever their licence, with the licence named (S-188). Check before adding. 8. **Every change ends with `scripts/check.sh` passing**, and `scripts/test.sh` where tests exist, or with the failure named and explained. -9. **Morphogen is out of the build** while the owner refactors it elsewhere: do not touch `repos/morphogen` or - depend on it. Fixes to an upstream project go by pull request (the `upstream` skill). +9. **Morphogen is the optimiser** (S-185; it was out of the build only so it could be iterated on quickly): use it + through its contract (the cell file, its Claude Code plugin and MCP server), never by importing its code; change + it only by pull request in its own repository, like any upstream project (the `upstream` skill). ## Working with the owner @@ -69,7 +79,7 @@ scripts/test.sh [FILE...] # the test suites, in the tools container scripts/build.sh [db|tools|companion|voice|kernel|worker] # none: pull published images, build what did not pull; SUBSTRATE_BUILD=1 builds all scripts/logs.sh SERVICE # db, gateway, ollama, ui, environment, companion, llm, voice scripts/tools.sh start|stop|status -scripts/kernel.sh init|export|login NAME|mcp NAME # the Knowledge Kernel: schema, one-off export of the old `store` schema, an agent's login and its MCP server +scripts/kernel.sh init|export|login NAME|mcp NAME # the Knowledge Kernel: schema, one-off export of the old `store` schema (now dropped), an agent's login and its MCP server scripts/down.sh [--volumes] # stop (deleting data asks first) python3 scripts/gateway.py render|keys # the gateway's config from .env and its callers bin/in-tools python3 scripts/db.py init # the databases and the environment's schema (environment/sql/) diff --git a/DECISIONS.md b/DECISIONS.md index 78c7ad8..9338cf9 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -176,3 +176,27 @@ Status: **decided** (owner agreed), **adopted** (recommended and taken; confirm | S-166 | **The judge's main job is choosing and writing tests; guards against reward hacking scale with the stakes** (2026-11-22; owner: "Substrate's 'judge' and the general need for the role in self-improvement is more about test/benchmark selection/creation (another catalog!) but the *promise* (not a threat) of reward hacking pushes us toward all kinds of adversarial countermeasures... which may not always be necessary and there's probably lower-hanging fruit"). (a) **Benchmarks are a catalog** (S-139): each case set is a catalog entry tied to the goal it measures (`has-goal`, its metric and target), with where it came from; choosing cases for a candidate is choosing from that catalog, and new cases are written where a goal has none. (b) **Cheap guards first, everywhere:** the harness measures outcomes and the candidate's own figures are never scored; the author never reads the cases (S-151); cases written or collected after the candidate is frozen (time-split, whole days held out); several metrics, and a regression on any blocks; cases replayed from the record, not synthetic only; a person activates and spot-checks a sample. (c) **Adversarial measures only where a verdict grants autonomy** or the candidate could reach the judge's inputs (process isolation, forged-result tests, as MetaSoar's harness plan has). (d) Next, when step 3's blocks are judged: a `benchmark` entry kind in the catalog and the judge reading cases from it. | | S-167 | **The stack runs from published images; a machine pulls instead of building** (2026-11-22; builds on S-19, S-154, S-163; follows the kernel's D-120). (a) **Published:** `.github/workflows/images.yml` builds and pushes `ghcr.io/openreplicant/substrate-db`, `-tools`, `-companion` and `-worker` (the four Containerfiles compose builds, apart from voice) on a push to `main` and on `v*` tags, tagged `main`, the short SHA, the tag as pushed and its semver form. A pull request builds without pushing and does not run for a fork. linux/amd64 only. The kernel's image is the Kernel repository's (`ghcr.io/openreplicant/kernel`, D-120); the worker is built `FROM` it (`ARG KERNEL_IMAGE`, default `ghcr.io/openreplicant/kernel:main`). `deploy/ontop` is not built by compose and not published. (b) **Voice is not published:** its image carries espeak-ng (GPL-3.0) inside the sherpa-onnx and kokoro-onnx wheels (S-146). Running it unmodified in its own container is fine; handing the image to others is distribution, which needs its source offered (espeak-ng's, at the version in those wheels, with the licence text and the written offer), and that is more than a note, so voice stays a local build (`localhost/substrate-voice:local`, `build:` in compose). Revisit when someone needs it prebuilt. (c) **Compose:** each service names its image as `ghcr.io/openreplicant/substrate-NAME:${SUBSTRATE_IMAGE_TAG:-main}` and keeps its `build:` as the fallback (`ui` carries the tools build; `environment` and `judge` share that image); kernel, kernel-init and kernel-export use `ghcr.io/openreplicant/kernel:${KERNEL_IMAGE_TAG:-main}`. `scripts/lib.sh` has `image_ref NAME` (the one place the names are made), `scripts/runtime/compose.sh` has `rt_pull`. `scripts/build.sh` with no argument pulls each published image and builds only those that did not pull, then builds voice; `SUBSTRATE_BUILD=1` (shell or `.env`) builds everything; a named part is always built. A local build is tagged with the published name, so compose, `tools.sh`, `kernel.sh` and `test.sh` see one image either way; `up.sh` and `bootstrap.sh` are unchanged because they call `build.sh`. `.env.example` has `SUBSTRATE_IMAGE_TAG=main`, `KERNEL_IMAGE_TAG=main`, `SUBSTRATE_BUILD=` (empty). (d) **Needs the owner:** the organisation's Actions policy must allow the pinned `docker/*` and `actions/checkout` actions and give `GITHUB_TOKEN` write access to packages; after the first push on `main` each new package is private, so set each to public (then `pull` needs no login) and, if one does not link itself to this repository, add the repository under the package's Actions access with write role; the kernel's #132 (its image workflow) merged first, so `ghcr.io/openreplicant/kernel` exists, since the worker build and the kernel services need it (until it does, `build.sh` falls back to cloning `repos/kernel` and building). Rule 8's `scripts/check.sh` run is the owner's, on their machine: nothing here was pulled, built or started (no Podman, no published image). (e) **Checked here:** `sh -n` on the scripts; the compose file parses and resolves to the intended image names and the worker's build arg with Docker Compose v5.7.1 (`docker compose config`, all profiles); the worker, blocks and gateway tests. **Not checked:** Podman compose with `image` and `build` together (Podman's providers read both, and compose's default `pull_policy: missing` keeps a local build). (f) **Pins:** the workflow reuses the kernel's, all read at their tags on 2026-11-22 (D-120 (d)): `actions/checkout` v7.0.1 (`3d3c42e5aac5ba805825da76410c181273ba90b1`), `docker/setup-buildx-action` v4.4.1 (`f87e5991a6d7451dcb8d9637bfbc97413f497069`), `docker/metadata-action` v6.2.0 (`dc802804100637a589fabce1cb79ff13a1411302`), `docker/login-action` v4.8.0 (`8aa5831fb8d48d8f76594c7ddde61ae58019f550`), `docker/build-push-action` v7.4.0 (`c3c9e263c25d99ce0380d002d59b67737d91b0dc`); I did not re-check for newer releases from here | decided | | S-168 | **The first run on the owner's machine, and what it fixed** (2026-11-22; the 2026-11-22 handoff's first steps; builds on S-154, S-160, S-163, S-164). Published images all pulled (S-167 holds); voice built here. Fixed, one at a time: (a) **`COMPOSE_PROFILES`** is now listed in `.env.example` (README named it, `.env.example` did not; rule 4): `llm,voice` brings up the local model, the worker, the judge and the voice head. (b) **The voice head's avatar mount** `.state/avatar:/avatar:ro` came back to compose (added in S-160, dropped in a stacked merge). (c) **The avatar's mouth**: a model with a dedicated open-mouth key (`jawOpen`, `mouthOpen`, `viseme_aa`, `aa`) has only that key driven by speech; ARKit's 52 matched ~30 keys and moved smile, frown, pucker and mouthClose together. (d) **The worker's kernel login comes from `.env`** (`WORKER_KERNEL_URL`, copied once by `scripts/up.sh` from `scripts/kernel.sh login worker`), not a mounted 0600 file the container's own user cannot read under rootless Podman; engine-neutral, unlike `--userns keep-id`. (e) **`blocks.` actuators**: the worker's setup registers one per world-changing block in `WORKER_BLOCKS`, gate **`free`** (the example writes only into the worker's workspace, where its file tools already write ungated; a gate someone changed is kept; the owner sets `propose` with `scripts/env.py gate`), lets the worker's login close them (`env.done` needs the queue), and the skill gate's executor acts on the worker's connection; before this S-164's gate refused every world-changing step and the task fell through to the model. (f) **The worker's model client is made per event loop** (each task is its own `asyncio.run`; the shared client's kept-alive connection failed the second task with "Event loop is closed"). (g) **The kernel test fixture keeps the stack's `KK_AUTHENTICATOR_PASSWORD`**: `kk init` sets that cluster-wide role's password, so a test run locked the live UI and `check.sh` out of the kernel. (h) `test_companion` passes the kernel URL `ui/server.serve` gained in S-154. Checked by hand: the avatar loads (52 ARKit morph targets, blink on `eyeBlinkLeft/Right`); a worker task took 4 calls, each `local/gemma` as `worker:loop` in the gateway's log; the example plan's trigger answered with 0 model calls and nothing at the gateway. All suites and `check.sh` pass. | adopted | +| S-169 | **Two local models: a slow capable one on the CPU, a small fast one on the GPU** (2026-11-22; supersedes S-149's local model and its LLM_ARGS; the owner chose Inkling over Gemma). (a) **Slow:** Inkling 2 Mini (thinkingmachines, Apache-2.0 per its GGUF; `inkling2_loop`, 128 experts of 1.8B, 8 active, layers 6 to 17 run three times per token), the owner's AtomicChat Q4_K GGUF, at the gateway as `local/slow` (provider `local`; the alias names the role, not the model). Needs llama.cpp b12591 or later; **`LLM_IMAGE` is `server-cuda12-b12627`**, the newest published image with both Inkling fixes, 1 to 2 days old: an exception to rule 1's two weeks, taken because the owner chose the model; revisit after 2026-12-06. (b) **It runs on the CPU and in RAM** (`-ngl 0 --no-op-offload -t 6`, 16k context, q4_0 KV): measured with the 1.7B generating beside it, Inkling with attention on the GPU (2.1 GB) cut the fast model from 86 to 63 tok/s; CPU-only (84 MB) left it at 84, for Inkling 7.1 tok/s against 10.8. Also measured and not taken: expert layers on the GPU (7 loop layers 14.1 tok/s at 6.2 GB, 8 layers 14.6 at 6.8 GB with 0.2 GB left), `--load-mode none`, f16 or q4_0 KV, flash attention on, off or auto (all within 0.5 tok/s); 6 threads were as fast as 8 (memory bandwidth bound). Op offload had to be off: with the experts in RAM it asked for 7 to 9 GB of GPU compute buffer. (c) **Fast:** compose service `llm-fast` (profile `llm`), `LLM_FAST_MODEL` from `LLM_FAST_MODELS_DIR` wholly on the GPU, at the gateway as `fast/` (provider `fast`, open to `voice:head` and `worker:loop`); the owner's LFM3 1.7B Q6_K: 86 tok/s, ~2,100 tok/s prompt, 1.9 GB at 32k context, a correct `run_command` tool call. Its licence is LiquidAI's LFM Open License v1.0, so `.env.example` leaves `LLM_FAST_MODEL` empty: recommending it as a default is the owner's call. (d) `VOICE_MODEL` picks the voice head's model (empty: `local/slow`). With the reply component's seed prompt the 1.7B handed over 8 of 8 utterances (4/8 right, 0.3 to 1.6 s), Inkling 8/8 right in 13 to 31 s; so voice stays on the slow model until the fast/slow split is designed (a hand-over is a message to the companion, Claude on the owner's login). (e) `TTS_URL=http://tts:8880` on this machine: Kokoro on the GPU, so speech does not compete with the slow model for the CPU. (f) `check.sh` waits up to a minute for a gateway that answers nothing yet: podman 4.9.3's network DNS dropped lookups while many containers started, and a recreated gateway restarted twice before it reached its database. Measured end to end with a simulated speaker (Kokoro's speech streamed to the voice head): exact transcripts, first reply audio 0.5 to 0.7 s after the speaker stopped (on the fast model). A worker task on `local/slow`: 3 calls, 150 s (the first 102 s: the CPU reads the prompt at about 26 tok/s). GPU now: fast model 1.9 GB, Kokoro 0.8 GB, the slow model 0.08 GB, about 5 GB left. | adopted | +| S-170 | **The fast model decides each voice turn by the tool it calls; work goes to the local worker, not the companion** (2026-11-22; builds on S-169; the owner: "don't use haiku when you could use the local model", and the idea of a talk tool). (a) **`VOICE_ROUTER=tools`** (the default): every turn the voice model (`VOICE_MODEL`, here LFM3 1.7B as `fast/fast`) must call one of `talk(text)` (spoken), `delegate(task)` ("On it", and the task goes to the worker's queue as `worker.owner.message` with `reply_to: voice`) or `save_note(text)` ("Noted", and the worker gets the example plan's "save a note called ...", answered with no model call; only a failure is read out, `reply_to: voice:quiet`). Thinking off, `tool_choice: required`, a stop at `` (with thinking off it sometimes wrote plain words and then looped on that marker until the cap), plain words with no call taken as talk. The worker's answer (`worker.task.done` carrying `reply_to`, new in the worker) is condensed by the voice model into a few spoken sentences, markdown stripped, and read out when the owner is quiet. (b) **Measured** on 12 held-out utterances (`scripts/trials/voice-route/`, never used to write the prompt): the reply component's HANDOFF prompt 6/12 (it handed over everything); a JSON-constrained talk/work answer 9/12, with examples 7/12, reason first 9/12, yes/no per capability 6/12 (all false), one `delegate` tool 9/12 (1.8 s), examples as turns with thinking 7/12 (4.5 s, often empty); talk and delegate as forced tools 9/12, plus `save_note` 10/12 (without it the model said "Saved note" for a note it had not saved), plus the stop and plain-words rule 12/12 and 11/12, plus "never say you cannot: delegate" 12/12 twice (median 0.35 s); three "can't" cases 2/3. An embedding vote over 28 seed examples also scored 12/12 (65 ms on the CPU) and is kept as **`VOICE_ROUTER=embed`** (`voice/route.py` Router; the owner's corrections as `voice.route.example` signals) for a first pass later. `off` keeps the reply component's HANDOFF line to the companion. (c) End to end with a simulated speaker: small talk answered with first audio 1.5 s after the speaker stopped (the tool's text is not streamed); "Remind me to call the dentist on Monday" said "Noted" at 0.7 s and the worker wrote `notes/call-the-dentist-on-monday.txt` with 0 model calls; "How many files are in your workspace notes folder?" said "On it" at 0.8 s, and the worker's answer from the slow model was read out 143 s later (3 calls). (d) Not yet: the tools prompt is a constant in `voice/route.py`, not a card the author and judge (S-151) can improve; streaming the talk text; more quick tools for the fast layer (the owner's terminal-navigation idea) behind the same gates. | adopted | +| S-171 | **The fast layer does simple things itself: quick tools in the voice head, streamed speech, SearXNG for search** (2026-11-22; builds on S-170; the owner: reminders, search and fact lookups should not need delegating, and the fast model should not get tied up in multi-step work). (a) **Quick tools**, run in the voice head (`voice/tools.py`), never through the worker (it takes one task at a time, so a reminder would wait behind a long job): `save_note` and `read_notes` (the worker's `notes/`, shared: the voice head joins the worker's group 65534 and the worker makes `notes/` group-writable with setgid at start; running the voice head as `nobody` would break its first-start model fetch), `remind(text, when)` (a `voice.reminder` signal, ISO local time or "in N minutes"; said when due to an open page, then `voice.reminder.said`), `calculate` (arithmetic only, by the AST), `lookup` (Wikipedia's REST search and summary, a generic User-Agent), `search` (the local SearXNG's JSON API, the top four results). At most 3 quick steps a turn, then only talk and delegate are offered; talk and delegate end the turn. The current local time is in the prompt (`TZ`, here America/Los_Angeles). (b) **Streaming:** each step streams; a talk call's `text` is read out of the arguments as they arrive (`route.TalkText`, escapes split across chunks included) and spoken sentence by sentence; markdown, list marks, emoji and zero-width characters are stripped before speech. (c) **SearXNG** (the owner chose it with Wikipedia, 2026-11-22: AGPL-3.0, fetched at setup, unmodified in its own container, reached over HTTP, as S-146 treats a GPL part): compose service `search` (profile `voice`), `docker.io/searxng/searxng:2026.11.8-74418092d` (the newest at least two weeks old; its entrypoint, settings path and `SEARXNG_SECRET` read from the image), no host port, `deploy/searxng/settings.yml` (JSON API on, no limiter or image proxy, engines 5 s). It forwards queries to public engines, and the voice head's lookups go to Wikipedia: spoken questions now leave the machine for these two tools (the owner's choice). podman 4.9.3's network DNS does not answer AAAA for a name with no IPv6 address, which stalled every lookup 5 s and lost all engines at 3 s: `dns_opt` timeout 1, one attempt; now about 40 results in 0.4 to 2.6 s (DuckDuckGo and Wikidata still unanswered). (d) **Measured:** held-out 11/12 twice ("Name three planets" searched first), five "can't" cases 5/5 twice (scored by the first tool, `scripts/trials/voice-route/trial.py`). Spoken end to end: a reminder "in one minute" set at 1.0 s and said 28 to 30 s after the turns ended; arithmetic, a Wikipedia fact, a news search, reading notes back and writing a summary note (read_notes then save_note) at 0.8 to 3.6 s to first audio. (e) **Found and fixed on the way:** tool results written into the history as text were copied into later replies ("(calculate: ...)") and misremembered: the history now holds only what was said; with more tools it saved a fact unasked and asked "which computer?" for disk space: the prompt now says save only when asked and that anything about the computer is delegated (it is the one it runs on); the worker returned ok with an empty answer (the slow model spent its tokens thinking) and the condenser invented one: an empty answer is now a failure with its reason, and the voice head says the task gave no answer. (f) Not yet: the worker has no tool that can read disk space or run a command, so such delegations cannot succeed until it gets a shell tool behind a gate; the tools prompt is still not a card for the author and judge (S-151). | adopted | +| S-172 | **Agent harnesses surveyed; the trial parked by the owner's direction (S-173)** (2026-11-22; research skill; the kernel's MCP tools were not loaded in this session, so the evidence is in `scripts/trials/harness/` and this row, to be written as claims from a session that has them). **Catalogs:** GitHub search and REST API (licences, releases), the best-of-Agent-Harnesses list (RyanAlberts, CC-BY-SA-4.0, `harnesses.json`, 186 projects; terminaltrove.com and tbench.ai as further sources), each candidate's docs (read by four Haiku subagents). **The entity list** `scripts/trials/harness/candidates.json`: 97 entries in the catalog skill's shape (catalog ids, described-at-url, licence, provides-interface with evidence), 84 listed from best-of's agent categories, 13 checked. **Shortlisted:** OpenCode (MIT; `opencode run --format json`, provider `headers`, stdio MCP, ordered allow/deny/ask rules, official image; pin v2.2.6, 2026-11-06), Codex CLI (Apache-2.0; `codex exec --json`, `http_headers`, Responses API only, read-only sandbox by default, analytics on by default), Goose (Apache-2.0; telemetry off by default, permission modes loosely documented; pin v1.57.0), Qwen Code (Apache-2.0; real allow/ask/deny rules and a sandbox, usage statistics on by default), RuleGo v1.0.0 and its AI components (Apache-2.0; rule chains, a ReAct node, MCP client and server, pre-LLM and pre-tool-call aspects). **Ruled out:** Crush (FSL-1.1-MIT), Aider (last release 2025-08-09, no MCP), mini-swe-agent (no MCP, no tool calling), Cline (auto-approve by default, no shell allow/deny list), OpenHands (headless CLI unmaintained), pi (no permission system), rulego-server (a modified Apache-2.0 with extra conditions); Claude Code has no open licence (it stays the companion, S-136). **Found:** the gateway serves Chat Completions, the Responses API and the Anthropic Messages API to the local models with a Bearer key, so any of these could reach Inkling or the 1.7B. Kept: the need (`README.md`), the isolated network (`net.sh`: internal, the gateway and a recording proxy only), a standard-library stub MCP server. | adopted | +| S-173 | **Our own light runtime on Postgres, MCP as every component's interface, one agent loop of ours, other harnesses as agent instances** (2026-11-22; the owner's direction; supersedes S-162's narrower own-loop pick by widening it, and parks S-172's trial; `docs/plan.md` "The runtime, components and agents"). Postgres is the backbone (pgmq queues, the `env` gates and record, the kernel as catalog). A block is an MCP tool and a registered MCP server's tools are components, both ways, behind the environment's gates. Blocks run on demand by default (measured 2026-11-22 in the tools container: a Python block per call with JSON in and out 18.8 ms median, a bare `python3 -I` 10.2 ms, a process spawn 0.6 ms, about 8 MB idle), with a `hot` toggle for a supervised persistent process. A process supervisor runs processes in one small container; **Nomad is out by default: its LICENSE is the Business Source License** (read 2026-11-22), so process-compose (Apache-2.0, Go, v1.124.0 of 2026-10-26) is the lead candidate, to be picked with the research skill against s6, supervisord and systemd units. One agent loop (the worker's, generalised) with M-17's gate at the model endpoint; Claude Code and other harnesses join as agent instances (tasks from a queue, tools from the MCP endpoint, models through the gateway, `task.done` back). | decided | +| S-174 | **Describe, check, decode: Substrate builds no runtime and does not mediate links; runtimes are pluggable, Compose first; the kernel as a symbolic latent space** (2026-11-22; the owner's direction; supersedes S-173's runtime engine, its bindings and its blocks MCP server as a requirement; `docs/plan.md` "Describe, check, decode"). Components talk to each other directly in the protocols they already speak; their interfaces are described in a WoT Thing Description's shape (affordance, schema, forms with protocol and address); two parts fit when one provides what the other requires, and otherwise a translator from the catalog goes between them. Substrate decodes the map into existing runtimes' native formats and encodes their state back (the kernel's D-41: automations stay in their runners' formats; D-36: chain runners parked). **The kernel's boundary is already decided there:** queues belong to a distribution in its own database (the kernel's D-94 c), signals and telemetry are observations, not claims (D-101), and the catalog entry becomes D-101's first content type, the proof that proposed framing waits on. **The kernel as a symbolic latent space** (the owner's words): one universal symbolic representation that systems are interpreted into and out of. **Compatibility list** (`docs/compatibility/README.md` and `runtimes.json`, read 2026-11-22 from each project's docs and GitHub by three Haiku subagents): 10 service and process runtimes, 15 workflow orchestrators, 7 cloud services, 13 interchange standards, each with its native format, API and licence; a licence decides only whether a part can be a default (open: Compose, Podman, process-compose, systemd, Kubernetes, Flowable, Kestra, Argo, Conductor, Node-RED, Airflow, Prefect, Dagster, Temporal, Hatchet), the rest are targets (Nomad and Restate BUSL-1.1, Inngest SSPL, n8n Sustainable Use, Camunda License, Windmill AGPL plus proprietary EE, cloud services). **Found:** P-Plan, whose terms blocks' plans use (S-164) and the kernel's chain model maps to, is CC BY-NC-SA 2.0, a non-commercial licence: the owner to decide how they refer to it. Next: the catalog entry content type with a compatibility check, then the Compose decoder and encoder tested on Substrate's own `deploy/compose.yaml`. | decided | +| S-175 | **Vocabularies: standards first and a thin profile of our own, no custom ontology; plans in PROV-O, not P-Plan** (2026-11-22; the owner: "alternative ontologies are fine ... it's your call"; the kernel's D-124, which closes its O-13). P-Plan's licence is CC BY-NC-SA 2.0 (non-commercial, found by S-174). A full custom ontology was weighed and set aside: owning every modelling decision would fight the kernel as a symbolic latent space (S-174, the kernel's D-122), which carries formats in and out best when its middle speaks the vocabularies they map to. So the kernel's D-40 stands (standard vocabularies first), with a thin profile of our own terms only where none fits, each mapped (SKOS). Blocks' plans keep their JSON shape; in the kernel a plan is `prov:Plan` and a run a `prov:Activity` with `prov:hadPlan`, with the profile's terms for steps, order and variables (mapped to BBO/BPMN where they overlap). `blocks/__init__.py` and `blocks/executor.yaml` no longer call the format P-Plan. P-Plan's IRIs already in kernel v0 stay until the owner schedules that migration. Also done this day, with the owner's go-ahead: the kernel's branches cleaned (27 deleted: 24 merged or squash-merged, and three early `*_iteration` branches first kept as `archive/*` tags). | decided | +| S-176 | **The catalog entry: Substrate's parts as Backstage entity files, read into the kernel by encoder-backstage; a fit check over files, compose and the kernel** (2026-11-22; plan step 1 of S-174; the kernel's D-101 first content type, D-123). **Format chosen, not invented:** Backstage's entity format (`backstage.io/v1alpha1`), which the kernel already reads (`encoder-backstage`, the kernel's D-100) and `map-drift` already compares with observed calls; one file per entity in `catalog/` (47: 22 components including jobs, agents, blocks, a plan and two external services, 22 APIs, the database, the system, the owner), so each file is one item's version. Interfaces are `API` entities, `spec.type` the protocol (`openapi`, `asyncapi` for pgmq queues, `mcp`, `websocket`, `http`, `wot-td`), `spec.definition` the contract (a block's is a WoT Thing Description action from its `block.yaml`); licence, image, compose service and decision as `substrate.dev/*` annotations. A queue is provided by the component that receives on it (AsyncAPI's sense). **`scripts/catalog.py`:** `check` (every consumed API has a provider, every reference resolves, compose matched both ways), `apis`, and `check --kernel` (the same fit from the kernel's usable claims under the read model's role, `kkm_view_substrate`, and drift between files and kernel). **Into the kernel:** compose job `kernel-catalog` (profile kernel-admin; `scripts/kernel.sh catalog`), the volume `kernel-artifacts` as the artifact store. **Seen:** 47 change sets applied; every claim cites its file and line (each file an artifact, `application/yaml`); 45 provides and consumes links, no gap, no drift; a second run submitted only the one new file. **Found on the way:** the first entries modelled the worker's queue backwards and missed two compose jobs, both caught by the check; my own `kernel-catalog` job was flagged until it had an entry. `scripts/check.sh` now runs the check; `scripts/tests/test_catalog.py` (9 checks). **For the kernel, follow-ups:** `encoder-backstage` reports every cross-file reference as `dangling-ref` (it resolves within one file, though the claims point at the right IRIs), and writes no current-version link from an item to its artifact (D-101's `kkt:hasArtifact`, or a standard term, `docs/content.md`'s open question); D-101's per-type items view is not built yet. | adopted | +| S-177 | **Compose into the kernel and back: the kernel's `encoder-compose` and `decoder-compose`** (2026-11-22; plan step 2 of S-174; the kernel's D-125, PR OpenReplicant/kernel#134, stacked on #133). Built as kernel modules, not in Substrate, because the kernel's architecture puts encoders and decoders in modules and Compose is any distribution's concern; they generalise the self-encoder's `encode_compose` (which reads only the kernel's own files). A compose file becomes a service template whose version is the file (D-101) and node templates `urn:kk:node:` with node type, image, profiles, ports, volumes, environment variable names (never values) and dependencies, each claim citing its lines; the decoder renders the file from that version and the current claims, so a changed claim changes the file. **Seen in this stack's kernel:** `deploy/compose.yaml`'s 17 services became 242 claims and decoded back equal as compose reads it; the catalog's components and compose's services meet on the same nodes (the voice head: 20 claims from the catalog, 28 from compose). **Found and fixed:** the catalog called the database `postgres` and compose `db`, so their nodes did not meet: the entry is now `resource:db`; the old file's claims stayed current until the kernel encoders gained `--prune` (retract what removed or renamed files said); a run from another working directory re-keyed every file (456 claims retracted and re-added, nothing lost), so the `kernel-catalog` job now passes `--root /`. **Not yet:** a `scripts/kernel.sh compose` job (it waits for a published kernel image with the modules), running state encoded back (`compose ps` as observations), and the decoder writing the stack's compose file in use. | adopted | +| S-178 | **M-17's gate at the model endpoint: a proxy in front of the gateway, asking decision questions; tabular in-context learning over embeddings as the first online learning** (2026-11-22; the owner: "the proxy for sure, and that makes it more universal so we're not just tied to bifrost"; "the tabular system is a first implementation of online learning at this point in the architecture (there are alternative ways to do this but i like how we're learning with embeddings)"; plan step 3). (a) **A proxy, not a Bifrost plugin:** it speaks OpenAI chat completions and Anthropic Messages (so Claude Code's calls pass it too), streaming included, and forwards what it does not answer to the gateway, which still records every model call (S-77). (b) **Every model call is a decision point**, not only a task's first message (Soar compiles decisions, not whole tasks): a skill may answer with final text or with a tool call. (c) **The gate's interface is the System One contract** (TypeSafe's Jev, 2026-09-15, and its open replications, `github.com/andyrewlee/awesome-system-one`, read 2026-11-22): a state and typed questions (yes/no, choice, score) in, a calibrated probability per option out; the gate skips the model only above a threshold and otherwise falls through. **Implementations are pluggable, to be picked and measured with the research skill:** (1) next-token probabilities read from the fast model already running (LFM3 1.7B), the free baseline; (2) a small open decision model (candidates as reported, unverified: decider 0.8B and dohnuts 0.8B, Apache-2.0; NanoJev 0.6B, MIT; Laya 421M, Apache-2.0; d1, licence unstated); (3) **embeddings (text, audio, image or feature detectors such as Silero's VAD or M-18's encoder) with a calibrated tabular in-context head** (TabICLv2, BSD-3-Clause code; weights' terms to check; TabPFN 2.5+ and Google TabFM weights are non-commercial, so not defaults), whose context is the gate's own log of labelled routes: online learning with no training step, and the way to non-text senses. S-170's embedding vote (12/12, 65 ms) is the baseline to beat. (d) **Every routed call is logged** with its features, the route taken and, once scored, whether it succeeded: the rows the tabular head learns from, the experiment's counts and what a compiler reads. Calls to the fast and slow models are counted apart. **A row's label is the outcome, never the decider's own choice** (else the head learns to copy the model, and a confident skip is confirmed by its own rows): the task's success, the scorer's verdict, and the owner's corrections as the strongest rows; a small sample of calls is still sent to the model when the head is confident (a shadow check, to see drift). **Feedback is long-horizon:** each decision keeps a stable id, and an outcome that arrives later (the owner corrects it an hour on, a reminder is never acknowledged, a task is redone, a note is found wrong) attaches to that id as a signal, so a row's label can change long after the call. The log keeps the raw request and its outcome, not only features, so features can be recomputed when the embedder or the PCA changes. The log holds the owner's words verbatim: it needs a retention rule and a line in docs/privacy.md before real use. (e) **Dogfooding:** the owner will use the assistant (voice head, fast and slow models, worker, gate) as their own personal assistant with real tools and tasks; real use supplies the recurring task families and the labels for M-17's first experiment, beside the scripted harness. Which real tools come first is the owner's (privacy, docs/privacy.md). | decided | +| S-179 | **The gate's decider: TabICL over embeddings, with the fast model's probabilities as the cold start and the tie-break; vela3-fast kept as the catalog's alternative** (2026-11-22; research skill on S-178's three slots; the kernel's MCP tools are not loaded in this session, so the evidence is the trial and this row, to be written as claims from a session that has them). **Trial:** `scripts/trials/decider/` (`run.sh`; output `.state/trials/decider/summary.txt`): 96 utterances over the voice head's eight routes (talk, lookup, calculate, save_note, read_notes, remind, search, delegate; `cases.json`, **a dev set written by Claude, not held out from the author**); stage 1 in the voice head's container through the gateway, stage 2 in a trial image (python 3.13.17-slim-bookworm, torch 2.15.0 CPU, transformers 5.17.0, gliner2 2.1.0, tabicl 2.2.0, scikit-learn 1.9.1, all on PyPI before 2026-11-08), all on this machine's CPU. **Results** (accuracy, top-label ECE, Brier, median per decision): `fast` (LFM3 1.7B, eight described options, one letter, thinking off, the answer prefilled, probabilities from `top_logprobs`) 93/96, 0.058, 0.062, 296 ms; `vote` (S-170's, qwen3-embedding 0.6b, k=3, leave one out) 84/96, 0.049, 0.167, 52 ms; **`tabicl` (TabICLv2 checkpoint `tabicl-classifier-v2-20260212`, HF `jingang/TabICL` at 4dcd344, BSD-3-Clause; the embedding cut to 32 by PCA; 4-fold, the other folds as context) 90/96, 0.027 (the best), 0.104, 74 ms with the embedding (TabICL's share measured batched over a fold; one call alone not yet measured)**; `tabicl+fast` (the fast model's eight probabilities as columns) 94/96, 0.035, 0.048, 373 ms; `vela` (vllm-sr/vela3-fast at fa60e3a, Apache-2.0, 2026-10-31, zero shot, the System One request as is, network off) 85/96, 0.081, 0.157, 179 ms, 3.7 GB RSS; `gliner` (fastino/GLiNER2.5-Decide at 9d1bfb8, Apache-2.0, zero shot with label descriptions) 65/96, 0.323, 0.646, 288 ms, 4.3 GB, nearly every talk case called lookup, and its API gave only the top label's confidence (the description form may be misused; not pursued). **Online learning, TabICL's curve** (examples per route in its context, 5 draws): 1: 0.675, 2: 0.838, 4: 0.884, 8: 0.912. **Checked:** Bifrost v2.3.2 passes `logprobs`/`top_logprobs` through to llama.cpp b12627 and back; `reasoning_effort: none` plus an assistant prefill `Answer:` gives the letter as the first token (40-90 ms for three options). **Pick:** the gate asks TabICL over the embedding first (cheap, best calibrated, learns from each logged and scored route with no training); below its threshold, or for a route with too few examples, it adds the fast model's probabilities (a new route needs only its description); above the threshold it skips. **Why not the others:** vela3-fast is the best zero-shot small model here but needs 3.7 GB beside what runs and loses to the fast model already loaded; GLiNER as measured; the embedding vote is beaten on accuracy and Brier; Julia-1 (144M, Apache-2.0) was modified 2026-11-09 (under two weeks) and not tried; d1 is "other" licence (Liquid's; the owner's call, like LFM3). **Searched:** `github.com/andyrewlee/awesome-system-one` (read 2026-11-22), Hugging Face's model API for licence, dates and size, PyPI for packages. **Not yet:** mid-task calls (after a tool result: answer or which tool next), the S-170 held-out set, one decision's latency alone, the GPU, and held-out cases written by the owner from real use (dogfooding, S-178 e). **Likely optimistic (said to the owner):** the cases and the route descriptions were written together by the same author, so the descriptions fit the cases' wording (most help to `fast` and `vela`); the cases are clean, balanced and single-intent; the 4-fold split leaves near-twin templates on both sides (TabICL's score and curve flattered); 96 cases give overlapping 95% ranges for the top three (about 0.91-0.99, 0.87-0.97, 0.93-0.99). Each decider was run once with its first prompt (no selection over variants); GLiNER's likely misuse was not fixed. **Next:** freeze the deciders, then a blind set (the owner's own requests, and one written by another model from the route names alone, unread before the run), realistic route mix, Parakeet-transcribed speech, context-dependent and mid-task cases, a split by template, intervals reported. **To check before relying on it:** TabICLv2's limit on the number of classes; a cap on its context (recent plus balanced per route, or nearest by embedding); the fast model's letter-order bias (shuffle and average). | trial, pending a blind run | +| S-180 | **The gate follows Soar: skills propose, the decider selects, impasses are typed, and choosing and compiling are two learning paths** (2026-11-22; the owner asked whether the design is close enough to Soar's chunking and whether it is a good System 1; builds on S-178, S-179). (a) **Mapping:** Soar's rules that propose operators are skills' **conditions** (when a skill applies), kept beside their triggers; selection by preferences tuned by Soar-RL is **the decider** (TabICL over outcome-labelled rows, S-179), which chooses among the proposed skills and the model rungs; the impasse is the decider abstaining; the substate is the model call (System 2); **chunking is the skill compiler**, not built yet. (b) **Impasse types are logged** from the decider's output at no cost: `none` (no skill proposed), `tie` (the top two close), `low` (one ahead but under the threshold); each is a different signal to the compiler and to M-17's measures. (c) **Two learning paths, kept apart:** choosing (statistical, online, in Substrate's gate) and compiling (a solved trace becomes a skill whose conditions are what the answer depended on, as chunking backtraces, so it generalises on what mattered rather than on wording and works after one case; the worker's `cited` ids are the start of that trace; in the M-17 experiment). The log keeps each answer's dependencies (the tool results and inputs it used) for the compiler. (d) **Evaluation is prequential:** each row is predicted before its label is seen, in arrival order, then added to the context; this is the test that matches online use and shows drift; intervals, not single scores. (e) **Exploration is Thompson sampling** over each skill's success rate (a Beta draw per decision): new or doubtful skills are checked by the model more often, proven ones rarely; this is the shadow check of S-178 (d) made principled. (f) **AutoML later, not now:** with about a hundred self-written rows a search over models finds what fits the author's wording; once real use has given a few thousand rows, candidates (AutoGluon's zoo, which includes TabPFN, TabICL, Mitra, boosted trees and kNN; Optuna for thresholds) compete prequentially, each picked with the research skill (licences unchecked). (g) **Not System 1 yet in full:** the gate chooses; acting without the model also needs filling a skill's arguments (span-marking decision models such as vela3 are candidates for that, S-179) and the compiler. | decided | +| S-181 | **One assistant: the capability levels are model rungs in one loop, not separate agents; MetaSoar's experiments fold into Substrate; plain role names** (2026-11-22; the owner: "too many named projects going ... and i also don't know why our voice agent has two aux agents other than 2 higher levels of capability it can defer to"; "go ahead and revise the docs"). (a) **Why there were two:** history, not design: the companion (S-136, Claude Code on the owner's login) came first and the voice head handed work to it; the worker (S-163, our loop on the self-hosted slow model) came later; S-170 moved the voice head's work to the worker and left the companion behind the worker's `ask_companion` (propose). (b) **Now:** behind the voice front end is **one assistant**: the worker's loop (S-173's one agent loop), whose model calls the gate routes by rung: a compiled skill (no model), `fast`, `slow`, and `cloud` (Claude through the gateway's pass-through route on the owner's login), the last always behind `propose` because it sends the owner's words off the machine (docs/privacy.md P3). One loop, one log, one page. The voice front end stays its own part (talking needs a fast turn-taker) and keeps its quick tools (S-171). **The companion as a separate agent retires once the cloud rung works;** a Claude Code session remains an agent instance like any other harness (S-173), for what it is uniquely good at, such as coding in a repository. Its budget and meter (S-144) carry over to the cloud rung. (c) **Projects:** two products: **the Kernel** (the store; its own database and other users) and **Substrate** (everything that runs). **MetaSoar's experiments move into Substrate** (`experiments/`, beginning with M-17's), as envkit did (S-161); MetaSoar keeps the hypothesis and its write-up, and its repository is changed there, by its own commits. **Morphogen** stays out of the build (rule 9). **No "personal distribution" name:** the assistant is what the owner runs. (d) **Names inside Substrate are roles:** the assistant, the voice front end, the gate, the judge, the kernel; model aliases by role (`fast`, `slow`, `cloud`), never by model, as S-169 began. "Companion" and "worker" stay as the code's names until the merge, then go. (e) **Build order** (`docs/plan.md` step 3): the decision log; the proxy (OpenAI format first, passing through and logging); the deciders behind a threshold with impasse types and Thompson sampling (S-180); the voice front end and the assistant through it; the cloud rung and the Anthropic format, retiring the companion; the frozen blind run (S-179). (f) **The owner's to decide:** the gate's log keeps the owner's requests verbatim (S-178 d), which docs/privacy.md P6 (no prompts kept by default) forbids for a personal stream unless the owner turns transcripts on for it; the alternative is keeping only features (the embedding and the outcome), which loses recomputing features when the embedder changes. Recommended: turn transcripts on for the gate's log only, with P7's retention set. | decided | +| S-182 | **Experience, not a decision log; the owner's privacy terms for it; the assistant's first real tools** (2026-11-22; the owner: "is it really 'decision logs'? i think of my own system 1 as distilling responses to scenarios"; "ok to keep, there can be privacy settings including encryption and deletion"; "real tools should be files and search and kernel/substrate, along with an MCP for searching/installing MCPs from a trusted website"). Supersedes the name "decision log" in S-178 (d), S-180 and S-181 (e) and the P6 question of S-181 (f). (a) **Experience:** what the gate stores is the assistant's experience, one **episode** per model call: the **scenario** (the request, its context and features), the **response** (who answered: a skill, a rung, and what it said or did, with what it depended on), the **outcome** (labels that arrive later by the episode's id). Table `env.experience` (Soar's episodic memory). **System 1 is distilled from experience** in two forms: **skills** (a compiled response with conditions, chunking, one case enough) and **preferences** (which response fits which scenario, TabICL over episodes, Soar-RL's role). The gate is System 1 answering: it recalls a distilled response for the scenario, or hands the call to System 2 (the model) when none fits. (b) **Privacy (a loosening of docs/privacy.md P6 for this store only, on the owner's word):** episodes keep the owner's requests verbatim, with: encryption at rest of the text (key from `.env` through the `sec_*` verbs; pgcrypto or the volume, to be picked), deletion of one episode, a time range or all (P9; the embedding and every derived row go with it, since embeddings can be partly inverted to text), and a retention period the owner sets (P7). (c) **The assistant's first real tools:** **files** (the workspace now; folders the owner names, P1, read-only unless named writable); **search** (the SearXNG and Wikipedia tools the voice front end already has, S-171); **the kernel** (the `memory` profile it has, and the `substrate` profile's search and read); **Substrate itself** (status, the environment's waiting proposals and gates, logs and the catalog, read-only first; changes through `propose`); and **an MCP that finds and installs MCP servers from one trusted registry**: finding is free; **installing waits for the owner** (`propose`), pins the exact version, checks the licence (rule 7), runs the server in its own container (rule 6), and writes it into the catalog as a component (S-176) before the assistant may call it. Which registry (the official MCP Registry is the lead candidate) is picked with the research skill. | decided | +| S-183 | **Experience built: `env.experience` and `env.outcome`, the text encrypted with pgcrypto under a key the database never stores** (2026-11-22; plan step 3 (a); S-182). **Built:** `environment/sql/008_experience.sql` (creates pgcrypto 1.3 and pgvector 0.8.7 where missing; both ship in our Postgres image) and `environment/experience.py` (`Experience`: record, outcome, episodes, and the owner's text, forget, expire). An episode: `ref` (a uuid outcomes and callers refer to), caller, login, the request and response as `pgp_sym_encrypt` bytea, features, embedder and embedding (`vector`, no fixed size, so the embedder can change), responder (`skill:`, `fast`, `slow`, `cloud`, or `model:`), what it depended on, the decider's output, the impasse (`none`, `tie`, `low`, or null). Outcomes: `ok` (boolean), `correct` (a responder), `score` (0..1), each with its source and an encrypted note; many per episode, the latest of each kind is the label. **Kept whole:** a trigger refuses any change or delete except inside the owner's forget; outcomes cascade with their episode. **Who:** new role `env_gate` (record, add outcomes, the decider's context `env.episodes(...)` with no text); `env_agent` may add outcomes only; reading the text (`env.episode_text`), forgetting (`env.forget_experience`: one, a time range, all; a vague call is refused) and expiring (`env.expire_experience`, from the setting `experience.retention_days`, none set means keep) are granted to no login. **Encryption choice:** pgcrypto rather than an encrypted volume or client-side encryption: no new package, the key is passed as a bound parameter, and Postgres here logs no statements (`log_statement=none`) and no parameters on error (`log_parameter_max_length_on_error=0`, read 2026-11-22); the embeddings are not encrypted (the decider reads them in the database), so deleting removes them with the text. **Key:** `EXPERIENCE_KEY` (`deploy/secrets.txt`, token:32, made by `scripts/settings.sh`; losing it loses the stored text). **Retention** is not scheduled yet: pg_cron is not installed in database `substrate`; the gate calls `expire` (S-183 leaves that to the gate's build). **Tested:** `scripts/tests/test_experience.py`, 29 checks (encryption, a wrong key, the gate unable to read text, select, change or forget, the assistant only adding outcomes, labels by latest, constraints, forgetting one, a range and all, expiry by the setting); all eleven suites pass; migrated on this machine's database. | adopted | +| S-184 | **OpenEnv is adopted fully, not wrapped: Substrate's environments are OpenEnv environments, in production and simulation** (2026-11-23; the owner: "let's not overlook openenv, that might save us from recreating its features"; "solidify whether we want to actually try to integrate fully with open env or if we're going to be re-implementing its features just to wrap it which seems unnecessary"; read `huggingface.co/docs/openenv` guides simulation-vs-production, reference core, tutorials mcp-environment and claude-code-harness, 2026-11-23). **What OpenEnv gives and we use as it is:** the environment classes (`Environment`, `MCPEnvironment`), the server (`create_app`, `mode="production"` or simulation), the clients (`EnvClient`, `MCPToolClient`), simulation episodes (`reset`, `step`, `state`, rewards, `done`) and rubrics (`Rubric`, `Gate`, `WeightedSum`, `LLMJudge`), production mode (the same class serving its MCP tools at `/mcp`, no episodes), the harness adapter (RFC 005 `HarnessEnvironment`: Claude Code headless, its own tools off, only the environment's MCP tools; `ANTHROPIC_BASE_URL` redirects its model calls), Docker packaging and Hugging Face distribution (`from_docker_image`, `from_env(repo_id)`), and Harbor's training traces later. **What it lacks, built inside our environments rather than around them:** persistence (state in Postgres, so many sessions share one live environment), auth (the database's logins; the server itself has none and its docs say keep it on localhost or behind your own auth), approval gates (a `propose` tool returns "waiting for approval", or MCP's `input_required` if the 2026-07-28 revision is final: to check), events to subscribers, and recording model calls. Simulation `reset` clones a template database. **Package (PyPI, read 2026-11-23):** `openenv`, BSD-3-Clause, Python 3.10 or newer, dependencies fastapi, pydantic, uvicorn, huggingface_hub, openai, websockets and a few small ones; 0.2.0 on 2026-06-02, weekly since, 0.14.0 on 2026-11-19; **pin 0.12.0 (2026-11-05)**, the newest at least two weeks old; expect breaking changes and keep our code against it thin. Not `openenv-core` (an older separate package, 0.3.0 of 2026-05-11). RFC 003 (MCP as the action boundary) and RFC 005 (harnesses) are still in review; the docs disagree on which routes production mode serves. **The spike before building on it:** (1) many agents' sessions share one Postgres-backed live environment; (2) events reach a subscriber in production mode; (3) `reset` clones a template database fast enough; (4) Claude Code runs through the harness adapter; (5) it runs against our model proxy through `ANTHROPIC_BASE_URL`, with an episode id carried in a header; (6) a skill's answer reaches Claude Code in a form its loop accepts (final text or a well-formed tool-use block); (7) a rubric's score attaches afterwards to every model call of its episode. **MetaSoar** moves its worlds (envkit's Mario, ARC-AGI-3, the stream) and M-17's experiment onto OpenEnv; envkit retires into that. | decided; spike pending | +| S-185 | **Substrate's shape: a top-level orchestrator that maps, orchestrates and optimises a working system, on a Postgres kernel; every dependency is a contract, our projects are default fillers** (2026-11-23; the owner: "a top-down hierarchy where the top-level is observing a working system and keeping it working by adjusting and orchestrating, everything is handled by sub-agents potentially within shared environments"; "the orchestrator being a regular LLM harness with skills and MCP servers and hooks"; "like it's the GNU operating system running on top of a Linux kernel but postgres has been turned into our kernel"; "the core of substrate would be to map and orchestrate and optimize"; "help me figure out where we draw the lines"). **The layers:** the **Kernel** (Postgres made into a kernel: knowledge with provenance, objects with properties, gated actions and events, logins, the record; data transformations and what happens at the Postgres level); **Substrate** (the orchestrator kit: the skills `map`, `catalog`, `research`, `orchestrate`, `optimize`, plus `setup` and `upstream`; MCP servers; hooks that enforce gates inside the harness; observing by subscription; the adapters (OpenEnv, the model proxy, compose decoding); the reference stack; and the document of how it fits; only a little agent framing, no LLM or harness methodology); **Morphogen** (the optimiser, a sub-agent pluggable into anyone's system: cells, optimizers behind a judge the optimizer cannot edit, the still-works gate, the system guard, the evidence log); **distributions** (what is built with it: kinds of environments, multi-stage agents, the assistant, the SMB Foundry or AI ERP; **folders in this repository, `distributions/`, until Substrate's shape is settled**); **MetaSoar** (the research on cognitive architecture). **Dependencies are contracts only, no cycles:** the Kernel needs only Postgres; Morphogen needs cell files and reads Backstage entities when present; Substrate needs OpenEnv and MCP (environments and delegation), Backstage entity files (the map), Morphogen's cell contract (the optimiser), and an OpenAI- or Anthropic-compatible model endpoint; distributions need Substrate and the fillers they choose. The test that the lines are clean: Substrate pointed at a folder of catalog files and one OpenEnv environment still runs. **Slots and default fillers:** environment and delegation: OpenEnv + MCP, with A2A v1.0's task states for a delegated task's lifecycle; three kinds of filler: an OpenEnv environment (rehearsal, scoring, packaging), a harness sub-agent (Claude Code's own sub-agents for quick work inside the orchestrator's session; a separate harness process, with its own Kernel login, context and record, for long or risky work), and custom (any MCP server: a service, a script, a non-LLM agent, the Kernel's Postgres environment); the map: Backstage entity files, read and written over MCP, the Kernel by default; the optimiser: Morphogen; the harness: Claude Code; models: Bifrost. **Autopoiesis:** Substrate's own stack is an environment like any other (its compose file into the map and back, S-177), so the orchestrator maintains and grows its own system with the same skills, imposing no functionality downstream. **Morphogen as the optimiser (rule 9 was misread: it was taken out of the build only to iterate on it quickly):** GitHub's main (rebuild 7, 2026-11-21) is already a Claude Code plugin (`.claude-plugin/plugin.json` v0.8.0, Apache-2.0) with an MCP server (`status`, `structure_check`, `structure_scope`, `structure_render`, `measure`, `probe`, `judge`, `judge_change`, `tune`, `optimizers_list`, `evidence_query`), the skills `morphogen` and `map`, the agents `worker` and `reviewer`, an optimizer catalog (grid, random, hill-climb, annealing, Optuna, GEPA, a bandit `selector`) with an entry-point group `morphogen.optimizers`, and reads Backstage; so it slots in by installing the plugin in the orchestrator's harness. The orchestrator's `optimize` skill decides which cell and when and promotes a winner through a propose gate; Morphogen proposes and judges; the judge stays separate from the proposer (S-166). **Small changes still needed:** one map skill (Substrate's `map` writes Backstage entities; Morphogen only adds cells from them); Substrate's configuration kept as files (the compose decoder, S-177) so Morphogen's git-based cells cover running components and a winner deploys through the decoder; a cell's `run` may run OpenEnv episodes (no change); an agent optimizer that writes code (Morphogen's planned `llm` member); optionally a reference to each verdict in the Kernel. Morphogen stays its own repository because the judge's independence from what the optimizer edits is the point; its code changes there by pull request (the upstream skill). The checkout at `~/Projects/Morphogen` is rebuild 5 (2026-10-26) and must be updated before use. **One database:** the Kernel's database holds the `env` schema too (objects' live state, queues, gates, the record) beside the knowledge schemas; this needs the kernel's D-94(c) ("Distributions such as Substrate create their queues in a database of their own") superseded by a kernel decision. **Supersedes** S-181 (c) (MetaSoar's experiments do not move into Substrate; MetaSoar stays its own repository and runs them on OpenEnv) and S-181's role names where they named cognitive parts as Substrate's. | decided | +| S-186 | **The multi-response ladder (S-178 to S-183) is a distribution component, built on OpenEnv** (2026-11-23; the owner: "Using open env, how would we build that multi response ladder system"; earlier "some of these concepts are implementing cognitive architecture which would be better to put in MetaSoar or some kind of distribution keeping substrate simple"). **Where:** the ladder (the proxy at the model endpoint, its deciders, `env.experience` of S-183) and its task-family environments go in a distribution folder (`distributions/assistant/`); the skill compiler and M-17's experiment are MetaSoar's, using them; Substrate gains nothing new for it beyond OpenEnv and the Morphogen plugin. **How:** an OpenEnv environment provides a recurring task family (`reset(seed)` picks a task on a fresh copy of the data); its harness adapter runs Claude Code with `ANTHROPIC_BASE_URL` set to the ladder, so every model call in the episode passes the ladder (the Anthropic format comes first now, not last); the episode's id travels in a header and the rubric's score becomes an outcome on every call of that episode (labelled experience with no person in the loop); TabICL reads those rows at once, the fast model's probabilities cover routes with few rows, Thompson sampling sets how often a confident route is still checked; the compiler proposes a skill from traces, Morphogen judges it as a cell (`change` the skill's files, `run` the environment's episodes, `better` fewer model calls, `tests` the rubric's pass rate), and a winner becomes rung 0 on the owner's approval. Production uses the same ladder with outcomes from tasks and the owner's corrections. M-17's three conditions are three settings of the ladder over rounds in the same environment. **S-178 to S-183 stand as the ladder's design** (proxy, System One questions, TabICL with the fast model's probabilities, outcome labels and long-horizon feedback, typed impasses, prequential measures, experience encrypted with deletion and retention); where they placed it in Substrate, this supersedes them. The code built (`environment/sql/008_experience.sql`, `environment/experience.py`, `scripts/trials/decider/`) moves to the distribution folder with the rest of the assistant (plan step 3). | decided | +| S-187 | **After the shape settles: everything runs on top of it, a bootstrap instance with self-knowledge, a second pass over the docs; the motto** (2026-11-23; the owner: "when we settle the shape of substrate we're going to need to make sure the experiments/test/distros work on top of it ... and probably also do a second pass over the docs to make sure they explain everything ... and a 'snapshot map' (and catalogs) to bootstrap an instance with self-knowledge along with anything else that should go in a base/bootstrap Substrate instance"; motto: "map or design software, agents, and organizations. optimize all the things!"; "my earlier concept of mapping/modeling everything outside this scope comes later built on top of and enabled by all this"). (a) **Running on top:** distributions, MetaSoar's experiments and every test suite use Substrate only through its contracts (S-185); plan step 6. (b) **The bootstrap instance** (plan step 7): a snapshot map of Substrate's own parts (the `catalog/` entities, 48 files today, and the compose file in the kernel), catalogs of the candidates already researched per intended component with their measurements, the vocabularies (S-175), Morphogen cells for Substrate's own configuration, default gates and privacy rules, the skills, and a first task (map yourself and check the map against what runs); one command loads it into an empty kernel; done when a fresh instance answers "what are you made of, and what could replace each part?" from its own store. (c) **A second documentation pass** (plan step 8), read cold. (d) **Scope:** software, agents and organisations first; mapping anything else comes later, on top. (e) **The motto**, the owner's, for the README and marketing: "Map or design software, agents and organisations. Optimise all the things!" | decided | +| S-188 | **The MCP installer's registries and how far each is trusted; LFM3 recommended; downloads may be recommended whatever their licence; business work in its own session** (2026-11-23; the owner: "give me a list of registries and how much you'd trust any of them"; "LFM3 is probably acceptable its just custom and we haven't read it, its fine to recommend these things since they can be downloaded by the user and not bundled - the only real issue with software licensing"; "the 'smb foundry' and any other business opportunities need to be revisited in another context where we can just focus on that without the code polluting context, but it needs to happen as soon as this substrate is ready for it. those first customers are the most valuable even if they don't pay a dime"). Supersedes S-182 (c)'s open registry question and S-169 (c)'s "the owner's call" on LFM3. (a) **Registries, from web searches of 2026-11-23 (vendor and blog sources; not yet read at each registry's own docs with the research skill):** **Docker MCP Catalog**: Docker-built, signed images with provenance and SBOM attestations, commit pinning, verifiable with cosign; Docker itself calls its measures best-effort; **trust highest for running code**, and it already fits rule 6 (each server in its own container). **The official MCP Registry** (`registry.modelcontextprotocol.io`, still in preview in October 2026, roughly 47,000 to 65,000 servers by different counts): metadata only, the publisher's namespace verified through GitHub, DNS or an HTTP challenge, no scanning of code; **trust: who published, not whether it is safe**; the index to search. **GitHub's MCP Registry**: a small curated set (tens of partner and community servers) mirrored from the official one, with enterprise allow lists; **trust: a curation signal, small coverage**. **Smithery**: a directory and a host; a path-traversal flaw disclosed in October 2025 exposed a token reaching more than 3,000 hosted servers (fixed); hosted servers receive users' tokens; MCP-Scan now runs on its listings; **trust: discovery only, never its hosting**. **Aggregators** (Glama, PulseMCP, mcp.so and others): rankings and search over the official registry; **discovery only**. Underneath them all, npm and PyPI: trust per package (publisher, attestations, deps.dev). **The installer's policy:** search the official registry (and Docker's catalog); prefer a Docker-catalog image, else a namespace-verified publisher, with GitHub's curation as a signal; every install still goes through `propose`, an exact pin, the licence check, its own container and a catalog entry (S-182 c); listing never implies trust; a server whose tools ask for broad credentials is flagged in the proposal. To confirm with the research skill when the installer is built. (b) **Licences of downloads (rule 7 extended):** rule 7 governs what the repository contains, links or bundles; a model or tool the user downloads themselves may be recommended whatever its licence, with the licence named. So **LFM3 1.7B is the recommended fast model** (`.env.example` says so; `LLM_FAST_MODEL` stays empty, since the file is the user's download); its licence, LiquidAI's LFM Open License v1.0, is named and still to be read. (c) **Business work** (the SMB Foundry and other opportunities) goes to **its own session**, without the code in its context, **as soon as Substrate is ready for it** (after plan steps 6 to 8); the first customers are design partners and the most valuable, paid or not. | decided | +| S-189 | **The motto corrected; one Postgres server with a database per concern, not one database; agent-facing documentation in the bootstrap instance; an `rtfm` skill** (2026-11-23; the owner: "correction: 'Map, design, and orchestrate software, agents and organisations. Optimise all the things!'"; "if there was any confusion around 'one database' i was not opposed to multiple db's in a single Postgres server just didn't want to run multiple servers"; "we're probably going to need to write more than 'skills' but a full 'agent-facing documentation' to bundle with a bootstrap instance"; "something missing from coding agents even today is a 'RTFM' skill where the agent will assume it doesn't have the latest knowledge about a library or otherwise and goes out to get the manual, which can be ingested into kernel to easily search and retrieve content by association"). Supersedes S-187 (e)'s wording of the motto, and S-185's "one database" (I had read the owner's "two databases" as databases, not servers). (a) **The motto:** "Map, design and orchestrate software, agents and organisations. Optimise all the things!" (b) **Databases:** one Postgres server, a database per concern, as today (`kernel`, `substrate`, `gateway`); the kernel's D-94 (c) stands and needs no change. The one trade-off: Postgres has no transaction or trigger across databases, so if a step must change an object and record its version atomically, those two share a database; that step says so when it happens. (c) **Agent-facing documentation** in the bootstrap instance (plan step 7): how the system works, its contracts, each tool and each part, written for an agent, loaded into the kernel for recall, beside the skills. (d) **The `rtfm` skill** (plan step 5), for every agent, Substrate's rule 1 made a skill: assume knowledge of a library, tool, API or standard is stale; fetch the manual for the exact version in use (project docs, `llms.txt`, the registry page, a trusted docs MCP server); ingest it into the kernel with source, version and spans, so it is recalled by association and cited; answer from it. Prior art to check with the research skill when building it: docs servers such as Context7, the `llms.txt` convention (not yet read). | decided | +| S-190 | **One database after all: the kernel's** (2026-11-23; the owner: "I'm not sure that we need a database for each concern when what we're trying to do is create the schema and ways of doing things through kernel which substrate will follow. So maybe it is all one database and you're right to get on that page"). Supersedes S-189 (b) and restores S-185's one database. The kernel defines the schemas and the ways of doing things; Substrate follows them; so the `env` schema (objects' live state, queues, gates, `env.experience`) moves into the kernel's database, by a kernel decision superseding its D-94 (c) ("Distributions such as Substrate create their queues in a database of their own"). One transaction or trigger can then change an object and record its version. The `substrate` database keeps only the retired `store` schema until the owner drops it. Bifrost's `gateway` database is a third party's private store and stays apart unless Bifrost can use a schema in the kernel's database (to check when step 4 is done). Still one Postgres server. | decided | +| S-191 | **The retired `store` schema is dropped; the kernel's D-126 replaces D-94 (c)** (2026-11-23; the owner: "D94c makes no sense to me and you should drop the substrate store database"). (a) **Dropped:** schema `store` in database `substrate` (10 tables, 17 MB; its content was exported to the kernel in S-154 and nothing in the tree uses it: only an old trial script and the throwaway test schema `scripts/tests/oldschema/` mention it), after a dump to `.state/backups/substrate-store-schema-20261123-114349.sql` (10 tables' data). The database `substrate` itself stays for now: it still holds the live `env` schema the companion, worker, voice head and judge use; it goes once `env` has moved into the kernel's database (plan step 4). Schema `graph` is the pgGraph extension's own and stays. `scripts/check.sh` and all eleven test suites pass after the drop. (b) **The kernel's D-126** ("One database: distributions keep their schemas in the kernel's database; supersedes D-94 (c)") is committed on the kernel's branch `claude/one-database`, stacked on `claude/compose-codec` (PR #134) so the numbering follows D-125; not pushed. | done (a); (b) awaiting push and review | +| S-192 | **The OpenEnv spike passes all seven points; gates stay a `propose` tool; Harbor and AgentEnv noted** (2026-11-23; plan step 1; S-184's seven points; code `scripts/trials/openenv/`, results `.state/trials/openenv/summary.md` and `results.jsonl`; openenv 0.12.0, fastmcp 3.4.11, mcp 1.30.0, Claude Code 2.1.311, Postgres 17.11; read in the installed package's source and run, not from docs). (1) **One live environment, many sessions:** OpenEnv makes an environment instance per session; with state in Postgres and `SUPPORTS_CONCURRENT_SESSIONS`, three MCP sessions on one production server each saw all six notes; `max_concurrent_envs` defaults to 1 and must be raised. (2) **Events:** OpenEnv pushes nothing (every websocket send is a reply), so events come from Postgres: a trigger's `pg_notify` reached a LISTEN subscriber in a median 2.6 ms; pgmq as `environment/` already does. (3) **Simulation `reset`** cloned a 9 MB template database in a median 61 ms (`STRATEGY WAL_LOG`) or 83 ms (`FILE_COPY`): fast enough; episode copies are throwaway databases beside the kernel's one (S-190 is about live state). (4) **Claude Code** ran as an RFC 005 `HarnessEnvironment` through our own `AgenticHarnessAdapter` (about 90 lines: `claude -p --bare --tools "" --mcp-config --strict-mcp-config`, resumed by session id; openenv 0.12.0 ships no Claude Code adapter for the turn API, only a black-box seam in its Harbor integration), calling the environment's tool over OpenEnv's loopback MCP bridge. (5) **`ANTHROPIC_BASE_URL`** sent every model call to a stand-in proxy, each with the episode id in `X-Episode-Id` from `ANTHROPIC_CUSTOM_HEADERS`; **we carry the episode in that header**, since the API key stays the caller's gateway key (OpenEnv's capture proxy uses the key as the session id instead). (6) **A skill's answer** with no model, a streamed `tool_use` block then final text, was executed and ended the turn. (7) **A rubric's** forward hook wrote its score as the episode's outcome, joined to every model call of the episode by id (as `env.outcome`, S-183). **Also found:** production `/mcp` is OpenEnv's own JSON-RPC (tools/list, tools/call, `openenv/session/*`, no `initialize`), not standard MCP: an orchestrator attaches through the environment's FastMCP served as streamable HTTP (`http_app()`, as the bridge does). **`input_required`:** MCP 2026-07-28 is the current released revision (modelcontextprotocol.io/specification/versioning) with multi-round-trip results (`resultType: "input_required"`, `inputRequests`, `requestState`, retried with `inputResponses`) and the Tasks extension's `input_required` status; the `mcp` SDK has it from 2.0.0; but fastmcp 3.4.11 requires `mcp<2.0`, so openenv 0.12.0 speaks 2025-11-25: **gates stay a `propose` tool returning `waiting_for_approval`** until fastmcp and openenv move to `mcp` 2. **Harbor and AgentEnv** (the owner's question): openenv already ships `openenv.harbor` (Harbor's task datasets, sandboxes, agents and verifiers served as OpenEnv environments; Harbor is Apache-2.0, v0.27.0 of 2026-11-21; its capture proxy records token ids and logprobs for training, needing vLLM or SGLang) and its current README says `openenv import` wraps Scale AI's AgentEnv bundles (`scaleapi/agentenv-framework`, Apache-2.0; 0.12.0's importers are only ORS and verifiers). Neither is needed now: Harbor fits MetaSoar's experiments and M-17's runs (plan step 9), AgentEnv only if we take environments from its bundles; both to weigh with the research skill then. | done | diff --git a/README.md b/README.md index d6cb76d..3aa23ab 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,36 @@ # Substrate -An agent framework, built around one working system so far: **the companion**, an assistant you can talk to, -in text or out loud with a face, that does real work in the background and improves its own parts under a -judge it cannot reach. - -The idea: you put an **environment** on a system you need. An environment is data in Postgres: the signals that -arrive, the actuators that can be acted on, and a record of everything. With nothing else configured, every -signal goes to an LLM harness (Claude Code), which acts only through gated actuators. That is **pass-through**. -From the record, the system writes **components** that handle what repeats, each with a **card** saying what it -is for, how it is measured and how it is tested. A **judge** tests each new version against the one in use, on -cases its author never saw, and **you** decide what goes live. - -It is four parts, each its own repository (S-153): +> **Map, design and orchestrate software, agents and organisations. Optimise all the things!** + +**An operating system for AI agents.** Today's agents live in a terminal where everything is a file. Here a working +system (a business, a codebase, a household, a game) lives in a **kernel** made of Postgres, where everything is an +object: state, actions behind permission gates (`free`, `propose` for your approval, `deny`), events anyone allowed +can subscribe to, and every change recorded. A **top-level orchestrator**, an ordinary LLM harness (Claude Code +first) given skills, MCP servers and hooks, keeps that system working: it **maps** it, **orchestrates** it through +sub-agents in shared environments (any harness, any model, or no model), and **optimises** it through an optimiser +whose judge it cannot edit, toward goals you set, asking before anything that matters. Harnesses join unmodified, +models come through one gateway, tools through MCP, and environments through [OpenEnv](https://huggingface.co/docs/openenv), +so a change can be rehearsed on a copy before it runs for real. | Part | What it is | | --- | --- | -| **Substrate** (this repository) | environments, streams and gated actuators, pass-through to Claude Code, components with cards, the judge interface, the model gateway, the UI | -| **[Knowledge Kernel](https://github.com/OpenReplicant/kernel)**, the store | everything known, each statement with who said it, its source and how sure; permissions enforced by Postgres per caller; review before anything counts; recall by words and by meaning (BM25 and pgvector) | -| **[MetaSoar](https://github.com/OpenReplicant/MetaSoar)**, the cognitive layer | how an agent perceives, attends, predicts and learns inside an environment, with the predictions that would show its model wrong; today it plays ARC-AGI-3 games and Super Mario Bros. from the screen | -| **The judge** | an interface: a candidate in, a verdict out, on cases its author never saw; [Morphogen](https://github.com/OpenReplicant/Morphogen) is one filler | +| **[Knowledge Kernel](https://github.com/OpenReplicant/kernel)** | Postgres made into a kernel: knowledge with provenance, objects and gated actions, logins and row-level security, the record | +| **Substrate** (this repository) | the orchestrator kit (skills `map`, `catalog`, `research`, `orchestrate`, `optimize`; hooks; adapters for OpenEnv, the model endpoint and compose), the reference stack, and the documentation | +| **[Morphogen](https://github.com/OpenReplicant/Morphogen)** | the optimiser, a Claude Code plugin: cells, optimizers behind a judge they cannot edit, an evidence log | +| **Distributions** (`distributions/`, here for now) | what is built with it: the personal assistant (voice, face, local models), the SMB Foundry, games | +| **[MetaSoar](https://github.com/OpenReplicant/MetaSoar)** | the research on cognitive architecture: System 1 distilled from experience (M-17) | + +Every dependency between them is a contract, not another project's code: the shape, the slots and what each needs +are in [`docs/framework.md`](docs/framework.md); what is built next is [`docs/plan.md`](docs/plan.md). -All of that now runs end to end once, on one component (the voice head's replies). The rest of the framework is -described in [`docs/framework.md`](docs/framework.md) and built as the plan's steps need it. +**Where it stands (2026-11-23):** the stack below runs on one machine. The parts that make up the personal +assistant (the companion, the voice head, the worker, blocks, the ladder's experience store) are still at the +repository's top level and move into `distributions/assistant/` (plan step 3); the first new work is an OpenEnv +spike (step 1), then Morphogen as the optimiser (step 2). ## What runs -Everything is in containers under Podman compose, published on 127.0.0.1 only. +The reference stack and, for now, the assistant distribution's parts. Everything is in containers under Podman compose, published on 127.0.0.1 only. | Part | Where | What it does | | --- | --- | --- | @@ -33,10 +38,11 @@ Everything is in containers under Podman compose, published on 127.0.0.1 only. | The environment | `environment/`, schema `env` | Signals logged whole and fanned out as pgmq topics; one queue per actuator behind a gate (`free`, `propose`, `deny`); proposals wait for a person; every action recorded | | The channel | `environment/channel.py` | Pushes an environment's signals into a live Claude Code session; a signal not acknowledged comes back | | The gateway | `gateway` (Bifrost), `scripts/gateway.py` | Every model call goes through it under its caller's key and is logged there, not by the caller. Keys decide which providers a caller may reach (voice stays local) | -| The companion | `deploy/companion`, service `companion` | Claude Code on Haiku, on your own Claude login, in its own container with no built-in tools, only the channel. It replies, starts background tasks (a separate Claude Code run with tools), and proposes budget and model changes | +| The assistant | `environment/worker.py`, service `worker`, the UI's `#/worker` | One agent loop on your own models: the slow model (`slow`, Inkling 2 Mini on the CPU here) with the kernel's memory and a workspace; compiled skills answer without a model. Handing work to the cloud waits for your approval | +| The companion (to retire) | `deploy/companion`, service `companion` | Claude Code on Haiku, on your own Claude login, in its own container with only the channel. It replies, starts background tasks and proposes budget and model changes; it becomes the assistant's `cloud` level (S-181) | | The companion's environment | `environment/companion.py`, service `environment` | The clock, the gateway's meter of the companion's own spend, the daily budget (background tasks are refused while over it), and the appliers of approved proposals: outside the companion's reach | -| The local model | service `llm` (llama.cpp) | Your own GGUF (Gemma 4 26B-A4B here) on the GPU, mixture-of-experts weights in system RAM | -| The voice head | `voice/`, service `voice`, http://127.0.0.1:8110 | The microphone in over a WebSocket; Silero cuts utterances, Parakeet turns them into text, the local model answers, Kokoro speaks each sentence, a face moves with the audio. Talk over it and it stops. Real work is handed to the companion, whose answers are read out | +| The local models | services `llm` and `llm-fast` (llama.cpp) | Two of your own GGUFs (S-169): a slow capable one on the CPU (`slow`; Inkling 2 Mini here) and a small fast one on the GPU (`fast`; LFM3 1.7B here) | +| The voice head | `voice/`, service `voice`, http://127.0.0.1:8110 | The microphone in over a WebSocket; Silero cuts utterances, Parakeet turns them into text, the fast model decides each turn by the tool it calls (talk, quick tools such as notes, reminders, lookups and search, or hand over), Kokoro speaks each sentence, a face moves with the audio. Talk over it and it stops. Real work goes to the assistant, whose answers are read out (S-170, S-171) | | Components and the judge | `env.component`, `env.verdict`, `environment/author.py`, `environment/judge.py`, service `judge` | Every version of a component with its card; an author writes new versions from the record; the judge tests them on cases only it can read; you activate | | The UI | `ui/`, service `ui`, http://127.0.0.1:8100 | The store's pages and maps as diagrams; the companion's page: the conversation, proposals to approve or refuse, the meter, the components and their verdicts | @@ -98,7 +104,7 @@ Picked: Parakeet 110M and kokoro-onnx, both on the CPU, so the GPU stays the lan not worth sharing the card. Every candidate is in the store's catalog with a note on when it would be the better choice (Kokoro on the GPU if the model moves off this card; Parakeet 0.6B for other languages). -**The local model** (S-149). llama.cpp rather than Ollama, because only llama.cpp keeps a mixture-of-experts +**The local model** (S-149; since replaced by two models, S-169). llama.cpp rather than Ollama, because only llama.cpp keeps a mixture-of-experts model's experts in system RAM (`--cpu-moe`): Gemma 4 26B-A4B then uses 2.9 GB of the 1070's 8 GB. Gemma 4 thinks before answering by default, about 6 s before the first word; with thinking off, 0.4 s. The first answer after the model loads took 14 s while its weights were read in from disk, so the voice head warms it at start. Spoken @@ -145,25 +151,24 @@ allow the microphone; headphones help). The defaults are in [`docs/privacy.md`](docs/privacy.md): nothing personal leaves the machine unless a rule is loosened for a named stream, and each loosening is a recorded decision. Loosened so far: your typed messages to -the companion reach Anthropic (S-136). What you say aloud stays on this machine: the voice head, its author and -its judge use only the local model, and only requests the voice hands over reach the companion. The gateway keeps -no message content. +the companion reach Anthropic (S-136). What you say aloud stays on this machine: the voice head, the assistant, +the author and the judge use only your own models, and the assistant hands work to the cloud only when you approve +it. Two quick tools you chose send questions out: Wikipedia lookups and SearXNG search (S-171). The gateway keeps no +message content. The gate's experience keeps your requests word for word, encrypted, deletable and kept only as long as you set (S-182). ## Not built yet -- Components beyond the first; the judge running each case more than once (so smaller differences can be told - from noise), judging answer quality, and comparing against plain pass-through; holding out whole days. -- The component lifecycle past activation: demotion when you keep overriding one, and the rate of model calls - per event, the number that should fall as it learns. -- The view (how the environment is laid out for each model) as a tested component; environments nested in one - another; a review lane in the UI beyond the companion page. -- A VRM avatar for the face, mixed reality on a Quest 3, and the embodied environments after it - (`docs/plan.md` steps 7 to 10). +`docs/plan.md`, "Next, in order": the OpenEnv spike; Morphogen as the optimiser; the repository in its shape +(distributions in folders); the `orchestrate` and `optimize` skills and gate hooks; the ladder on +OpenEnv and M-17's experiment; the SMB Foundry distribution. Later, in the assistant distribution: a VRM avatar, +mixed reality on a Quest 3, and the embodied environments after it. ## Where to read more - [`docs/plan.md`](docs/plan.md): the steps, and where each stands -- [`docs/framework.md`](docs/framework.md): the shape of the framework +- [`docs/framework.md`](docs/framework.md): the shape: layers, the orchestrator, objects, slots and contracts +- [`docs/repos.md`](docs/repos.md): what each repository owns and depends on +- [`docs/research/`](docs/research/): the prior-art research behind the shape (2026-11-23) - [`DECISIONS.md`](DECISIONS.md): every default, every measurement behind it, and why (append-only) - `CLAUDE.md`: the parts and the rules for working on it diff --git a/blocks/__init__.py b/blocks/__init__.py index fd15c52..0777fe2 100644 --- a/blocks/__init__.py +++ b/blocks/__init__.py @@ -12,17 +12,19 @@ Schema subset: type (object, array, string, number, integer, boolean, null), properties, required, items, enum. -A plan (an assembly) is JSON in P-Plan's terms, data and not code: +A plan (an assembly) is JSON, data and not code; in the kernel it is a PROV-O plan (`prov:Plan`; a run is a +`prov:Activity` that `prov:hadPlan` it) with the vocabulary profile's own terms for steps, order and variables (S-175, +the kernel's D-124; P-Plan was dropped for its non-commercial licence): {"type": "Plan", "name", "version", "description", - "variables": {"text": {"type": "string"}}, p-plan:Variable: the plan's inputs - "steps": [{"id": "count", "block": "word_count", p-plan:Step; the block it runs + "variables": {"text": {"type": "string"}}, the plan's inputs (its variables) + "steps": [{"id": "count", "block": "word_count", a step: the block it runs "inputs": {"text": "$input.text"}}], "$input.x" a variable, "$step.field" an earlier step's output, {"value": ...} a literal "answer": "{count.words} words", what the plan says when it is done "trigger": {"pattern": "(?i)^count (?P.+)$"}} optional: a task that matches runs it (the skill gate) -A step precedes another when the second reads its output (p-plan:isPrecededBy); order follows from that. +A step precedes another when the second reads its output ; order follows from that. """ from __future__ import annotations diff --git a/blocks/executor.yaml b/blocks/executor.yaml index 33f2320..a525990 100644 --- a/blocks/executor.yaml +++ b/blocks/executor.yaml @@ -5,7 +5,7 @@ description: Runs a plan step by step in dependency order, in a subprocess per b kind: executor layer: code entry: blocks.run:Executor -plan_format: p-plan (JSON, blocks/__init__.py) +plan_format: plan JSON (blocks/__init__.py), a PROV-O plan in the kernel (S-175) runs: [python, command] refuses: [http, mcp] enforces: [timeout_s, retry-once-if-idempotent, changes_world-through-an-Env-actuator] diff --git a/catalog/README.md b/catalog/README.md new file mode 100644 index 0000000..dad68e9 --- /dev/null +++ b/catalog/README.md @@ -0,0 +1,23 @@ +# Substrate's catalog + +Substrate's own parts, one file per entity, in **Backstage's entity format** (`backstage.io/v1alpha1`): components +(services, jobs, agents, blocks, plans, external services), the APIs they provide and consume, the database, the +system and its owner (S-176). It is the first content type of the kernel's D-101: each entity is an item, each file a +version kept as an artifact, and the kernel's claims about it (each citing its file and line) are its fields. + +- **Interfaces** are `API` entities: `spec.type` names the protocol (`openapi`, `asyncapi` for a pgmq queue, `mcp`, + `websocket`, `http`, `wot-td` for blocks and plans) and `spec.definition` holds the contract; a block's is a + WoT Thing Description action read from its `block.yaml`. +- **Annotations** (`substrate.dev/*`): `licence`, `image`, `compose-service`, `decision`, `source`, `gate`, + `otel-service`, `trigger`. +- **A queue's provider** is the component that receives on it (the worker provides `worker-tasks`; the voice head + and the UI consume it by publishing to it), as in AsyncAPI. + +```sh +bin/in-tools python3 scripts/catalog.py check --compose deploy/compose.yaml # every consumed API provided, compose matched +bin/in-tools python3 scripts/catalog.py apis # each API, its providers and consumers +scripts/kernel.sh catalog # into the kernel (encoder-backstage) +bin/in-tools python3 scripts/catalog.py check --kernel # the same fit from the kernel's claims, and drift +``` + +`scripts/check.sh` runs the first; a compose service added without an entry fails it. diff --git a/catalog/api-anthropic-api.yaml b/catalog/api-anthropic-api.yaml new file mode 100644 index 0000000..bce85b4 --- /dev/null +++ b/catalog/api-anthropic-api.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: anthropic-api + title: Anthropic's API +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "api.anthropic.com", + "version": "0" + }, + "paths": { + "/v1/messages": { + "post": { + "summary": "api.anthropic.com" + } + } + } + } diff --git a/catalog/api-anthropic-messages.yaml b/catalog/api-anthropic-messages.yaml new file mode 100644 index 0000000..e903fc0 --- /dev/null +++ b/catalog/api-anthropic-messages.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: anthropic-messages + title: Anthropic Messages at the gateway +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "Messages API, and the pass-through route for a Claude login", + "version": "0" + }, + "paths": { + "/anthropic/v1/messages": { + "post": { + "summary": "Messages API, and the pass-through route for a Claude login" + } + } + } + } diff --git a/catalog/api-block-note-with-count.yaml b/catalog/api-block-note-with-count.yaml new file mode 100644 index 0000000..ca0e06f --- /dev/null +++ b/catalog/api-block-note-with-count.yaml @@ -0,0 +1,45 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: block-note-with-count + title: The note_with_count plan + description: Count the words of a text and save it as a note. + annotations: + substrate.dev/trigger: '(?is)^save a note called (?P[\w-]+): (?P.+)$' +spec: + type: wot-td + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "@context": "https://www.w3.org/2022/wot/td/v1.1", + "title": "note_with_count", + "actions": { + "note_with_count": { + "input": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "name", + "text" + ] + }, + "safe": false, + "forms": [ + { + "href": "substrate:blocks/run.py", + "subprotocol": "substrate-plan" + } + ] + } + } + } diff --git a/catalog/api-block-word-count.yaml b/catalog/api-block-word-count.yaml new file mode 100644 index 0000000..8fe59dd --- /dev/null +++ b/catalog/api-block-word-count.yaml @@ -0,0 +1,53 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: block-word-count + title: The word_count block + description: Counts the words in a text. + annotations: {} +spec: + type: wot-td + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "@context": "https://www.w3.org/2022/wot/td/v1.1", + "title": "word_count", + "actions": { + "word_count": { + "input": { + "type": "object", + "properties": { + "text": { + "type": "string" + } + }, + "required": [ + "text" + ] + }, + "output": { + "type": "object", + "properties": { + "words": { + "type": "integer" + } + }, + "required": [ + "words" + ] + }, + "safe": true, + "idempotent": true, + "forms": [ + { + "href": "stdio:python -I word_count:run", + "contentType": "application/json", + "subprotocol": "substrate-block-stdio" + } + ] + } + } + } diff --git a/catalog/api-block-write-note.yaml b/catalog/api-block-write-note.yaml new file mode 100644 index 0000000..995907e --- /dev/null +++ b/catalog/api-block-write-note.yaml @@ -0,0 +1,58 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: block-write-note + title: The write_note block + description: Writes a note into the worker's workspace (WORKER_WORKSPACE, default /workspace) as notes/.txt. + annotations: + substrate.dev/gate: blocks.write_note +spec: + type: wot-td + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "@context": "https://www.w3.org/2022/wot/td/v1.1", + "title": "write_note", + "actions": { + "write_note": { + "input": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "name", + "text" + ] + }, + "output": { + "type": "object", + "properties": { + "path": { + "type": "string" + } + }, + "required": [ + "path" + ] + }, + "safe": false, + "idempotent": true, + "forms": [ + { + "href": "stdio:python -I write_note:run", + "contentType": "application/json", + "subprotocol": "substrate-block-stdio" + } + ] + } + } + } diff --git a/catalog/api-companion-channel.yaml b/catalog/api-companion-channel.yaml new file mode 100644 index 0000000..7c5cc5a --- /dev/null +++ b/catalog/api-companion-channel.yaml @@ -0,0 +1,18 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: companion-channel + title: The channel into Claude Code +spec: + type: mcp + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "protocol": "model-context-protocol", + "transport": "stdio", + "tools": [], + "note": "the claude/channel contract: signals in, archived only on ack (S-143)" + } diff --git a/catalog/api-companion-session.yaml b/catalog/api-companion-session.yaml new file mode 100644 index 0000000..db0c140 --- /dev/null +++ b/catalog/api-companion-session.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: companion-session + title: The companion's session queue +spec: + type: asyncapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "asyncapi": "3.0.0", + "info": { + "title": "signals for the companion's Claude Code session", + "version": "0" + }, + "channels": { + "companion_session": { + "address": "companion_session", + "description": "signals for the companion's Claude Code session" + } + }, + "x-transport": "pgmq (Postgres), the env schema's topics and queues (S-143)" + } diff --git a/catalog/api-embeddings.yaml b/catalog/api-embeddings.yaml new file mode 100644 index 0000000..529bbb8 --- /dev/null +++ b/catalog/api-embeddings.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: embeddings + title: Embeddings at the gateway +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "ollama/qwen3-embedding:0.6b", + "version": "0" + }, + "paths": { + "/v1/embeddings": { + "post": { + "summary": "ollama/qwen3-embedding:0.6b" + } + } + } + } diff --git a/catalog/api-kernel-mcp-memory.yaml b/catalog/api-kernel-mcp-memory.yaml new file mode 100644 index 0000000..64a8051 --- /dev/null +++ b/catalog/api-kernel-mcp-memory.yaml @@ -0,0 +1,23 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: kernel-mcp-memory + title: The kernel's memory profile +spec: + type: mcp + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "protocol": "model-context-protocol", + "transport": "stdio", + "tools": [ + "remember", + "recall", + "explain", + "changes_since" + ], + "note": "KK_PROFILE=memory" + } diff --git a/catalog/api-kernel-mcp-substrate.yaml b/catalog/api-kernel-mcp-substrate.yaml new file mode 100644 index 0000000..11525b6 --- /dev/null +++ b/catalog/api-kernel-mcp-substrate.yaml @@ -0,0 +1,29 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: kernel-mcp-substrate + title: The kernel's substrate profile +spec: + type: mcp + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "protocol": "model-context-protocol", + "transport": "stdio", + "tools": [ + "search", + "read", + "expand", + "locate", + "path", + "alternatives", + "violations", + "create_item", + "say", + "deprecate" + ], + "note": "KK_PROFILE=substrate" + } diff --git a/catalog/api-llama-chat-fast.yaml b/catalog/api-llama-chat-fast.yaml new file mode 100644 index 0000000..980aaf8 --- /dev/null +++ b/catalog/api-llama-chat-fast.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: llama-chat-fast + title: llama-server, the fast model +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "llama.cpp's OpenAI-compatible server at llm-fast:8080", + "version": "0" + }, + "paths": { + "/v1/chat/completions": { + "post": { + "summary": "llama.cpp's OpenAI-compatible server at llm-fast:8080" + } + } + } + } diff --git a/catalog/api-llama-chat-slow.yaml b/catalog/api-llama-chat-slow.yaml new file mode 100644 index 0000000..6f0d649 --- /dev/null +++ b/catalog/api-llama-chat-slow.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: llama-chat-slow + title: llama-server, the slow model +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "llama.cpp's OpenAI-compatible server at llm:8080", + "version": "0" + }, + "paths": { + "/v1/chat/completions": { + "post": { + "summary": "llama.cpp's OpenAI-compatible server at llm:8080" + } + } + } + } diff --git a/catalog/api-model-chat.yaml b/catalog/api-model-chat.yaml new file mode 100644 index 0000000..827451e --- /dev/null +++ b/catalog/api-model-chat.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: model-chat + title: OpenAI Chat Completions at the gateway +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "chat completions, tool calls, streaming; key in Authorization: Bearer or x-bf-vk", + "version": "0" + }, + "paths": { + "/v1/chat/completions": { + "post": { + "summary": "chat completions, tool calls, streaming; key in Authorization: Bearer or x-bf-vk" + } + } + } + } diff --git a/catalog/api-model-responses.yaml b/catalog/api-model-responses.yaml new file mode 100644 index 0000000..729ee31 --- /dev/null +++ b/catalog/api-model-responses.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: model-responses + title: OpenAI Responses at the gateway +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "the Responses API, translated by Bifrost (checked 2026-11-22)", + "version": "0" + }, + "paths": { + "/v1/responses": { + "post": { + "summary": "the Responses API, translated by Bifrost (checked 2026-11-22)" + } + } + } + } diff --git a/catalog/api-ollama-api.yaml b/catalog/api-ollama-api.yaml new file mode 100644 index 0000000..c1a8999 --- /dev/null +++ b/catalog/api-ollama-api.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: ollama-api + title: Ollama API +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "Ollama's native API", + "version": "0" + }, + "paths": { + "/api/embed": { + "post": { + "summary": "Ollama's native API" + } + } + } + } diff --git a/catalog/api-search-api.yaml b/catalog/api-search-api.yaml new file mode 100644 index 0000000..1c5ebc3 --- /dev/null +++ b/catalog/api-search-api.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: search-api + title: SearXNG search +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "q, format=json", + "version": "0" + }, + "paths": { + "/search": { + "get": { + "summary": "q, format=json" + } + } + } + } diff --git a/catalog/api-speech-api.yaml b/catalog/api-speech-api.yaml new file mode 100644 index 0000000..cc2d2a7 --- /dev/null +++ b/catalog/api-speech-api.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: speech-api + title: OpenAI-compatible speech +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "Kokoro-FastAPI; pcm or wav", + "version": "0" + }, + "paths": { + "/v1/audio/speech": { + "post": { + "summary": "Kokoro-FastAPI; pcm or wav" + } + } + } + } diff --git a/catalog/api-ui-http.yaml b/catalog/api-ui-http.yaml new file mode 100644 index 0000000..fb1c87d --- /dev/null +++ b/catalog/api-ui-http.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: ui-http + title: The UI +spec: + type: http + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "the pages; the API under /api", + "version": "0" + }, + "paths": { + "/": { + "get": { + "summary": "the pages; the API under /api" + } + } + } + } diff --git a/catalog/api-voice-ws.yaml b/catalog/api-voice-ws.yaml new file mode 100644 index 0000000..5bca126 --- /dev/null +++ b/catalog/api-voice-ws.yaml @@ -0,0 +1,18 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: voice-ws + title: The voice head's page and socket +spec: + type: websocket + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "page": "http://127.0.0.1:8110/", + "socket": "ws://127.0.0.1:8110/", + "in": "16 kHz int16 PCM frames; {type: stop}", + "out": "state, heard, say, audio (24 kHz PCM), error" + } diff --git a/catalog/api-wikipedia-rest.yaml b/catalog/api-wikipedia-rest.yaml new file mode 100644 index 0000000..c04254f --- /dev/null +++ b/catalog/api-wikipedia-rest.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: wikipedia-rest + title: Wikipedia REST +spec: + type: openapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "then /api/rest_v1/page/summary/{title}", + "version": "0" + }, + "paths": { + "/w/rest.php/v1/search/page": { + "get": { + "summary": "then /api/rest_v1/page/summary/{title}" + } + } + } + } diff --git a/catalog/api-worker-results.yaml b/catalog/api-worker-results.yaml new file mode 100644 index 0000000..de3a3a2 --- /dev/null +++ b/catalog/api-worker-results.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: worker-results + title: The worker's results +spec: + type: asyncapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "asyncapi": "3.0.0", + "info": { + "title": "each task's outcome: text, ok, model_calls, skipped_calls, cited, reply_to", + "version": "0" + }, + "channels": { + "worker.task.done": { + "address": "worker.task.done", + "description": "each task's outcome: text, ok, model_calls, skipped_calls, cited, reply_to" + } + }, + "x-transport": "pgmq (Postgres), the env schema's topics and queues (S-143)" + } diff --git a/catalog/api-worker-tasks.yaml b/catalog/api-worker-tasks.yaml new file mode 100644 index 0000000..8c31a53 --- /dev/null +++ b/catalog/api-worker-tasks.yaml @@ -0,0 +1,26 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: worker-tasks + title: The worker's task queue +spec: + type: asyncapi + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "asyncapi": "3.0.0", + "info": { + "title": "worker.owner.message and worker.task: tasks for the worker, which receives on this channel (so it provides it); the voice head and the UI publish to it; reply_to says who wants the answer", + "version": "0" + }, + "channels": { + "worker_loop": { + "address": "worker_loop", + "description": "worker.owner.message and worker.task: tasks for the worker, which receives on this channel (so it provides it); the voice head and the UI publish to it; reply_to says who wants the answer" + } + }, + "x-transport": "pgmq (Postgres), the env schema's topics and queues (S-143)" + } diff --git a/catalog/component-anthropic.yaml b/catalog/component-anthropic.yaml new file mode 100644 index 0000000..64f8bdf --- /dev/null +++ b/catalog/component-anthropic.yaml @@ -0,0 +1,16 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: anthropic + title: Anthropic API + description: Claude, reached only with a caller's own Claude login (the companion's). + annotations: + substrate.dev/licence: proprietary service +spec: + type: external-service + lifecycle: production + owner: owner + system: substrate + providesApis: + - anthropic-api diff --git a/catalog/component-block-word-count.yaml b/catalog/component-block-word-count.yaml new file mode 100644 index 0000000..16d9369 --- /dev/null +++ b/catalog/component-block-word-count.yaml @@ -0,0 +1,18 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: block-word-count + title: word_count + description: Counts the words of a text (blocks/examples/word_count). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/source: blocks/examples/word_count + substrate.dev/decision: S-164 +spec: + type: block + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - block-word-count diff --git a/catalog/component-block-write-note.yaml b/catalog/component-block-write-note.yaml new file mode 100644 index 0000000..f34ade6 --- /dev/null +++ b/catalog/component-block-write-note.yaml @@ -0,0 +1,18 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: block-write-note + title: write_note + description: Writes a note into the worker's workspace; changes the world, behind blocks.write_note (S-164). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/source: blocks/examples/write_note + substrate.dev/decision: S-164 +spec: + type: block + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - block-write-note diff --git a/catalog/component-companion.yaml b/catalog/component-companion.yaml new file mode 100644 index 0000000..8a31ba1 --- /dev/null +++ b/catalog/component-companion.yaml @@ -0,0 +1,23 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: companion + title: Claude Code (the companion) + description: An agent instance on the owner's Claude login through the gateway, fed by the channel (S-136). + annotations: + substrate.dev/licence: proprietary (Claude Code) + substrate.dev/image: ghcr.io/openreplicant/substrate-companion + substrate.dev/compose-service: companion + substrate.dev/decision: S-136, S-144 +spec: + type: agent + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - companion-channel + consumesApis: + - anthropic-messages + - companion-session + - kernel-mcp-substrate diff --git a/catalog/component-environment.yaml b/catalog/component-environment.yaml new file mode 100644 index 0000000..6ffc1c6 --- /dev/null +++ b/catalog/component-environment.yaml @@ -0,0 +1,21 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: environment + title: The companion's environment + description: Its streams, actuators and gates on pgmq; the clock and the meter (environment/companion.py). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: ghcr.io/openreplicant/substrate-tools + substrate.dev/compose-service: environment + substrate.dev/decision: S-143, S-144 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - companion-session + dependsOn: + - resource:db diff --git a/catalog/component-gateway.yaml b/catalog/component-gateway.yaml new file mode 100644 index 0000000..0fb8d66 --- /dev/null +++ b/catalog/component-gateway.yaml @@ -0,0 +1,30 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: gateway + title: Bifrost + description: Every model call passes here, under its caller's key, and is logged (S-77). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: docker.io/maximhq/bifrost:v2.3.2 + substrate.dev/compose-service: gateway + substrate.dev/decision: S-04, S-77 + substrate.dev/otel-service: bifrost +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - model-chat + - model-responses + - anthropic-messages + - embeddings + consumesApis: + - ollama-api + - llama-chat-slow + - llama-chat-fast + - anthropic-api + dependsOn: + - resource:db diff --git a/catalog/component-judge.yaml b/catalog/component-judge.yaml new file mode 100644 index 0000000..2c62f2d --- /dev/null +++ b/catalog/component-judge.yaml @@ -0,0 +1,21 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: judge + title: The judge + description: Tests a component's candidate against the active one on cases its author never read (S-151). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: ghcr.io/openreplicant/substrate-tools + substrate.dev/compose-service: judge + substrate.dev/decision: S-151 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + consumesApis: + - model-chat + dependsOn: + - resource:db diff --git a/catalog/component-kernel-catalog.yaml b/catalog/component-kernel-catalog.yaml new file mode 100644 index 0000000..1e13f26 --- /dev/null +++ b/catalog/component-kernel-catalog.yaml @@ -0,0 +1,21 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: kernel-catalog + title: encoder-backstage + description: Reads catalog/*.yaml, these entries, into the kernel as claims citing their lines (scripts/kernel.sh catalog); + a one-shot job. + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: ghcr.io/openreplicant/kernel + substrate.dev/compose-service: kernel-catalog + substrate.dev/decision: S-176, the kernel's D-100 +spec: + type: job + lifecycle: experimental + owner: owner + system: substrate + dependsOn: + - resource:db + - component:kernel diff --git a/catalog/component-kernel-export.yaml b/catalog/component-kernel-export.yaml new file mode 100644 index 0000000..52c94d9 --- /dev/null +++ b/catalog/component-kernel-export.yaml @@ -0,0 +1,20 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: kernel-export + title: encoder-substrate + description: Exports the retired store's items into the kernel as change sets (scripts/kernel.sh export); a one-shot job. + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: ghcr.io/openreplicant/kernel + substrate.dev/compose-service: kernel-export + substrate.dev/decision: S-154, the kernel's D-103 +spec: + type: job + lifecycle: experimental + owner: owner + system: substrate + dependsOn: + - resource:db + - component:kernel diff --git a/catalog/component-kernel-init.yaml b/catalog/component-kernel-init.yaml new file mode 100644 index 0000000..1f87ad1 --- /dev/null +++ b/catalog/component-kernel-init.yaml @@ -0,0 +1,20 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: kernel-init + title: kk init + description: Installs the kernel's schema, modules and packs in the database kernel (scripts/kernel.sh init); a one-shot + job. + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: ghcr.io/openreplicant/kernel + substrate.dev/compose-service: kernel-init + substrate.dev/decision: S-154 +spec: + type: job + lifecycle: experimental + owner: owner + system: substrate + dependsOn: + - resource:db diff --git a/catalog/component-kernel-mcp.yaml b/catalog/component-kernel-mcp.yaml new file mode 100644 index 0000000..8d733a7 --- /dev/null +++ b/catalog/component-kernel-mcp.yaml @@ -0,0 +1,21 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: kernel-mcp + title: kernel-mcp + description: The kernel's MCP server, run per agent over stdio with the agent's own login. + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: ghcr.io/openreplicant/kernel + substrate.dev/decision: S-154, the kernel's D-88, D-105 +spec: + type: tool + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - kernel-mcp-memory + - kernel-mcp-substrate + dependsOn: + - component:kernel diff --git a/catalog/component-kernel.yaml b/catalog/component-kernel.yaml new file mode 100644 index 0000000..27a197c --- /dev/null +++ b/catalog/component-kernel.yaml @@ -0,0 +1,19 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: kernel + title: The Knowledge Kernel + description: Claims with provenance, belief and clearance; validator and belief model (kk serve). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: ghcr.io/openreplicant/kernel + substrate.dev/compose-service: kernel + substrate.dev/decision: S-153, S-154 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + dependsOn: + - resource:db diff --git a/catalog/component-llm-fast.yaml b/catalog/component-llm-fast.yaml new file mode 100644 index 0000000..71a0407 --- /dev/null +++ b/catalog/component-llm-fast.yaml @@ -0,0 +1,19 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: llm-fast + title: 'llama.cpp: the fast model' + description: A small model wholly on the GPU, fast/fast (S-169). + annotations: + substrate.dev/licence: MIT (llama.cpp); the model's own (LFM Open License v1.0 for LFM3) + substrate.dev/image: ghcr.io/ggml-org/llama.cpp:server-cuda12-b12627 + substrate.dev/compose-service: llm-fast + substrate.dev/decision: S-169 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - llama-chat-fast diff --git a/catalog/component-llm.yaml b/catalog/component-llm.yaml new file mode 100644 index 0000000..472c608 --- /dev/null +++ b/catalog/component-llm.yaml @@ -0,0 +1,19 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: llm + title: 'llama.cpp: the slow model' + description: Inkling 2 Mini on the CPU and in RAM, local/slow (S-169). + annotations: + substrate.dev/licence: MIT (llama.cpp); Apache-2.0 (Inkling 2 Mini) + substrate.dev/image: ghcr.io/ggml-org/llama.cpp:server-cuda12-b12627 + substrate.dev/compose-service: llm + substrate.dev/decision: S-169 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - llama-chat-slow diff --git a/catalog/component-ollama.yaml b/catalog/component-ollama.yaml new file mode 100644 index 0000000..8f3ff4f --- /dev/null +++ b/catalog/component-ollama.yaml @@ -0,0 +1,19 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: ollama + title: Ollama + description: Local embeddings for the store and the voice router (qwen3-embedding:0.6b). + annotations: + substrate.dev/licence: MIT + substrate.dev/image: docker.io/ollama/ollama:0.40.12 + substrate.dev/compose-service: ollama + substrate.dev/decision: S-83 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - ollama-api diff --git a/catalog/component-plan-note-with-count.yaml b/catalog/component-plan-note-with-count.yaml new file mode 100644 index 0000000..9fe19e9 --- /dev/null +++ b/catalog/component-plan-note-with-count.yaml @@ -0,0 +1,21 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: plan-note-with-count + title: note_with_count + description: 'The example plan: count the words, then save the note (blocks/examples/plans).' + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/source: blocks/examples/plans/note.plan.json + substrate.dev/decision: S-164 +spec: + type: plan + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - block-note-with-count + consumesApis: + - block-word-count + - block-write-note diff --git a/catalog/component-search.yaml b/catalog/component-search.yaml new file mode 100644 index 0000000..1b88934 --- /dev/null +++ b/catalog/component-search.yaml @@ -0,0 +1,19 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: search + title: SearXNG + description: Web search for the voice head's search tool; no host port (S-171). + annotations: + substrate.dev/licence: AGPL-3.0 + substrate.dev/image: docker.io/searxng/searxng:2026.11.8-74418092d + substrate.dev/compose-service: search + substrate.dev/decision: S-171 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - search-api diff --git a/catalog/component-tts.yaml b/catalog/component-tts.yaml new file mode 100644 index 0000000..b7b08b1 --- /dev/null +++ b/catalog/component-tts.yaml @@ -0,0 +1,19 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: tts + title: Kokoro-FastAPI + description: Speech on the GPU (S-150). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: ghcr.io/remsky/kokoro-fastapi-gpu:latest + substrate.dev/compose-service: tts + substrate.dev/decision: S-150 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - speech-api diff --git a/catalog/component-ui.yaml b/catalog/component-ui.yaml new file mode 100644 index 0000000..d85f31d --- /dev/null +++ b/catalog/component-ui.yaml @@ -0,0 +1,25 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: ui + title: The UI + description: The store's pages and maps, the companion's and worker's pages (127.0.0.1:8100). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: ghcr.io/openreplicant/substrate-tools + substrate.dev/compose-service: ui + substrate.dev/decision: S-140, S-141 +spec: + type: website + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - ui-http + consumesApis: + - worker-tasks + - companion-session + dependsOn: + - resource:db + - component:kernel diff --git a/catalog/component-voice.yaml b/catalog/component-voice.yaml new file mode 100644 index 0000000..2f22e94 --- /dev/null +++ b/catalog/component-voice.yaml @@ -0,0 +1,29 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: voice + title: The voice head + description: Microphone in, speech out, the avatar; the fast layer's tools (S-147, S-170, S-171). + annotations: + substrate.dev/licence: Apache-2.0 (ours); GPL-3.0 espeak-ng in its own container (S-146) + substrate.dev/image: localhost/substrate-voice:local + substrate.dev/compose-service: voice + substrate.dev/decision: S-147, S-170, S-171 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - voice-ws + consumesApis: + - model-chat + - embeddings + - speech-api + - search-api + - wikipedia-rest + - worker-tasks + - worker-results + dependsOn: + - resource:db diff --git a/catalog/component-wikipedia.yaml b/catalog/component-wikipedia.yaml new file mode 100644 index 0000000..d9e2d4c --- /dev/null +++ b/catalog/component-wikipedia.yaml @@ -0,0 +1,16 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: wikipedia + title: Wikipedia + description: Its REST search and page summaries, for the voice head's lookup tool (S-171). + annotations: + substrate.dev/licence: CC BY-SA (content) +spec: + type: external-service + lifecycle: production + owner: owner + system: substrate + providesApis: + - wikipedia-rest diff --git a/catalog/component-worker.yaml b/catalog/component-worker.yaml new file mode 100644 index 0000000..805ae60 --- /dev/null +++ b/catalog/component-worker.yaml @@ -0,0 +1,25 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: worker + title: The worker + description: An agent on the slow local model with the kernel's memory and workspace tools (S-163). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: ghcr.io/openreplicant/substrate-worker + substrate.dev/compose-service: worker + substrate.dev/decision: S-162, S-163 +spec: + type: agent + lifecycle: experimental + owner: owner + system: substrate + providesApis: + - worker-tasks + - worker-results + consumesApis: + - model-chat + - kernel-mcp-memory + - companion-session + - block-note-with-count diff --git a/catalog/group-owner.yaml b/catalog/group-owner.yaml new file mode 100644 index 0000000..89e609d --- /dev/null +++ b/catalog/group-owner.yaml @@ -0,0 +1,9 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: owner + description: 'The owner: the person who decides.' +spec: + type: person + children: [] diff --git a/catalog/resource-db.yaml b/catalog/resource-db.yaml new file mode 100644 index 0000000..cdf5d18 --- /dev/null +++ b/catalog/resource-db.yaml @@ -0,0 +1,16 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Resource +metadata: + name: db + title: Postgres 17 (pgvector, pg_cron, pgmq, pgGraph) + description: 'The one database: the env schema, the kernel''s database, the gateway''s log.' + annotations: + substrate.dev/licence: PostgreSQL + substrate.dev/image: ghcr.io/openreplicant/substrate-db + substrate.dev/compose-service: db + substrate.dev/decision: S-19, the kernel's D-94 +spec: + type: database + owner: owner + system: substrate diff --git a/catalog/system-substrate.yaml b/catalog/system-substrate.yaml new file mode 100644 index 0000000..ff808f5 --- /dev/null +++ b/catalog/system-substrate.yaml @@ -0,0 +1,8 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: System +metadata: + name: substrate + description: 'Substrate: an environment put on a system, run, watched and changed; its own parts as catalog entries (S-174).' +spec: + owner: owner diff --git a/deploy/compose.yaml b/deploy/compose.yaml index d14a0fe..ef22998 100644 --- a/deploy/compose.yaml +++ b/deploy/compose.yaml @@ -139,6 +139,29 @@ services: depends_on: db: {condition: service_healthy} + # Substrate's catalog into the kernel (S-176): encoder-backstage (the kernel's D-100) reads catalog/*.yaml, one Backstage + # entity per file, as claims in Backstage's terms, each citing its file and line; each file is kept as an artifact in + # the volume kernel-artifacts. An unchanged file submits nothing; a changed one supersedes what it said + # (scripts/kernel.sh catalog). Profile kernel-admin: run, not kept running. + kernel-catalog: + profiles: [kernel-admin] + image: ghcr.io/openreplicant/kernel:${KERNEL_IMAGE_TAG:-main} + # --root /: files are recorded as substrate/catalog/ whatever the image's working directory (a different root + # re-keys every file: the kernel's D-125 lesson) + entrypoint: ["sh", "-c", "exec python3 -m encoder_backstage --project substrate --root / /substrate/catalog/*.yaml"] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + tmpfs: [/tmp] + environment: + DATABASE_URL: postgresql://kk_authenticator:${KK_AUTHENTICATOR_PASSWORD:?set in .env}@db:5432/kernel + KK_ARTIFACTS: /artifacts + volumes: + - ../catalog:/substrate/catalog:ro + - kernel-artifacts:/artifacts + depends_on: + db: {condition: service_healthy} + # The UI (S-140, S-141: Substrate's UI, no name of its own): the store's pages and maps, read-only, on the standard # library (ui/server.py) in the tools image. It sees only ui/ and reaches Postgres as db: the entities, pages and # maps from the kernel's read model (S-154), the companion's page from the substrate database. @@ -235,7 +258,7 @@ services: PYTHONDONTWRITEBYTECODE: "1" STORE_URL: postgresql://judge:${JUDGE_DB_PASSWORD:?set in .env}@db:5432/substrate JUDGE_KEY: ${JUDGE_KEY:?set in .env} - JUDGE_MODEL: local/${LLM_ALIAS:-gemma} + JUDGE_MODEL: local/${LLM_ALIAS:-slow} volumes: - ../environment:/app/environment:ro - ../voice:/app/voice:ro @@ -244,20 +267,22 @@ services: depends_on: db: {condition: service_healthy} - # The local model (plan step 5): llama.cpp's server on the GPU (as deploy/compose.nvidia.yaml gives it to Ollama: - # device nodes and the driver's libraries, no CDI, no root), serving LLM_MODEL from LLM_MODELS_DIR read-only. - # Reached only through the gateway (provider local). Started with the profile `llm` (COMPOSE_PROFILES in .env). + # The local slow model (plan step 5, S-169): llama.cpp's server, serving LLM_MODEL from LLM_MODELS_DIR read-only, by + # default on the CPU and in RAM (LLM_ARGS -ngl 0) so the GPU stays free for the models that answer at once (llm-fast, + # tts). The GPU's device nodes and driver libraries are still given (as deploy/compose.nvidia.yaml gives them to + # Ollama: no CDI, no root) for a machine that wants layers there. Reached only through the gateway (provider local). + # Started with the profile `llm` (COMPOSE_PROFILES in .env). llm: profiles: [llm] - image: ${LLM_IMAGE:-ghcr.io/ggml-org/llama.cpp:server-cuda12-b12098} + image: ${LLM_IMAGE:-ghcr.io/ggml-org/llama.cpp:server-cuda12-b12627} cap_drop: [ALL] security_opt: [no-new-privileges:true] restart: unless-stopped entrypoint: ["sh", "-c", "exec /app/llama-server -m \"/models/$$LLM_MODEL\" --host 0.0.0.0 --port 8080 --alias \"$$LLM_ALIAS\" --jinja $$LLM_ARGS"] environment: LLM_MODEL: ${LLM_MODEL:-} - LLM_ALIAS: ${LLM_ALIAS:-gemma} - LLM_ARGS: ${LLM_ARGS:--ngl 999 --cpu-moe -c 16384 -ctk q4_0 -ctv q4_0 -fa auto} + LLM_ALIAS: ${LLM_ALIAS:-slow} + LLM_ARGS: ${LLM_ARGS:--ngl 0 --no-op-offload -t 6 -c 16384 -b 512 -ub 128 -ctk q4_0 -ctv q4_0 -fa on} devices: - /dev/nvidia0 - /dev/nvidiactl @@ -274,6 +299,36 @@ services: interval: 10s retries: 60 + # The local fast model (S-169): a small model wholly on the GPU for what must answer at once (the voice head's replies, + # quick tool calls); the slow model takes the bigger jobs on the CPU. LLM_FAST_MODEL from LLM_FAST_MODELS_DIR, + # read-only; at the gateway as fast/LLM_FAST_ALIAS. Profile `llm`; empty LLM_FAST_MODEL: it is not started. + llm-fast: + profiles: [llm] + image: ${LLM_IMAGE:-ghcr.io/ggml-org/llama.cpp:server-cuda12-b12627} + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + restart: unless-stopped + entrypoint: ["sh", "-c", "[ -n \"$$LLM_MODEL\" ] || { echo 'LLM_FAST_MODEL is empty: no fast model'; exec sleep infinity; }; exec /app/llama-server -m \"/models/$$LLM_MODEL\" --host 0.0.0.0 --port 8080 --alias \"$$LLM_ALIAS\" --jinja $$LLM_ARGS"] + environment: + LLM_MODEL: ${LLM_FAST_MODEL:-} + LLM_ALIAS: ${LLM_FAST_ALIAS:-fast} + LLM_ARGS: ${LLM_FAST_ARGS:--ngl 999 -t 2 -c 32768 -fa on -ctk q8_0 -ctv q8_0} + devices: + - /dev/nvidia0 + - /dev/nvidiactl + - /dev/nvidia-uvm + - /dev/nvidia-uvm-tools + volumes: + - ${LLM_FAST_MODELS_DIR:-/nonexistent}:/models:ro + - ${NVIDIA_LIB_DIR:-/usr/lib/x86_64-linux-gnu}/libcuda.so.1:/usr/lib/x86_64-linux-gnu/libcuda.so.1:ro + - ${NVIDIA_LIB_DIR:-/usr/lib/x86_64-linux-gnu}/libcuda.so.1:/usr/lib/x86_64-linux-gnu/libcuda.so:ro + - ${NVIDIA_LIB_DIR:-/usr/lib/x86_64-linux-gnu}/libnvidia-ml.so.1:/usr/lib/x86_64-linux-gnu/libnvidia-ml.so.1:ro + - ${NVIDIA_LIB_DIR:-/usr/lib/x86_64-linux-gnu}/libnvidia-ptxjitcompiler.so.1:/usr/lib/x86_64-linux-gnu/libnvidia-ptxjitcompiler.so.1:ro + healthcheck: + test: ["CMD-SHELL", "[ -z \"$$LLM_MODEL\" ] || curl -sf http://127.0.0.1:8080/health"] + interval: 5s + retries: 60 + # Text-to-speech on the GPU (S-150): Kokoro-FastAPI (Apache-2.0; espeak-ng inside, S-146), the owner's local # copy of ghcr.io/remsky/kokoro-fastapi-gpu:latest (v0.10.0, image fed40d86539c), beside the local model. The voice # head uses it when TTS_URL is set and falls back to Kokoro on the CPU when it does not answer. Profile `voice`. @@ -318,7 +373,12 @@ services: VOICE_STYLE: ${VOICE_STYLE:-af_heart} VOICE_THREADS: ${VOICE_THREADS:-4} VOICE_SILENCE_S: ${VOICE_SILENCE_S:-0.6} - LLM_NAME: local/${LLM_ALIAS:-gemma} + LLM_NAME: ${VOICE_MODEL:-local/${LLM_ALIAS:-slow}} + VOICE_ROUTER: ${VOICE_ROUTER:-tools} + SEARCH_URL: http://search:8080 + VOICE_NOTES_ROOT: /workspace + TZ: ${TZ:-UTC} + EMBED_MODEL: ${STORE_EMBED_MODEL:-ollama/qwen3-embedding:0.6b} TTS_URL: ${TTS_URL:-} AVATAR_FILE: ${AVATAR_FILE:-} STORE_URL: postgresql://postgres:${POSTGRES_PASSWORD:?set in .env}@db:5432/substrate @@ -326,12 +386,34 @@ services: - voice-models:/models - ../voice:/app/voice:ro - ../.state/avatar:/avatar:ro # AVATAR_FILE lives here, never committed (S-160) + - worker-workspace:/workspace # its quick tools read and write notes/ there, beside the worker (S-171) + group_add: ["65534"] # the worker's group: notes/ is group-writable (the worker sets it up) ports: - "127.0.0.1:${VOICE_PORT:-8110}:8110" depends_on: db: {condition: service_healthy} gateway: {condition: service_started} + # Web search for the voice head's `search` tool (S-171): SearXNG (AGPL-3.0, the owner's choice: fetched at setup, run + # unmodified in its own container and reached over HTTP, as S-146 treats a GPL part), image pinned (2026.11.8, the newest + # at least two weeks old on 2026-11-22). It forwards queries to public search engines. No host port: only the compose + # network reaches it. Settings in deploy/searxng/settings.yml (the JSON API on, no limiter). Profile `voice`. + search: + profiles: [voice] + image: ${SEARCH_IMAGE:-docker.io/searxng/searxng:2026.11.8-74418092d} + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + restart: unless-stopped + environment: + SEARXNG_SECRET: ${SEARXNG_SECRET:?set in .env} + FORCE_OWNERSHIP: "false" + # podman 4.9's network DNS does not answer an AAAA query for a name with no IPv6 address, so every lookup of such an + # engine stalled 5 s and SearXNG's 3 s engine timeout lost them all (S-171); a 1 s resolver wait caps the stall + dns_opt: ["timeout:1", "attempts:1"] + volumes: + - ./searxng/settings.yml:/etc/searxng/settings.yml:ro + - search-cache:/var/cache/searxng + # The worker (plan step 1, S-163): an offline agent on the local model. Its loop is ours (environment/worker.py, S-162): # the model only through the gateway as worker:loop (local models only), the kernel's `memory` profile over stdio # (kernel-mcp, in the kernel's image this one is built on) under its own kernel login (scripts/kernel.sh login worker), @@ -356,7 +438,7 @@ services: PYTHONPATH: /app GATEWAY_URL: http://gateway:8080 WORKER_KEY: ${WORKER_KEY:?set in .env} - WORKER_MODEL: ${WORKER_MODEL:-local/${LLM_ALIAS:-gemma}} + WORKER_MODEL: ${WORKER_MODEL:-local/${LLM_ALIAS:-slow}} WORKER_MAX_STEPS: ${WORKER_MAX_STEPS:-8} WORKER_CONTEXT_TOKENS: ${WORKER_CONTEXT_TOKENS:-11000} WORKER_REASONING: ${WORKER_REASONING:-} @@ -373,6 +455,9 @@ services: gateway: {condition: service_started} volumes: + kernel-artifacts: + name: ${KERNEL_ARTIFACTS_VOLUME:-substrate_kernel-artifacts} # the kernel's artifact store: catalog files as they were read + search-cache: worker-workspace: name: ${WORKER_VOLUME:-substrate_worker-workspace} # the only place its file tools reach voice-models: diff --git a/deploy/searxng/settings.yml b/deploy/searxng/settings.yml new file mode 100644 index 0000000..ff2f8ea --- /dev/null +++ b/deploy/searxng/settings.yml @@ -0,0 +1,19 @@ +# SearXNG for the voice head's `search` tool (S-171): the defaults, plus the JSON API, no limiter (only the voice head +# reaches it, on the compose network; no port on the host) and no image proxy. The secret comes from SEARXNG_SECRET. +use_default_settings: true +general: + instance_name: "substrate search" +server: + secret_key: "overridden-by-SEARXNG_SECRET" + limiter: false + public_instance: false + image_proxy: false +search: + safe_search: 0 + autocomplete: "" + formats: + - html + - json +outgoing: + # engines get 5 s (the default 3 s lost them to slow DNS lookups on podman 4.9's network, S-171) + request_timeout: 5.0 diff --git a/deploy/secrets.txt b/deploy/secrets.txt index d2b56e1..f2e75e0 100644 --- a/deploy/secrets.txt +++ b/deploy/secrets.txt @@ -17,7 +17,9 @@ COMPANION_AUTHOR_KEY key:sk-bf-:20 the companion's author of components JUDGE_KEY key:sk-bf-:20 the judge's key at the gateway (the local model only; S-151) WORKER_KEY key:sk-bf-:20 the worker's key at the gateway (the local model only: an offline agent; S-163) WORKER_DB_PASSWORD token:24 the worker's container's login to the store's database (worker: publish, act, its queues; S-163) +EXPERIENCE_KEY token:32 the key the assistant's experience is encrypted under (env.experience, S-182); losing it loses the stored text WORKER_KERNEL_URL provided the worker's kernel login (scripts/up.sh copies it from scripts/kernel.sh login worker; the container cannot read the 0600 file) JUDGE_DB_PASSWORD token:24 the judge's login to the store's database (judge: reads the record, records verdicts; environment/sql/007) +SEARXNG_SECRET token:32 signs SearXNG's sessions (compose service search, S-171) KK_AUTHENTICATOR_PASSWORD token:24 the Knowledge Kernel's one login for its services; the UI reads the kernel's read model through it (S-154) KK_JWT_SECRET token:32 signs the kernel's tokens for its HTTP MCP (kk token); not used by the stdio profile diff --git a/docs/archive/framework-s125.md b/docs/archive/framework-s125.md new file mode 100644 index 0000000..3ff411d --- /dev/null +++ b/docs/archive/framework-s125.md @@ -0,0 +1,431 @@ +# The framework + +What Substrate is built as (S-125). `docs/plan.md` says what is built next; this page says what shape it all +takes. Marked **decided** where the owner has agreed, **open** where not. + +## In one paragraph + +An **environment** is data in Postgres: streams of readings, the objects they are about, and the actuators that +can be acted on. With nothing else configured it is a **pass-through**: every event goes to an LLM harness +(Claude Code, on any model through the gateway), which acts through gated actuators, and everything is recorded. +From that record, the LLM **distills components** (reactive handlers for patterns in one event or several +aligned ones), each carrying a **card**: its intent, trigger, action, the cases it came from, its KPIs and tests. +A **judge** outside the author's reach tests the card on recorded cases the author never saw, and only then does +the component join the environment. What a component cannot handle goes back up to the LLM, and from there to a +person. Environments nest: a child is an object in its parent's environment. The UI is where people watch +and decide. + +## Signals and claims (decided, S-126) + +- A **signal** is what a source reports: a reading, an event, a message, a snapshot, a transcript. It is kept + whole and is no one's opinion; if it is wrong, the sensor is broken. Parsing a signal into fields leaves it a + signal. +- A **claim** is an interpretation of one or more signals (or other claims) by an **interpreter** that answers + for it: the LLM, a distilled component, or a person. It cites what it rests on, and can be wrong even when + every signal is right, which is why it is reviewed, judged and retracted. + +The test: anything that could be wrong for reasons other than a broken sensor is a claim. Streams carry signals; +the claim log holds claims; actions cite the claims that justify them (under pass-through the LLM may act straight +from signals, and records its interpretation as claims). Interpreters are components, so a distilled interpreter +has a card and its claims carry its name. A person's statement is their claim; the interview transcript is the +signal. + +*Where the store lives moved to the Knowledge Kernel (S-153); the model below is still the target, reached through the kernel's D-101.* + +**The store (decided, S-135): Wikibase's data model in Postgres, with OpenWiki's pinned evidence.** An +**entity** (an item, or a property, itself an entity) has **statements**: a property, a typed value, qualifiers, +a rank (preferred, normal, deprecated) and **references**. A reference says who stated it (a parser's run, an +interpreter and its version, a person, a rule and its premises) and which **span** of a signal it rests on; a span +carries its text's hash and a vector. Every edit is a **revision** of its entity. The usable value is Wikidata's: +preferred if any, else normal. Constraints are statements on properties, checked and reported, never blocking. A +Markdown page per entity, regenerated from its statements, is what people and agents read. When a span's hash +changes, what cites it, and what was derived from that, is flagged with no model call. Under this model a claim is +a statement whose reference is an interpreter: it enters at normal rank and is preferred or deprecated by review. +What a parser wrote is a statement too, with a parser's reference, and nobody reviews it: if it is wrong, the +parser is fixed and rerun. + +**A claim's fields**, after Graphiti's data model ([graphiti](https://github.com/getzep/graphiti), Apache-2.0; +its `nodes.py` and `edges.py` read, S-129), with what it lacks added. Graphiti keeps raw input as episodes (our +signals) and facts as edges with an `episodes` list, and is bi-temporal: `valid_at` and `invalid_at` (when the +fact held), `created_at` and `expired_at` (when the store learned and dropped it). On a contradiction an LLM only +nominates candidates; code decides by dates. Kept: the four times, and "the model nominates, code decides". Not +kept: it overwrites an edge's times in place, has delete paths, records no interpreter, no confidence and no +review status, and links provenance by a list of strings. So a claim here carries `cites` (signals or claims, by +foreign key), `interpreter` (who, and which version of a component), `confidence`, `status` (proposed, +accepted, retracted) and `retracted_by`, and a change of belief is a new claim, never an edit. Graphiti has no +Postgres backend, so it is a model to borrow from, not a part to add. + +## The parts (S-153) + +| Part | Repository | Does | Is not | +| --- | --- | --- | --- | +| **Substrate** | this one | the environment, streams and gated actuators, pass-through, the record, components and their cards, the hierarchy, the gateway, the UI | a harness: Claude Code is the harness | +| **The store** | [Knowledge Kernel](https://github.com/OpenReplicant/kernel) | items and claims with provenance, each caller its own Postgres login under row-level security, the review lane, recall (BM25 and pgvector), reasoning (conclusions with premises, truth maintenance), the agent's MCP tools | Substrate's own `store/` package, retired in S-156 (`docs/store-to-kernel.md`) | +| **The cognitive layer** | [MetaSoar](https://github.com/OpenReplicant/MetaSoar) for the hypothesis and its write-up; its experiments run in Substrate's `experiments/` (S-181) | how an agent inside an environment perceives, attends, predicts and learns: perception from pixels, the workspace and attention, simulators and surprise, a lockstep runtime for worlds faster than the wall clock; its hypothesis and the predictions that would show it wrong (`docs/cognitive-model.md` there) | required: pass-through works without it, and each of its parts is judged against pass-through like any component | +| **The judge** | an interface here; Morphogen is one filler | a card and a candidate in, a verdict out, on cases the candidate's author cannot read | a framework; Morphogen is optional | + +## The environment is data (decided) + +Everything is in one Postgres, so the environment, the record and the judge's cases are the same data. + +| Need | Mechanism | +| --- | --- | +| The source of truth | signals kept whole (pgmq's archive and the readings they become), and the claim log: claims (subject, property, value, the signals or claims cited, the interpreter, time, confidence). Append-only; a claim is retracted, never erased | +| Streams in | pgmq topics. A signal is published with `pgmq.send_topic` under a routing key `..` (dot-separated, so a child's keys sit under its parent's); logged queues, archived after handling, so a stream can be replayed | +| Sensing, in parallel | each subscriber (an encoder, a reactive handler, the LLM's channel) owns a queue bound to the patterns it watches (`pgmq.bind_topic`; `*` one segment, `#` any). Fan-out is pgmq's; no subscriber takes a message from another | +| Acting, in series | one pgmq queue per actuator, read by the one process that applies it. Who may write to it, and through which gate, is the arbitration | +| Gates | per action kind: `free` (applied), `propose` (into the review lane for a person), `deny`. Live work starts at `propose` | +| Escalation | a topic too: `.escalate`, which the level above subscribes to | +| Views | pgGraph's projection, Ontop's SPARQL over the ontologies, full text, pgvector: read-only and rebuildable from the log | + +Reactive logic runs in **handler processes**, not database triggers, so that each one is a component with a card, +a version and a verdict, and can be judged and rolled back. (Memgraph triggers over a property graph were the +earlier design; the graph is now a view of the claims, not the store.) + +Raw readings are kept, so interpreting them into claims is itself a component: at first the LLM reads the raw +data and decides what it means; when it keeps deciding the same way, it writes an encoder with a card. + +## Pass-through is the default (decided) + +With no components, the environment hands every event to the harness. The harness is **Claude Code**, which +runs on any model the gateway serves and already has tools, MCP, hooks, skills, subagents, permissions and +context management; Substrate does not rebuild any of them. + +- **In:** a Claude Code channel (an MCP server that pushes events into a running session) subscribed to the + environment's topics. +- **Look around:** the store's MCP server, to query objects, claims and history. +- **Out:** actions written to actuator queues through MCP, under the gates; hooks and permissions enforce them. + +Pass-through is useful on its own, and it is the **baseline every other layer is measured against**. + +### The channel, as documented (read 2026-11-17, S-129) + +From [channels](https://code.claude.com/docs/en/channels) and the +[channels reference](https://code.claude.com/docs/en/channels-reference). Research preview; the flag syntax and +protocol "may change", so the version that works is pinned when it is built. + +- **Shape:** a local MCP server, spawned by Claude Code over stdio, declaring + `capabilities.experimental['claude/channel']`, and sending `notifications/claude/channel` with `content` (the + body) and `meta` (attributes; keys letters, digits and underscores only, others silently dropped). Claude sees + each event as a `` tag; events queued during a turn arrive together on the next. Its + `instructions` string tells Claude what the attributes mean. +- **No acknowledgement and no persistence:** a notification is fire-and-forget, and nothing survives a closed + session. So the durable side is ours: the channel reads its pgmq queue with a visibility timeout and does not + archive a message until Claude calls an `ack(msg_id)` tool (or acts on it); an unacknowledged message + reappears and is delivered again. +- **Two-way:** replies and actions are ordinary MCP tools on the same server (or the store's). +- **Permission relay** (`claude/channel/permission`): Claude Code sends `permission_request` (`request_id`, + `tool_name`, `description`, `input_preview`) and accepts `allow` or `deny` back; first answer wins. This can be + where a `propose` gate meets the review lane: the UI shows the request and a person's decision goes back + through it. Anyone who can answer the relay can approve tool use, so it is declared only for an authenticated + path. +- **Enabling it:** a server of our own needs `claude --dangerously-load-development-channels server:` + (a confirmation dialog; ignored with `-p` and through the Agent SDK), so pass-through runs as an interactive + session kept open (tmux or a user service). Team and Enterprise organizations must set `channelsEnabled`. +- **Untrusted input:** "An ungated channel is a prompt injection vector." Every signal from outside is data, + not instructions: the channel's `instructions` say so, senders are gated where a stream has senders, and + actions stay behind the gates. +- **Unknown, to test first:** whether channels work when Claude Code runs on a non-Anthropic model through the + gateway (`ANTHROPIC_BASE_URL`); the docs require a claude.ai login or a Console API key and say nothing of + other endpoints. If they do not, pass-through on a local model needs another way in (a hook that injects + pending events, or polling through a tool). Also unstated: rate limits, maximum payload, reconnects. +- **Known preview bug:** a server negotiating protocol revision 2026-07-28 does not register on the v2 MCP client + runtime; pin the SDK's protocol revision. + +### The harness profile is a component, sized to the model (S-134) + +Claude Code can be cut down so a small model sees only what it needs (read 2026-11-17 in the +[CLI reference](https://code.claude.com/docs/en/cli-reference.md) and [permissions](https://code.claude.com/docs/en/permissions.md)): +`--tools ""` (or a short list) removes built-in tools from the model's context; a bare-name deny +(`--disallowedTools "Edit"`, `permissions.deny`) removes a tool's schema, while a scoped one only blocks calls; +`--strict-mcp-config --mcp-config FILE` loads exactly the listed MCP servers; `--system-prompt-file` replaces the +system prompt (whether that drops the built-in tool instructions is undocumented, so it is tested); and +`CLAUDE_CODE_DISABLE_AUTO_MEMORY`, `CLAUDE_CODE_DISABLE_CLAUDE_MDS`, `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS`, +`CLAUDE_CODE_DISABLE_WEB_FETCH` and `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` drop context. `--bare` and +`--safe-mode` also skip MCP, which the channel needs, so they are not used. Subagents take their own `tools` +allowlist and `model` (background subagents keep only MCP tools). The model is set by `ANTHROPIC_MODEL`, and +Claude Code's background calls by `ANTHROPIC_DEFAULT_HAIKU_MODEL`, both at the gateway. Anthropic states it does +not support routing Claude Code to non-Claude models through a gateway ([LLM gateway](https://code.claude.com/docs/en/llm-gateway.md)), +so on a local model the first test is whether channels deliver, tool calls hold, and the replaced prompt works. + +A **profile** (tool set, prompt, MCP servers, context switches, model) is a component with a card: the lean one +for a small local model (only the channel's and the store's tools, a short prompt), richer ones for larger models, +each measured on the same record. + +## Components can be pipelines: adaptive perception (decided as a shape) + +A component need not be a rule. When a stream has no handler, the LLM can build one: probe the signal, decide +what it is, and install a pipeline that turns it into something it can use. Example: a raw audio stream arrives +unhandled; the LLM samples it, and either pipes it to its own audio input if the model has one, or installs a +classifier (speech, music, noise) and, for speech, a speech-to-text model chosen from the catalog (the `research` +skill), writing transcripts as signals and what they mean as claims. Each stage is a component with a card, so +each can be tested, swapped for a cheaper or better one, and judged against the stage it replaces. The +environment's senses grow to fit its streams and its model: embodiment that adapts. + +## Maps, roles and catalogs (decided, S-139) + +Any thing, software or not, is taken apart the same way: a whole *has part* parts, each playing a **role** there; +a role *requires interface* what anything filling it must provide, and a part *provides interface* it. The +interface is what makes parts interchangeable, so it is named exactly enough to check. A **catalog** is where +candidates come from; `alternatives` lists what provides everything a role requires. A whole *has goal* +measurable goals; a trial's results are *measurements*, and whether a candidate is better is a judge's +*verdict*, a statement whose reference is the judge (Morphogen, when it is back in the build). All of it is +statements in the store, written by the `map` and `catalog` skills through the store's MCP tools, so a map is +reviewed, flagged and corrected like anything else. The components below are this applied to an +environment's own parts. + +## Components and their cards (decided) + +A component is a handler that subscribes to a pattern and does something: writes claims, proposes an action, +or escalates. Its kind may be a rule, a script, a model call, a Claude Code session, or a person. Components come +from the LLM distilling its own repeated decisions (or from a person), and each carries a **card**: + +| Field | Says | +| --- | --- | +| intent | what it is for, in a sentence the owner can check | +| trigger | the pattern it fires on: one signal or claim, or several aligned in time | +| action | what it does, through which actuator | +| source cases | the recorded events it was made from, each with what the LLM or person did | +| KPIs | what it must hold to: agreement with what it replaces, cost per event, latency, override rate | +| tests | cases it must handle, and cases where it must not fire | + +**Lifecycle:** proposed → judged → active at `propose` → `free` once trusted → demoted when it drifts (overrides +climb in the review lane). Every version is kept, so a component can be rolled back or compared against the LLM +it replaced. + +**What CogRec shows, and what it lacks** ([arXiv 2512.24113](https://arxiv.org/abs/2512.24113), read in full, +S-129). A recommender: Soar handles what its rules cover; on an impasse, a summary of working memory goes to an +LLM (DeepSeek-V3), and the answer is parsed into a condition-action pair that Soar's chunking compiles into a +rule. It beat the best baseline by 4–9% on three datasets, and its rate of LLM calls fell to a low plateau as +rules accumulated; without chunking it stayed near the plain LLM. But no seeds, variance or significance tests +are reported, and learned rules are never tested, scoped or removed: they are "permanently internalized". That +is the gap the card and the judge fill. Taken from it: the escalation carries a structured summary of the +state, not the raw context; the answer is parsed into trigger and action before it becomes a component; and +the **rate of LLM calls per event** is a KPI of the whole environment, the number that should fall as it learns. + +**Confidence is measured, not stated.** A component's confidence is the agreement the judge measured on held-out +cases, within the scope its trigger covers. The LLM gets an event when no trigger fires, when the event falls +outside what the component was judged on, or when the component has been demoted. (Cascade research finds +routing only as good as its quality estimate; this is how the estimate is earned.) + +## The judge is an interface (decided; its filler is open) + +A card and a candidate go in; a verdict comes out, with each KPI's result, the case counts, and pass or refuse, +appended to a log. What it needs beyond ordinary CI is two things: **cases the author cannot read** (a slice of +the record held by another role: Postgres row-level security, or a separate user for the stronger version), and +**comparison against the incumbent**, not pass/fail alone. + +- **First filler:** a script run as the judge user, running the card's tests and the held-out slice. +- **Candidates for the runner** (rule 3, not yet searched): Inspect AI, promptfoo, DeepEval. +- **Morphogen** is frozen as an option behind the same interface (S-127). Its later overhaul, when the owner + starts it, is toward a standard CI workflow built from components (a runner, held-out cases, a verdict log, + statistics as a step) rather than one custom program. + +## It is an actor model on Postgres (a description, not a runtime to build) + +Each component is an actor: it owns a mailbox (its pgmq queue), handles one message at a time, and sends +messages (`send_topic`); the parent environment supervises its children, as an Erlang/OTP supervisor does. Two +differences from a pure actor model: state is shared, not private (the claim log is a blackboard every actor +reads), and an actor is judged before it runs live. So: actors for messaging, a blackboard for state. + +What follows from that: + +- **Borrow the semantics, not a runtime:** one mailbox per actor, per-mailbox order, supervision, retries with + visibility timeouts. pgmq gives all of it; no actor framework is added. +- **Side effects must be idempotent:** a retried message re-applies its action. Writes to the database are + transactional; anything outside (an email, an API call) needs an idempotency key on the actuator. +- **Postgres has a rate ceiling:** work-level events (tickets, messages, changes) are fine; high-rate sensor + data is sampled or batched before it becomes a signal, or uses an unlogged queue where loss is acceptable. +- **Nearby tools** for durable steps on Postgres, if a component needs multi-step workflows: + [Absurd](https://lucumr.pocoo.org/2025/11/3/absurd-workflows/) (SQL-only, works with pgmq), + [DBOS](https://dbos.dev/blog/making-postgres-queues-scale), Hatchet. Chosen by the research skill when needed. + +## The view: serializing the environment for the LLM (a component, tested per model) + +What the LLM sees is a rendering of the environment, and how it is rendered changes results: one study found +up to 40% differences between plain text, Markdown, YAML and JSON on the same task, with no format best across +models ([He et al. 2024](https://arxiv.org/abs/2411.10541), OpenAI models only). It also decides cost, through +the prompt cache. So the **view is a component with a card**, like any other, and is judged per model and per +arrangement. + +Its parameters: + +| Parameter | Choices | +| --- | --- | +| format | plain text, Markdown, YAML, JSON, XML tags, tables | +| content | signals, claims, or both; citations inline or by id | +| granularity | each signal, a summary per stream, deltas against a snapshot | +| order | by time, by object, by priority | +| time | absolute or relative; where timestamps sit | +| budget | how much fits before older content is summarized | + +**Cache layout (default):** stable first, changing last, and nothing already sent rewritten: instructions and +the environment's schema (streams, objects, actuators), then a snapshot of the objects that matters, then the +events appended in order. Timestamps, tool sets and instructions that change mid-session break the cached prefix +([prefix-stability study](https://neurips.cc/virtual/2026/162685) finds a badly arranged loop can cost more than +no caching). The gateway already meters `tokens_cached` (S-106), so a view's cache rate is a KPI on its card. + +**Under pass-through** the view is two things Substrate controls: the format of the events a channel pushes, +and what the store's MCP tools return. Claude Code manages the rest of the context (compaction, its own cache +layout), and that stays its job. A self-lever lets the LLM ask for a different view (a summary instead of raw +signals), as a `propose`. + +## Environments nest (decided as a shape; built later) + +A child environment is an object in its parent's environment: + +- its **streams** are its escalations, KPIs, verdicts and activity, under its own routing keys, so the parent + subscribes with `.#`; +- its **actuators** are what the parent may do to it: start or stop it, change its configuration, approve or + retire its components, take over an event; +- its **gates** work as anywhere else: the parent changing a child's structure is `propose` until trusted. + +Escalation goes up a level at a time; only the top reaches a person. The **top level is the system itself**: the +map (objects: components, services, packages), the observer (streams: what runs) and interviews (intent). That is +where the map work done so far belongs. A child's whole configuration is a component with a card from the +parent's side, judged like any rule. + +**The one rule built in from the start:** an environment's interface (streams, objects, actuators, gates) is +exactly what a parent sees of it as an object, so nesting needs no redesign. + +## The chimera: the root and its goals (decided, S-130) + +The root environment is the **chimera**: one system that finds components, or makes and changes them, as its +goals require. Every other environment is a child of it. Its goals, in the order they bind: + +1. **Values and constraints** (floor, changed only by the owner): the gates, the privacy rules for personal + streams (`docs/privacy.md`), the budgets, and what the judge holds. Nothing optimizes against these. +2. **The owner's preferences** (from what they say, in interviews and in the review lane, as their own claims). +3. **Self-optimization** (seed): lower cost and fewer LLM calls per event, fewer escalations to the owner, at + equal or better quality, every change judged against what it replaces. + +**Budgets** are a floor the owner sets (spend per day, per caller, per model) and signals the chimera reads (the +gateway's meter). Choosing a model or a compute placement within the budget is a self-lever; raising a budget +is always the owner's. + +**The children, in order:** the companion (a persistent voice and avatar assistant working in the background), +then embodied environments it acts in: VRChat or Virt-A-Mate for presence as a 'hologram', ROS2 for a robot in +simulation and later in operation. Each is nested by the interface rule, so the companion acts in them through +their actuators under the same gates and budget. A personal stream (the owner's voice, messages, files) carries +the privacy floor from its first signal. + +### Privacy: adjustable, with defaults that flag and prevent exfiltration (decided, S-131) + +The rules in `docs/privacy.md` are the defaults, and they hold until the owner loosens one for a named stream +(a review-lane decision: who, when, why). The default is to **flag and prevent**: personal content does not go +to a hosted model, and an attempt is refused and flagged rather than silently allowed. The gateway is the one +place that can enforce this, so every model call goes through it, **Claude Code's included** +(`ANTHROPIC_BASE_URL` at the gateway), and each caller's key names the providers it may reach. Loosening P3 or +P4 for the companion's text is then one change to one key, visible in the record. + +### Placement is a trade-off the system can choose (decided, S-131) + +On the owner's machine today (a GTX 1070, 8 GB, weights already partly offloaded to system RAM), each part runs +on the GPU or the CPU, at a cost in latency: today the slow model (Inkling 2 Mini) on the CPU, the fast model (LFM3 +1.7B) and speech on the GPU (S-169), where S-131 had Gemma 4 for one local model. +These are parameters on each component's card (placement, model, quantization), measured for latency, quality +and memory, and choosing among them within the budget is a self-lever; the owner can pin any of them. + +### The browser client is an environment (decided as a shape, S-131) + +The UI's browser client is where the owner is, so it is an environment of its own, a child of the companion: + +- **Sensors** from browser APIs: microphone, camera, text, and others as needed (screen, location), each off + until the owner turns it on, each a personal stream under the privacy floor. +- **Actuators:** the speaker, the avatar's rendering, the page itself (messages, notifications, the review lane). +- **Transport:** today the shell gets Server-Sent Events of changed ids (`NOTIFY` on `wb_events`) and sends by + HTTP. Media needs a two-way binary path (a WebSocket, or WebRTC if latency demands it) on the UI's server. +- **Rate:** raw audio and video do not go through pgmq frame by frame (Postgres's rate ceiling). The browser's + media goes straight to its pipeline; what the pipeline makes (an utterance, a transcript, a detection) is the + signal published to the topics, and raw media is kept, if at all, as files under the retention rule (P7). + +**Built as its own package, not inside the UI (S-132).** The UI's live events stay as they are. The browser +environment is a small JavaScript library dropped onto any page (the UI's page is the first host) that +declares what the browser offers, sensors and actuators each with a schema, the way an MCP server declares its +tools; and a small bridge on the server that takes one WebSocket from it and connects it to pgmq (signals out to +topics, actuator queues in; raw media to its pipeline). Every embodied child is the same pattern: an adapter from +a native API (the browser's, VRChat's OSC, ROS2) to topics and queues. The declarations follow WebMCP's tool +shape (`document.modelContext`; a draft W3C community report in a Chrome origin trial, not called by mainstream +agents as of May 2026), so the library can register there later without depending on it now. + +**The avatar's actuators are defined once:** `speak` (audio, optional visemes), `express` (name, weight), +`look_at`, `gesture`; each embodied environment fills them its own way. First filler, in the browser: three.js +with `@pixiv/three-vrm` (versions pinned when built), idle motion, and the mouth driven by speech volume through +VRM's expression presets (`aa`, `ih`, `ou`, `ee`, `oh`) rather than a jaw bone, so any VRM model works; blink +and look-at from the same expression manager. Later: visemes from the text-to-speech's phoneme timings, if +Kokoro's Rust implementation provides them. + +**Mixed reality on the Quest 3 is the same environment on the headset (S-133).** An `immersive-ar` WebXR +session with passthrough gives, as sensors: plane detection with semantic labels, mesh detection, hit testing +(on Meta's Depth API since Horizon Browser 40.4), persistent anchors, depth sensing (mostly the GPU path), and +head and hand pose. The headset runs SLAM itself; its poses and anchors are signals, so SLAM is never built. +Camera pixels are the open question: Meta's Passthrough Camera API is native (Android Camera2, Horizon OS v74+); +WebXR `camera-access` is reportedly refused for `immersive-ar` (Horizon OS v85); a "headset cameras" website +permission and `getUserMedia` reportedly work but are not in Meta's developer docs. Tested first on the device; +if the browser cannot have the camera, a small native Quest app is one more adapter onto the same topics. The +avatar gains `move_to` (an anchor or point), `place_on` (a plane) and `look_at` (a person or object) for presence +in the room. Recognition (objects, activity, pose, face, gaze) is perception pipelines: light and fast on the +headset, rich and slow on the PC's GPU from frames sent at a low rate; their output is claims, and the companion +reasons over claims, not pixels. Camera frames from inside the owner's home are personal under the privacy +defaults: local models only, retention bounded. + +### Perception pipelines trade interpretability against refresh rate + +Every pipeline sits somewhere between fast and shallow and slow and rich, and can run both at once: + +| | Fast path | Slow path | +| --- | --- | --- | +| Hearing | voice activity, wake word, speaker turn | speech-to-text, then what was meant (claims) | +| Sight | motion, presence, face or hand landmarks, many times a second | a vision model's description or answer, a frame every few seconds or on demand | + +The fast path's signals decide when to spend on the slow one (someone spoke; something moved), and the LLM can +ask for the slow path directly. The rates, models and the switching rule are card parameters, so the balance is +measured per machine and per task rather than fixed. Speech candidates named by the owner: **Kokoro** (a Rust +implementation) for text-to-speech and **NVIDIA Parakeet TDT** for speech-to-text; versions, licences and +CPU latency are checked with the `research` skill before they are pinned (rules 1, 3, 6). + +## Assumptions, as parameters + +Each layer is switched on per environment and has to beat pass-through on the same work, on quality, cost or how +much reaches a person. A layer that does not stays off. + +| Layer | Its assumption | +| --- | --- | +| Raw readings into claims | encoding helps more than it loses | +| Reactive handlers, in parallel | cheap pattern matching takes load off the LLM without missing things | +| Escalation filtering | the LLM judges better with less in its context, and can query the rest | +| The view's format and layout | a given rendering suits a given model; differs per model and arrangement | +| Serial arbitration per actuator | needed once there is more than one actor | +| Self-levers (subscribe, mute, add or retire a handler, set a threshold) | the LLM tunes its own setup well; structure changes are `propose` | +| Nesting | splitting off a child lowers cost or escalations without losing quality | + +## Prior art + +From one round of searches (2026-11-17), mostly abstracts; CogRec, Graphiti's code and Global Workspace Agents +were then read in full (S-129). + +| Part | Closest work | +| --- | --- | +| Shared space, broadcast | blackboard systems with LLMs, the ones with results: [LbMAS](https://arxiv.org/html/2507.01701v1), [Google's data-discovery blackboard](https://arxiv.org/abs/2510.01285v2). [Global Workspace Agents](https://arxiv.org/html/2604.08206) (2026), read in full: a design with no evaluation at all, and a serial four-phase loop with fixed roles, not parallel subscribers; ideas only (an explicit "respond or think more" tag from an arbiter; compressing short-term memory into a retrievable long-term store past a threshold) | +| Distilling LLM decisions into rules | [CogRec](https://arxiv.org/abs/2512.24113) (Soar chunking of LLM answers; results, but rules never tested or removed); [NL2GenSym](https://arxiv.org/pdf/2510.09355v1); [LATM](https://arxiv.org/abs/2305.17126v2) | +| Claims with provenance, over time | [Graphiti](https://github.com/getzep/graphiti) (episodes, bi-temporal facts; no interpreter, confidence or review; times overwritten in place) | +| Rules written by an LLM, run without it | [llm-trigger](https://github.com/c4pt0r/llm-trigger); [LLM4CEP](https://pure.uva.nl/ws/files/201121899/24-LLM4CEP.pdf); [reactive synthesis](https://arxiv.org/html/2402.16905v1). All start from a person's request, not from the observed stream | +| Cheap first, escalate | [FrugalGPT](https://www.emergentmind.com/papers/2305.05176); [routing and cascades review](https://web.stanford.edu/~shuhuiq/blog/review-routing-cascades.html) (no router clearly beat the trivial one on RouterBench) | +| Event logs, actors | [OpenHands events](https://docs.openhands.dev/sdk/arch/events); [AutoGen Core](https://www.mintlify.com/microsoft/autogen/core/overview); [ambient agents](https://snowplow.io/blog/what-are-ambient-agents) | +| Environment interface | [OpenEnv](https://huggingface.co/docs/openenv/tutorials/mcp-environment) (reset/step/state with MCP tools, for training) | +| Self-change | [Letta](https://medium.com/@piyush.jhamb4u/stateful-ai-agents-a-deep-dive-into-letta-memgpt-memory-models-a2ffc01a7ea1); [Gödel Agent](https://arxiv.org/html/2410.04444v2); [Darwin Gödel Machine](https://arxiv.org/pdf/2505.22954) (archive of versions, empirical checks) | +| Frame | [CoALA](https://huggingface.co/papers/2309.02427); [cognitive architectures to language agents](https://arxiv.org/pdf/2607.23942) | +| Nesting (not yet searched) | Erlang/OTP supervision trees, Kubernetes controllers, holonic multi-agent systems, hierarchical RL | + +What appears new is the combination: pass-through as the baseline every layer must beat; components distilled +from the observed stream rather than from a request; reviewed claims rather than derived edges; and a real +harness rather than a research loop over a bare model API. + +## Open + +- What the LLM sees by default: everything, or what components escalate plus queries (recommended: the latter, + once there are components; everything under pass-through). +- The judge's runner: a script, or one of Inspect AI, promptfoo, DeepEval. +- The default view's format, until one has been measured on the first environment's model. +- Whether channels work with Claude Code on a non-Anthropic model through the gateway; the first thing to test. +- The first system to put an environment on. diff --git a/docs/compatibility/README.md b/docs/compatibility/README.md new file mode 100644 index 0000000..1a374e3 --- /dev/null +++ b/docs/compatibility/README.md @@ -0,0 +1,73 @@ +# What Substrate can talk to + +Substrate doesn't replace the runtime a system already uses. It describes the system as a map in the Knowledge +Kernel, and a **decoder** writes that map out in the runtime's own format; an **encoder** reads the runtime's state +and history back in (S-174). So a business that already runs Kubernetes, Camunda or Step Functions keeps it: the +map is the same, and only the decoder changes. Compose is the first runtime Substrate decodes to, because Substrate +itself runs on it. + +A licence decides only whether a part can be one of Substrate's **defaults** (rule 7: open licences; GPL only in +its own container, S-146). Any runtime below can be a **target** for a business that already runs it. + +The facts (formats, APIs, licences) were read from each project's docs and GitHub on 2026-11-22; +`runtimes.json` holds them with their sources, as entries for the kernel. The agent harnesses surveyed the same day +are in `scripts/trials/harness/candidates.json`. + +## Services and processes + +| Runtime | Native format | Read back | Licence | Default? | +| --- | --- | --- | --- | --- | +| Docker Compose / Podman | `compose.yaml` (Compose Specification, JSON schema) | `compose ps --format json` | Apache-2.0 | **yes (now)** | +| Podman Quadlet / `kube play` | Quadlet units; Kubernetes YAML (a subset) | Libpod REST API | Apache-2.0 | yes | +| process-compose | `process-compose.yaml` | REST (OpenAPI) | Apache-2.0 | lead candidate for processes | +| systemd | unit files | `systemctl show` | LGPL-2.1+ | yes | +| Kubernetes, k3s | YAML manifests (OpenAPI schema) | the API server | Apache-2.0 | yes | +| Docker Swarm | Compose files as stacks | `docker service ls` | Apache-2.0 | yes | +| s6, supervisord | service directories; INI | `s6-svstat`; XML-RPC | ISC; BSD-style | yes (check supervisord's clause) | +| Nomad | HCL jobspec | HTTP API | BUSL-1.1 | target only | + +## Workflow orchestrators + +| Orchestrator | How a workflow is defined | Interchange | Licence | Default? | +| --- | --- | --- | --- | --- | +| Flowable | BPMN 2.0 XML | **BPMN** | Apache-2.0 | yes | +| Kestra | YAML flows | | Apache-2.0 | yes | +| Argo Workflows | Kubernetes YAML | | Apache-2.0 | yes | +| Conductor | JSON definitions | | Apache-2.0 | yes | +| Node-RED | flow JSON | | Apache-2.0 | yes | +| Apache Airflow, Prefect, Dagster | Python | | Apache-2.0 | yes (code, not files) | +| Temporal, Hatchet | code (several languages) | | MIT | yes (code, not files) | +| Windmill | code | | AGPL-3.0 + proprietary EE | owner's call | +| Camunda 8 | BPMN 2.0 | **BPMN** | Camunda License | target only | +| n8n | visual, JSON | | Sustainable Use License | target only | +| Restate, Inngest | code | | BUSL-1.1, SSPL | target only | + +Where a workflow is code, not a file, Substrate can read its runs (encode) but writes it only through generated code +or the orchestrator's API; the file-defined ones (BPMN, YAML, JSON) are decoded directly. + +## Cloud services (targets) + +| Service | Format | +| --- | --- | +| AWS Step Functions | Amazon States Language (JSON) | +| Azure Logic Apps | Workflow Definition Language (JSON schema) | +| Google Cloud Workflows | YAML or JSON | +| AWS ECS; Google Cloud Run | task definitions (JSON); Knative Service YAML | +| Cloudflare Workflows; Azure Durable Functions | code | + +## Interchange standards + +| Standard | Describes | Note | +| --- | --- | --- | +| BPMN 2.0 (OMG) | processes | the kernel reads it (`encoder-bpmn`, the BBO pack); Camunda and Flowable run it | +| CNCF Serverless Workflow 1.1 | workflows | no orchestrator above confirmed as an adopter | +| Compose Specification | deployments | Substrate's own | +| OASIS TOSCA 2.0 | deployments | the kernel's `kk-tosca` mirror | +| CWL 1.2 | workflows | | +| W3C WoT Thing Description 1.1 | interfaces: affordances and protocol forms | blocks follow its shape (S-164) | +| OpenAPI 3.2, AsyncAPI 3.1 | HTTP and message APIs | AsyncAPI describes a queue link | +| CloudEvents 1.0 | event envelopes | | +| OpenTelemetry (GenAI conventions) | telemetry | | +| Model Context Protocol | agent tools | | +| W3C PROV-O | provenance | the kernel's | +| P-Plan | plans | **CC BY-NC-SA 2.0**: the owner decides how plans refer to it | diff --git a/docs/compatibility/runtimes.json b/docs/compatibility/runtimes.json new file mode 100644 index 0000000..8c42f12 --- /dev/null +++ b/docs/compatibility/runtimes.json @@ -0,0 +1,593 @@ +{ + "what": "Runtimes, orchestrators, cloud services and interchange standards Substrate can talk to: it decodes a map into a runtime's native format and encodes the runtime's state and history back (S-174). A licence decides only whether one can be a default part (rule 7); any of them can be a target for a business that already runs it.", + "licence_classes": { + "open": "OSI-approved; may be a default (GPL only in its own container, S-146)", + "source-available": "BUSL, SSPL, Sustainable Use, Camunda, FSL: a target, not a default", + "proprietary": "a cloud service: a target" + }, + "sources": [ + "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + ], + "service_and_process_runtimes": [ + { + "label": "Docker Compose", + "kind": "service runtime", + "catalog_ids": { + "github": "docker/compose" + }, + "licence": "Apache-2.0 (the Compose Specification, compose-spec/compose-spec)", + "licence_class": "open", + "definition_format": "compose.yaml (the Compose Specification)", + "format_spec": "https://github.com/compose-spec/compose-spec/blob/master/schema/compose-spec.json", + "deploy_and_read_api": "docker compose up; docker compose ps --format json (State, Health)", + "health": "healthchecks", + "telemetry": "engine Prometheus (metrics-addr); Compose itself: not found", + "notes": "the default; Substrate runs on it with Podman", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Podman", + "kind": "service runtime", + "catalog_ids": { + "github": "containers/podman" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "Quadlet units (.container, .pod, .kube ...); podman kube play takes Kubernetes YAML (a subset)", + "format_spec": "not found (Quadlet)", + "deploy_and_read_api": "Docker-compatible and Libpod REST APIs on a Unix socket; podman ps", + "health": "Quadlet HealthCmd", + "telemetry": "not found (a third-party OTel receiver)", + "notes": "the engine under Substrate's compose (rule 5)", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "process-compose", + "kind": "process runtime", + "catalog_ids": { + "github": "F1bonacc1/process-compose" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "process-compose.yaml", + "format_spec": "not found", + "deploy_and_read_api": "REST (OpenAPI), token PC_API_TOKEN; CLI start/stop/restart", + "health": "liveness and readiness probes", + "telemetry": "not found", + "notes": "lead candidate for processes (S-173)", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "systemd", + "kind": "service and process runtime", + "catalog_ids": { + "github": "systemd/systemd" + }, + "licence": "LGPL-2.1-or-later (core)", + "licence_class": "open", + "definition_format": "unit files (INI)", + "format_spec": "systemd.unit(5)", + "deploy_and_read_api": "systemctl show / status / is-active", + "health": "unit states, Type=notify", + "telemetry": "not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Kubernetes", + "kind": "service runtime", + "catalog_ids": { + "github": "kubernetes/kubernetes" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "YAML manifests", + "format_spec": "the OpenAPI spec in api/openapi-spec", + "deploy_and_read_api": "the API server (REST)", + "health": "liveness, readiness, startup probes", + "telemetry": "Prometheus /metrics; OTLP traces from components", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "k3s", + "kind": "service runtime", + "catalog_ids": { + "github": "k3s-io/k3s" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "Kubernetes manifests", + "format_spec": "Kubernetes'", + "deploy_and_read_api": "the Kubernetes API", + "health": "Kubernetes'", + "telemetry": "not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "HashiCorp Nomad", + "kind": "service and process runtime", + "catalog_ids": { + "github": "hashicorp/nomad" + }, + "licence": "BUSL-1.1", + "licence_class": "source-available", + "definition_format": "HCL jobspec (JSON accepted)", + "format_spec": "not found (JSON schema)", + "deploy_and_read_api": "PUT /v1/jobs, GET /v1/jobs", + "health": "HealthyAllocs / UnhealthyAllocs", + "telemetry": "Prometheus, StatsD and others; OTel not found", + "notes": "can be a target for a business that runs it; not a default (rule 7, S-173)", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Docker Swarm", + "kind": "service runtime", + "catalog_ids": { + "github": "moby/moby" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "Compose files (3.x) as stacks", + "format_spec": "the Compose Specification", + "deploy_and_read_api": "docker stack deploy; docker service ls", + "health": "not found", + "telemetry": "engine Prometheus", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "s6 / s6-overlay", + "kind": "process supervisor", + "catalog_ids": { + "github": "just-containers/s6-overlay" + }, + "licence": "ISC (s6); s6-overlay's not confirmed", + "licence_class": "open", + "definition_format": "service directories of scripts", + "format_spec": "not found", + "deploy_and_read_api": "s6-svstat", + "health": "not found", + "telemetry": "not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "supervisord", + "kind": "process supervisor", + "catalog_ids": { + "github": "Supervisor/supervisor" + }, + "licence": "BSD-style with a modification-notice clause (no SPDX id)", + "licence_class": "open (check)", + "definition_format": "INI [program:x]", + "format_spec": "supervisord.org/configuration", + "deploy_and_read_api": "XML-RPC over HTTP", + "health": "autorestart, startretries", + "telemetry": "not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + } + ], + "workflow_orchestrators": [ + { + "label": "Temporal", + "kind": "workflow orchestrator", + "catalog_ids": { + "github": "temporalio/temporal" + }, + "licence": "MIT", + "licence_class": "open", + "definition_format": "code (Go, Java, TypeScript, Python); no definition file", + "format_spec": "none", + "deploy_and_read_api": "SDK client (gRPC, port 7233)", + "health": "workflow history", + "telemetry": "OTel tracing in SDKs; Prometheus metrics", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Apache Airflow", + "kind": "workflow orchestrator", + "catalog_ids": { + "github": "apache/airflow" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "Python DAGs", + "format_spec": "none", + "deploy_and_read_api": "REST API", + "health": "task states", + "telemetry": "OTel traces ([traces])", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Argo Workflows", + "kind": "workflow orchestrator", + "catalog_ids": { + "github": "argoproj/argo-workflows" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "Kubernetes Workflow resource (YAML)", + "format_spec": "its CRD", + "deploy_and_read_api": "REST API server (Swagger)", + "health": "workflow status", + "telemetry": "metrics over OTLP and Prometheus", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Prefect", + "kind": "workflow orchestrator", + "catalog_ids": { + "github": "PrefectHQ/prefect" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "Python flows", + "format_spec": "none", + "deploy_and_read_api": "REST: create_flow_run, flow_runs/filter", + "health": "flow run states", + "telemetry": "not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Dagster", + "kind": "workflow orchestrator", + "catalog_ids": { + "github": "dagster-io/dagster" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "Python assets and jobs", + "format_spec": "none", + "deploy_and_read_api": "GraphQL (not verified)", + "health": "run states", + "telemetry": "not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Kestra", + "kind": "workflow orchestrator", + "catalog_ids": { + "github": "kestra-io/kestra" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "YAML flows; ZIP export/import", + "format_spec": "its flow schema", + "deploy_and_read_api": "REST: POST /api/v1/main/flows (YAML)", + "health": "executions", + "telemetry": "OTel: traces, metrics, logs", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Windmill", + "kind": "workflow orchestrator", + "catalog_ids": { + "github": "windmill-labs/windmill" + }, + "licence": "AGPL-3.0 (most), Apache-2.0 (clients), proprietary EE", + "licence_class": "open (AGPL) / mixed", + "definition_format": "scripts and flows in code", + "format_spec": "not verified", + "deploy_and_read_api": "OpenAPI", + "health": "jobs", + "telemetry": "OTLP tracing (Enterprise)", + "notes": "a target, not a default without the owner's licence call", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "n8n", + "kind": "workflow orchestrator", + "catalog_ids": { + "github": "n8n-io/n8n" + }, + "licence": "Sustainable Use License", + "licence_class": "source-available", + "definition_format": "visual editor, workflows as JSON", + "format_spec": "none", + "deploy_and_read_api": "public REST API (OpenAPI)", + "health": "executions", + "telemetry": "not found", + "notes": "a target only", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Camunda 8 (Zeebe)", + "kind": "workflow orchestrator (BPMN)", + "catalog_ids": { + "github": "camunda/camunda" + }, + "licence": "Camunda License v1", + "licence_class": "source-available", + "definition_format": "BPMN 2.0 (Modeler)", + "format_spec": "BPMN 2.0", + "deploy_and_read_api": "REST: POST /deployments (BPMN), POST /process-instances; Zeebe gRPC", + "health": "process instances", + "telemetry": "metrics over OTLP (Micrometer)", + "notes": "a target only; BPMN is the bridge (the kernel's encoder-bpmn)", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Flowable", + "kind": "workflow orchestrator (BPMN)", + "catalog_ids": { + "github": "flowable/flowable-engine" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "BPMN 2.0 XML (also CMMN, DMN)", + "format_spec": "BPMN 2.0", + "deploy_and_read_api": "REST /flowable-rest/process-api (deploy BPMN XML)", + "health": "process instances", + "telemetry": "via Spring Boot (Micrometer)", + "notes": "the open BPMN engine", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Conductor (conductor-oss)", + "kind": "workflow orchestrator", + "catalog_ids": { + "github": "conductor-oss/conductor" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "JSON workflow definitions", + "format_spec": "its JSON model", + "deploy_and_read_api": "REST /api (metadata, start, workflow)", + "health": "workflow status", + "telemetry": "not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Node-RED", + "kind": "flow runtime", + "catalog_ids": { + "github": "node-red/node-red" + }, + "licence": "Apache-2.0", + "licence_class": "open", + "definition_format": "flows as JSON", + "format_spec": "its flow JSON", + "deploy_and_read_api": "Admin API GET/POST /flows, /flow/:id", + "health": "not found", + "telemetry": "not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Hatchet", + "kind": "workflow orchestrator", + "catalog_ids": { + "github": "hatchet-dev/hatchet" + }, + "licence": "MIT", + "licence_class": "open", + "definition_format": "code (Python, TypeScript, Go)", + "format_spec": "none", + "deploy_and_read_api": "REST and gRPC (not verified)", + "health": "runs", + "telemetry": "OTel and Prometheus (not verified)", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Restate", + "kind": "durable execution", + "catalog_ids": { + "github": "restatedev/restate" + }, + "licence": "BUSL-1.1 (Apache-2.0 after four years)", + "licence_class": "source-available", + "definition_format": "code (TypeScript, Java, Kotlin)", + "format_spec": "none", + "deploy_and_read_api": "HTTP ingress /service/handler", + "health": "invocations", + "telemetry": "OTLP traces", + "notes": "a target only", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Inngest", + "kind": "durable execution", + "catalog_ids": { + "github": "inngest/inngest" + }, + "licence": "SSPL v1.0 (Apache-2.0 future licence)", + "licence_class": "source-available", + "definition_format": "code (TypeScript)", + "format_spec": "none", + "deploy_and_read_api": "REST api.inngest.com/v1, /v2", + "health": "function runs", + "telemetry": "OTel (extended traces)", + "notes": "a target only", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + } + ], + "cloud_services": [ + { + "label": "AWS Step Functions", + "kind": "cloud workflow", + "catalog_ids": {}, + "licence": "proprietary service; ASL spec copyright Amazon", + "licence_class": "proprietary", + "definition_format": "Amazon States Language (JSON)", + "format_spec": "https://states-language.net/spec.html", + "deploy_and_read_api": "CreateStateMachine, DescribeStateMachine, GetExecutionHistory", + "health": "executions", + "telemetry": "CloudWatch; OTel not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Azure Logic Apps", + "kind": "cloud workflow", + "catalog_ids": {}, + "licence": "proprietary service", + "licence_class": "proprietary", + "definition_format": "Workflow Definition Language (JSON)", + "format_spec": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json", + "deploy_and_read_api": "Workflow REST API", + "health": "run history", + "telemetry": "Azure Monitor; OTel not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Google Cloud Workflows", + "kind": "cloud workflow", + "catalog_ids": {}, + "licence": "proprietary service", + "licence_class": "proprietary", + "definition_format": "YAML or JSON syntax", + "format_spec": "not found (schema)", + "deploy_and_read_api": "workflowexecutions API", + "health": "executions", + "telemetry": "Cloud Logging", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Cloudflare Workflows", + "kind": "cloud workflow", + "catalog_ids": {}, + "licence": "proprietary service", + "licence_class": "proprietary", + "definition_format": "TypeScript class run(event, step)", + "format_spec": "none", + "deploy_and_read_api": "Workers binding (create, get, status)", + "health": "instance status", + "telemetry": "built-in observability", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Azure Durable Functions", + "kind": "cloud workflow", + "catalog_ids": {}, + "licence": "proprietary service", + "licence_class": "proprietary", + "definition_format": "code", + "format_spec": "none", + "deploy_and_read_api": "not found", + "health": "not found", + "telemetry": "not found", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "AWS ECS", + "kind": "cloud service runtime", + "catalog_ids": {}, + "licence": "proprietary service", + "licence_class": "proprietary", + "definition_format": "task definitions (JSON)", + "format_spec": "the TaskDefinition reference", + "deploy_and_read_api": "RegisterTaskDefinition, DescribeTaskDefinition", + "health": "task health", + "telemetry": "CloudWatch; ADOT (OTel) sidecar", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + }, + { + "label": "Google Cloud Run", + "kind": "cloud service runtime", + "catalog_ids": {}, + "licence": "proprietary service", + "licence_class": "proprietary", + "definition_format": "Knative Service YAML (serving.knative.dev/v1)", + "format_spec": "https://docs.cloud.google.com/run/docs/reference/yaml/v1", + "deploy_and_read_api": "Cloud Run Admin API v1", + "health": "revisions", + "telemetry": "Cloud Monitoring; OTel sidecar", + "source": "2026-11-22, subagent reports from official docs and GitHub (licences from GitHub's API or the LICENSE file)" + } + ], + "standards": [ + { + "label": "BPMN 2.0", + "describes": "processes", + "version": "2.0.2, 2014-01", + "governance_and_licence": "OMG", + "spec": "https://www.omg.org/spec/BPMN/", + "notes": "the kernel has encoder-bpmn and the BBO profile pack" + }, + { + "label": "CNCF Serverless Workflow", + "describes": "workflows", + "version": "1.1.0", + "governance_and_licence": "CNCF; repo Apache-2.0", + "spec": "https://github.com/serverlessworkflow/specification", + "notes": "no orchestrator above confirmed as an adopter" + }, + { + "label": "Compose Specification", + "describes": "deployments", + "version": "living spec", + "governance_and_licence": "Compose Spec project; Apache-2.0", + "spec": "https://github.com/compose-spec/compose-spec" + }, + { + "label": "OASIS TOSCA", + "describes": "deployments", + "version": "2.0, OASIS Standard 2025-07-22", + "governance_and_licence": "OASIS", + "spec": "https://docs.oasis-open.org/tosca/TOSCA/v2.0/TOSCA-v2.0.html", + "notes": "the kernel's kk-tosca mirror" + }, + { + "label": "Common Workflow Language", + "describes": "workflows", + "version": "1.2.0", + "governance_and_licence": "CWL project (Software Freedom Conservancy)", + "spec": "https://www.commonwl.org/specification/" + }, + { + "label": "W3C WoT Thing Description", + "describes": "interfaces (affordances and protocol forms)", + "version": "1.1, W3C Recommendation 2023-12-05", + "governance_and_licence": "W3C", + "spec": "https://www.w3.org/TR/wot-thing-description11/", + "notes": "blocks' interfaces follow its shape (S-164)" + }, + { + "label": "OpenAPI", + "describes": "HTTP APIs", + "version": "3.2.1, 2026-09-10", + "governance_and_licence": "OpenAPI Initiative (Linux Foundation); Apache-2.0", + "spec": "https://spec.openapis.org/oas/latest.html" + }, + { + "label": "AsyncAPI", + "describes": "event and message APIs", + "version": "3.1.0", + "governance_and_licence": "AsyncAPI Initiative; Apache-2.0", + "spec": "https://www.asyncapi.com/docs/reference/specification/latest", + "notes": "the natural description of a pgmq link" + }, + { + "label": "CloudEvents", + "describes": "event envelopes", + "version": "1.0.2, 2022-02", + "governance_and_licence": "CNCF (graduated)", + "spec": "https://github.com/cloudevents/spec" + }, + { + "label": "OpenTelemetry GenAI semantic conventions", + "describes": "model and agent telemetry", + "version": "stability to check (moved repo)", + "governance_and_licence": "OpenTelemetry", + "spec": "https://github.com/open-telemetry/semantic-conventions-genai" + }, + { + "label": "Model Context Protocol", + "describes": "agent tools", + "version": "spec dated 2026-07-28", + "governance_and_licence": "to confirm (second source)", + "spec": "https://modelcontextprotocol.io/specification/latest" + }, + { + "label": "W3C PROV-O", + "describes": "provenance", + "version": "W3C Recommendation 2013-04-30", + "governance_and_licence": "W3C", + "spec": "https://www.w3.org/TR/prov-o/", + "notes": "the kernel's provenance" + }, + { + "label": "P-Plan", + "describes": "plans", + "version": "rev 1.1, 2013-09-17", + "governance_and_licence": "no body; CC BY-NC-SA 2.0", + "spec": "https://www.opmw.org/model/p-plan/", + "notes": "non-commercial licence: the owner to decide how blocks' plans and the kernel refer to it" + } + ] +} \ No newline at end of file diff --git a/docs/framework.md b/docs/framework.md index e201d2a..bf3b8da 100644 --- a/docs/framework.md +++ b/docs/framework.md @@ -1,430 +1,144 @@ # The framework -What Substrate is built as (S-125). `docs/plan.md` says what is built next; this page says what shape it all -takes. Marked **decided** where the owner has agreed, **open** where not. +What Substrate is, its parts, and how they plug together (S-184 to S-186, 2026-11-23). Every default and its reason +is in `DECISIONS.md`. The framework this replaces (S-125 onward) is `docs/archive/framework-s125.md`: history. ## In one paragraph -An **environment** is data in Postgres: streams of readings, the objects they are about, and the actuators that -can be acted on. With nothing else configured it is a **pass-through**: every event goes to an LLM harness -(Claude Code, on any model through the gateway), which acts through gated actuators, and everything is recorded. -From that record, the LLM **distills components** (reactive handlers for patterns in one event or several -aligned ones), each carrying a **card**: its intent, trigger, action, the cases it came from, its KPIs and tests. -A **judge** outside the author's reach tests the card on recorded cases the author never saw, and only then does -the component join the environment. What a component cannot handle goes back up to the LLM, and from there to a -person. Environments nest: a child is an object in its parent's environment. The UI is where people watch -and decide. +**An operating system for AI agents.** Today's agents live in a terminal where everything is a file: one agent, one +context, permissions by convention. Here a working system (a business, a codebase, a household, a game) lives in a +**kernel** where everything is an object: state, actions behind permission gates, events anyone allowed can subscribe +to, and every change recorded. **A top-level orchestrator keeps that system working:** it **maps** it (what the parts +are, what they do, how they connect), **orchestrates** it (sub-agents in shared environments: any harness, any +model, or no model), and **optimises** it (through an optimiser it delegates to, judged before anything changes), +toward goals and values a person sets, asking before anything that matters. It hosts your tools rather than +replacing them: Claude Code or any harness joins unmodified, models come through one gateway, tools through MCP, +environments through OpenEnv, so a change can be rehearsed on a copy before it runs for real. -## Signals and claims (decided, S-126) +## The layers -- A **signal** is what a source reports: a reading, an event, a message, a snapshot, a transcript. It is kept - whole and is no one's opinion; if it is wrong, the sensor is broken. Parsing a signal into fields leaves it a - signal. -- A **claim** is an interpretation of one or more signals (or other claims) by an **interpreter** that answers - for it: the LLM, a distilled component, or a person. It cites what it rests on, and can be wrong even when - every signal is right, which is why it is reviewed, judged and retracted. +Like GNU on Linux, with Postgres made into the kernel: -The test: anything that could be wrong for reasons other than a broken sensor is a claim. Streams carry signals; -the claim log holds claims; actions cite the claims that justify them (under pass-through the LLM may act straight -from signals, and records its interpretation as claims). Interpreters are components, so a distilled interpreter -has a card and its claims carry its name. A person's statement is their claim; the interview transcript is the -signal. - -*Where the store lives moved to the Knowledge Kernel (S-153); the model below is still the target, reached through the kernel's D-101.* - -**The store (decided, S-135): Wikibase's data model in Postgres, with OpenWiki's pinned evidence.** An -**entity** (an item, or a property, itself an entity) has **statements**: a property, a typed value, qualifiers, -a rank (preferred, normal, deprecated) and **references**. A reference says who stated it (a parser's run, an -interpreter and its version, a person, a rule and its premises) and which **span** of a signal it rests on; a span -carries its text's hash and a vector. Every edit is a **revision** of its entity. The usable value is Wikidata's: -preferred if any, else normal. Constraints are statements on properties, checked and reported, never blocking. A -Markdown page per entity, regenerated from its statements, is what people and agents read. When a span's hash -changes, what cites it, and what was derived from that, is flagged with no model call. Under this model a claim is -a statement whose reference is an interpreter: it enters at normal rank and is preferred or deprecated by review. -What a parser wrote is a statement too, with a parser's reference, and nobody reviews it: if it is wrong, the -parser is fixed and rerun. - -**A claim's fields**, after Graphiti's data model ([graphiti](https://github.com/getzep/graphiti), Apache-2.0; -its `nodes.py` and `edges.py` read, S-129), with what it lacks added. Graphiti keeps raw input as episodes (our -signals) and facts as edges with an `episodes` list, and is bi-temporal: `valid_at` and `invalid_at` (when the -fact held), `created_at` and `expired_at` (when the store learned and dropped it). On a contradiction an LLM only -nominates candidates; code decides by dates. Kept: the four times, and "the model nominates, code decides". Not -kept: it overwrites an edge's times in place, has delete paths, records no interpreter, no confidence and no -review status, and links provenance by a list of strings. So a claim here carries `cites` (signals or claims, by -foreign key), `interpreter` (who, and which version of a component), `confidence`, `status` (proposed, -accepted, retracted) and `retracted_by`, and a change of belief is a new claim, never an edit. Graphiti has no -Postgres backend, so it is a model to borrow from, not a part to add. - -## The parts (S-153) - -| Part | Repository | Does | Is not | -| --- | --- | --- | --- | -| **Substrate** | this one | the environment, streams and gated actuators, pass-through, the record, components and their cards, the hierarchy, the gateway, the UI | a harness: Claude Code is the harness | -| **The store** | [Knowledge Kernel](https://github.com/OpenReplicant/kernel) | items and claims with provenance, each caller its own Postgres login under row-level security, the review lane, recall (BM25 and pgvector), reasoning (conclusions with premises, truth maintenance), the agent's MCP tools | Substrate's own `store/` package, retired in S-156 (`docs/store-to-kernel.md`) | -| **The cognitive layer** | [MetaSoar](https://github.com/OpenReplicant/MetaSoar) | how an agent inside an environment perceives, attends, predicts and learns: perception from pixels, the workspace and attention, simulators and surprise, a lockstep runtime for worlds faster than the wall clock; its hypothesis and the predictions that would show it wrong (`docs/cognitive-model.md` there) | required: pass-through works without it, and each of its parts is judged against pass-through like any component | -| **The judge** | an interface here; Morphogen is one filler | a card and a candidate in, a verdict out, on cases the candidate's author cannot read | a framework; Morphogen is optional | - -## The environment is data (decided) - -Everything is in one Postgres, so the environment, the record and the judge's cases are the same data. - -| Need | Mechanism | -| --- | --- | -| The source of truth | signals kept whole (pgmq's archive and the readings they become), and the claim log: claims (subject, property, value, the signals or claims cited, the interpreter, time, confidence). Append-only; a claim is retracted, never erased | -| Streams in | pgmq topics. A signal is published with `pgmq.send_topic` under a routing key `..` (dot-separated, so a child's keys sit under its parent's); logged queues, archived after handling, so a stream can be replayed | -| Sensing, in parallel | each subscriber (an encoder, a reactive handler, the LLM's channel) owns a queue bound to the patterns it watches (`pgmq.bind_topic`; `*` one segment, `#` any). Fan-out is pgmq's; no subscriber takes a message from another | -| Acting, in series | one pgmq queue per actuator, read by the one process that applies it. Who may write to it, and through which gate, is the arbitration | -| Gates | per action kind: `free` (applied), `propose` (into the review lane for a person), `deny`. Live work starts at `propose` | -| Escalation | a topic too: `.escalate`, which the level above subscribes to | -| Views | pgGraph's projection, Ontop's SPARQL over the ontologies, full text, pgvector: read-only and rebuildable from the log | - -Reactive logic runs in **handler processes**, not database triggers, so that each one is a component with a card, -a version and a verdict, and can be judged and rolled back. (Memgraph triggers over a property graph were the -earlier design; the graph is now a view of the claims, not the store.) - -Raw readings are kept, so interpreting them into claims is itself a component: at first the LLM reads the raw -data and decides what it means; when it keeps deciding the same way, it writes an encoder with a card. - -## Pass-through is the default (decided) - -With no components, the environment hands every event to the harness. The harness is **Claude Code**, which -runs on any model the gateway serves and already has tools, MCP, hooks, skills, subagents, permissions and -context management; Substrate does not rebuild any of them. - -- **In:** a Claude Code channel (an MCP server that pushes events into a running session) subscribed to the - environment's topics. -- **Look around:** the store's MCP server, to query objects, claims and history. -- **Out:** actions written to actuator queues through MCP, under the gates; hooks and permissions enforce them. - -Pass-through is useful on its own, and it is the **baseline every other layer is measured against**. - -### The channel, as documented (read 2026-11-17, S-129) - -From [channels](https://code.claude.com/docs/en/channels) and the -[channels reference](https://code.claude.com/docs/en/channels-reference). Research preview; the flag syntax and -protocol "may change", so the version that works is pinned when it is built. - -- **Shape:** a local MCP server, spawned by Claude Code over stdio, declaring - `capabilities.experimental['claude/channel']`, and sending `notifications/claude/channel` with `content` (the - body) and `meta` (attributes; keys letters, digits and underscores only, others silently dropped). Claude sees - each event as a `` tag; events queued during a turn arrive together on the next. Its - `instructions` string tells Claude what the attributes mean. -- **No acknowledgement and no persistence:** a notification is fire-and-forget, and nothing survives a closed - session. So the durable side is ours: the channel reads its pgmq queue with a visibility timeout and does not - archive a message until Claude calls an `ack(msg_id)` tool (or acts on it); an unacknowledged message - reappears and is delivered again. -- **Two-way:** replies and actions are ordinary MCP tools on the same server (or the store's). -- **Permission relay** (`claude/channel/permission`): Claude Code sends `permission_request` (`request_id`, - `tool_name`, `description`, `input_preview`) and accepts `allow` or `deny` back; first answer wins. This can be - where a `propose` gate meets the review lane: the UI shows the request and a person's decision goes back - through it. Anyone who can answer the relay can approve tool use, so it is declared only for an authenticated - path. -- **Enabling it:** a server of our own needs `claude --dangerously-load-development-channels server:` - (a confirmation dialog; ignored with `-p` and through the Agent SDK), so pass-through runs as an interactive - session kept open (tmux or a user service). Team and Enterprise organizations must set `channelsEnabled`. -- **Untrusted input:** "An ungated channel is a prompt injection vector." Every signal from outside is data, - not instructions: the channel's `instructions` say so, senders are gated where a stream has senders, and - actions stay behind the gates. -- **Unknown, to test first:** whether channels work when Claude Code runs on a non-Anthropic model through the - gateway (`ANTHROPIC_BASE_URL`); the docs require a claude.ai login or a Console API key and say nothing of - other endpoints. If they do not, pass-through on a local model needs another way in (a hook that injects - pending events, or polling through a tool). Also unstated: rate limits, maximum payload, reconnects. -- **Known preview bug:** a server negotiating protocol revision 2026-07-28 does not register on the v2 MCP client - runtime; pin the SDK's protocol revision. - -### The harness profile is a component, sized to the model (S-134) - -Claude Code can be cut down so a small model sees only what it needs (read 2026-11-17 in the -[CLI reference](https://code.claude.com/docs/en/cli-reference.md) and [permissions](https://code.claude.com/docs/en/permissions.md)): -`--tools ""` (or a short list) removes built-in tools from the model's context; a bare-name deny -(`--disallowedTools "Edit"`, `permissions.deny`) removes a tool's schema, while a scoped one only blocks calls; -`--strict-mcp-config --mcp-config FILE` loads exactly the listed MCP servers; `--system-prompt-file` replaces the -system prompt (whether that drops the built-in tool instructions is undocumented, so it is tested); and -`CLAUDE_CODE_DISABLE_AUTO_MEMORY`, `CLAUDE_CODE_DISABLE_CLAUDE_MDS`, `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS`, -`CLAUDE_CODE_DISABLE_WEB_FETCH` and `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` drop context. `--bare` and -`--safe-mode` also skip MCP, which the channel needs, so they are not used. Subagents take their own `tools` -allowlist and `model` (background subagents keep only MCP tools). The model is set by `ANTHROPIC_MODEL`, and -Claude Code's background calls by `ANTHROPIC_DEFAULT_HAIKU_MODEL`, both at the gateway. Anthropic states it does -not support routing Claude Code to non-Claude models through a gateway ([LLM gateway](https://code.claude.com/docs/en/llm-gateway.md)), -so on a local model the first test is whether channels deliver, tool calls hold, and the replaced prompt works. - -A **profile** (tool set, prompt, MCP servers, context switches, model) is a component with a card: the lean one -for a small local model (only the channel's and the store's tools, a short prompt), richer ones for larger models, -each measured on the same record. - -## Components can be pipelines: adaptive perception (decided as a shape) - -A component need not be a rule. When a stream has no handler, the LLM can build one: probe the signal, decide -what it is, and install a pipeline that turns it into something it can use. Example: a raw audio stream arrives -unhandled; the LLM samples it, and either pipes it to its own audio input if the model has one, or installs a -classifier (speech, music, noise) and, for speech, a speech-to-text model chosen from the catalog (the `research` -skill), writing transcripts as signals and what they mean as claims. Each stage is a component with a card, so -each can be tested, swapped for a cheaper or better one, and judged against the stage it replaces. The -environment's senses grow to fit its streams and its model: embodiment that adapts. - -## Maps, roles and catalogs (decided, S-139) - -Any thing, software or not, is taken apart the same way: a whole *has part* parts, each playing a **role** there; -a role *requires interface* what anything filling it must provide, and a part *provides interface* it. The -interface is what makes parts interchangeable, so it is named exactly enough to check. A **catalog** is where -candidates come from; `alternatives` lists what provides everything a role requires. A whole *has goal* -measurable goals; a trial's results are *measurements*, and whether a candidate is better is a judge's -*verdict*, a statement whose reference is the judge (Morphogen, when it is back in the build). All of it is -statements in the store, written by the `map` and `catalog` skills through the store's MCP tools, so a map is -reviewed, flagged and corrected like anything else. The components below are this applied to an -environment's own parts. - -## Components and their cards (decided) - -A component is a handler that subscribes to a pattern and does something: writes claims, proposes an action, -or escalates. Its kind may be a rule, a script, a model call, a Claude Code session, or a person. Components come -from the LLM distilling its own repeated decisions (or from a person), and each carries a **card**: - -| Field | Says | -| --- | --- | -| intent | what it is for, in a sentence the owner can check | -| trigger | the pattern it fires on: one signal or claim, or several aligned in time | -| action | what it does, through which actuator | -| source cases | the recorded events it was made from, each with what the LLM or person did | -| KPIs | what it must hold to: agreement with what it replaces, cost per event, latency, override rate | -| tests | cases it must handle, and cases where it must not fire | - -**Lifecycle:** proposed → judged → active at `propose` → `free` once trusted → demoted when it drifts (overrides -climb in the review lane). Every version is kept, so a component can be rolled back or compared against the LLM -it replaced. - -**What CogRec shows, and what it lacks** ([arXiv 2512.24113](https://arxiv.org/abs/2512.24113), read in full, -S-129). A recommender: Soar handles what its rules cover; on an impasse, a summary of working memory goes to an -LLM (DeepSeek-V3), and the answer is parsed into a condition-action pair that Soar's chunking compiles into a -rule. It beat the best baseline by 4–9% on three datasets, and its rate of LLM calls fell to a low plateau as -rules accumulated; without chunking it stayed near the plain LLM. But no seeds, variance or significance tests -are reported, and learned rules are never tested, scoped or removed: they are "permanently internalized". That -is the gap the card and the judge fill. Taken from it: the escalation carries a structured summary of the -state, not the raw context; the answer is parsed into trigger and action before it becomes a component; and -the **rate of LLM calls per event** is a KPI of the whole environment, the number that should fall as it learns. - -**Confidence is measured, not stated.** A component's confidence is the agreement the judge measured on held-out -cases, within the scope its trigger covers. The LLM gets an event when no trigger fires, when the event falls -outside what the component was judged on, or when the component has been demoted. (Cascade research finds -routing only as good as its quality estimate; this is how the estimate is earned.) - -## The judge is an interface (decided; its filler is open) - -A card and a candidate go in; a verdict comes out, with each KPI's result, the case counts, and pass or refuse, -appended to a log. What it needs beyond ordinary CI is two things: **cases the author cannot read** (a slice of -the record held by another role: Postgres row-level security, or a separate user for the stronger version), and -**comparison against the incumbent**, not pass/fail alone. - -- **First filler:** a script run as the judge user, running the card's tests and the held-out slice. -- **Candidates for the runner** (rule 3, not yet searched): Inspect AI, promptfoo, DeepEval. -- **Morphogen** is frozen as an option behind the same interface (S-127). Its later overhaul, when the owner - starts it, is toward a standard CI workflow built from components (a runner, held-out cases, a verdict log, - statistics as a step) rather than one custom program. - -## It is an actor model on Postgres (a description, not a runtime to build) - -Each component is an actor: it owns a mailbox (its pgmq queue), handles one message at a time, and sends -messages (`send_topic`); the parent environment supervises its children, as an Erlang/OTP supervisor does. Two -differences from a pure actor model: state is shared, not private (the claim log is a blackboard every actor -reads), and an actor is judged before it runs live. So: actors for messaging, a blackboard for state. - -What follows from that: - -- **Borrow the semantics, not a runtime:** one mailbox per actor, per-mailbox order, supervision, retries with - visibility timeouts. pgmq gives all of it; no actor framework is added. -- **Side effects must be idempotent:** a retried message re-applies its action. Writes to the database are - transactional; anything outside (an email, an API call) needs an idempotency key on the actuator. -- **Postgres has a rate ceiling:** work-level events (tickets, messages, changes) are fine; high-rate sensor - data is sampled or batched before it becomes a signal, or uses an unlogged queue where loss is acceptable. -- **Nearby tools** for durable steps on Postgres, if a component needs multi-step workflows: - [Absurd](https://lucumr.pocoo.org/2025/11/3/absurd-workflows/) (SQL-only, works with pgmq), - [DBOS](https://dbos.dev/blog/making-postgres-queues-scale), Hatchet. Chosen by the research skill when needed. - -## The view: serializing the environment for the LLM (a component, tested per model) - -What the LLM sees is a rendering of the environment, and how it is rendered changes results: one study found -up to 40% differences between plain text, Markdown, YAML and JSON on the same task, with no format best across -models ([He et al. 2024](https://arxiv.org/abs/2411.10541), OpenAI models only). It also decides cost, through -the prompt cache. So the **view is a component with a card**, like any other, and is judged per model and per -arrangement. - -Its parameters: - -| Parameter | Choices | -| --- | --- | -| format | plain text, Markdown, YAML, JSON, XML tags, tables | -| content | signals, claims, or both; citations inline or by id | -| granularity | each signal, a summary per stream, deltas against a snapshot | -| order | by time, by object, by priority | -| time | absolute or relative; where timestamps sit | -| budget | how much fits before older content is summarized | - -**Cache layout (default):** stable first, changing last, and nothing already sent rewritten: instructions and -the environment's schema (streams, objects, actuators), then a snapshot of the objects that matters, then the -events appended in order. Timestamps, tool sets and instructions that change mid-session break the cached prefix -([prefix-stability study](https://neurips.cc/virtual/2026/162685) finds a badly arranged loop can cost more than -no caching). The gateway already meters `tokens_cached` (S-106), so a view's cache rate is a KPI on its card. - -**Under pass-through** the view is two things Substrate controls: the format of the events a channel pushes, -and what the store's MCP tools return. Claude Code manages the rest of the context (compaction, its own cache -layout), and that stays its job. A self-lever lets the LLM ask for a different view (a summary instead of raw -signals), as a `propose`. - -## Environments nest (decided as a shape; built later) - -A child environment is an object in its parent's environment: - -- its **streams** are its escalations, KPIs, verdicts and activity, under its own routing keys, so the parent - subscribes with `.#`; -- its **actuators** are what the parent may do to it: start or stop it, change its configuration, approve or - retire its components, take over an event; -- its **gates** work as anywhere else: the parent changing a child's structure is `propose` until trusted. - -Escalation goes up a level at a time; only the top reaches a person. The **top level is the system itself**: the -map (objects: components, services, packages), the observer (streams: what runs) and interviews (intent). That is -where the map work done so far belongs. A child's whole configuration is a component with a card from the -parent's side, judged like any rule. - -**The one rule built in from the start:** an environment's interface (streams, objects, actuators, gates) is -exactly what a parent sees of it as an object, so nesting needs no redesign. - -## The chimera: the root and its goals (decided, S-130) - -The root environment is the **chimera**: one system that finds components, or makes and changes them, as its -goals require. Every other environment is a child of it. Its goals, in the order they bind: - -1. **Values and constraints** (floor, changed only by the owner): the gates, the privacy rules for personal - streams (`docs/privacy.md`), the budgets, and what the judge holds. Nothing optimizes against these. -2. **The owner's preferences** (from what they say, in interviews and in the review lane, as their own claims). -3. **Self-optimization** (seed): lower cost and fewer LLM calls per event, fewer escalations to the owner, at - equal or better quality, every change judged against what it replaces. - -**Budgets** are a floor the owner sets (spend per day, per caller, per model) and signals the chimera reads (the -gateway's meter). Choosing a model or a compute placement within the budget is a self-lever; raising a budget -is always the owner's. - -**The children, in order:** the companion (a persistent voice and avatar assistant working in the background), -then embodied environments it acts in: VRChat or Virt-A-Mate for presence as a 'hologram', ROS2 for a robot in -simulation and later in operation. Each is nested by the interface rule, so the companion acts in them through -their actuators under the same gates and budget. A personal stream (the owner's voice, messages, files) carries -the privacy floor from its first signal. - -### Privacy: adjustable, with defaults that flag and prevent exfiltration (decided, S-131) - -The rules in `docs/privacy.md` are the defaults, and they hold until the owner loosens one for a named stream -(a review-lane decision: who, when, why). The default is to **flag and prevent**: personal content does not go -to a hosted model, and an attempt is refused and flagged rather than silently allowed. The gateway is the one -place that can enforce this, so every model call goes through it, **Claude Code's included** -(`ANTHROPIC_BASE_URL` at the gateway), and each caller's key names the providers it may reach. Loosening P3 or -P4 for the companion's text is then one change to one key, visible in the record. - -### Placement is a trade-off the system can choose (decided, S-131) - -On the owner's machine today (a GTX 1070, 8 GB, weights already partly offloaded to system RAM), each part runs -on the GPU or the CPU, at a cost in latency: Gemma 4 26B or 12B for the local model, speech parts on the CPU. -These are parameters on each component's card (placement, model, quantization), measured for latency, quality -and memory, and choosing among them within the budget is a self-lever; the owner can pin any of them. - -### The browser client is an environment (decided as a shape, S-131) - -The UI's browser client is where the owner is, so it is an environment of its own, a child of the companion: - -- **Sensors** from browser APIs: microphone, camera, text, and others as needed (screen, location), each off - until the owner turns it on, each a personal stream under the privacy floor. -- **Actuators:** the speaker, the avatar's rendering, the page itself (messages, notifications, the review lane). -- **Transport:** today the shell gets Server-Sent Events of changed ids (`NOTIFY` on `wb_events`) and sends by - HTTP. Media needs a two-way binary path (a WebSocket, or WebRTC if latency demands it) on the UI's server. -- **Rate:** raw audio and video do not go through pgmq frame by frame (Postgres's rate ceiling). The browser's - media goes straight to its pipeline; what the pipeline makes (an utterance, a transcript, a detection) is the - signal published to the topics, and raw media is kept, if at all, as files under the retention rule (P7). - -**Built as its own package, not inside the UI (S-132).** The UI's live events stay as they are. The browser -environment is a small JavaScript library dropped onto any page (the UI's page is the first host) that -declares what the browser offers, sensors and actuators each with a schema, the way an MCP server declares its -tools; and a small bridge on the server that takes one WebSocket from it and connects it to pgmq (signals out to -topics, actuator queues in; raw media to its pipeline). Every embodied child is the same pattern: an adapter from -a native API (the browser's, VRChat's OSC, ROS2) to topics and queues. The declarations follow WebMCP's tool -shape (`document.modelContext`; a draft W3C community report in a Chrome origin trial, not called by mainstream -agents as of May 2026), so the library can register there later without depending on it now. - -**The avatar's actuators are defined once:** `speak` (audio, optional visemes), `express` (name, weight), -`look_at`, `gesture`; each embodied environment fills them its own way. First filler, in the browser: three.js -with `@pixiv/three-vrm` (versions pinned when built), idle motion, and the mouth driven by speech volume through -VRM's expression presets (`aa`, `ih`, `ou`, `ee`, `oh`) rather than a jaw bone, so any VRM model works; blink -and look-at from the same expression manager. Later: visemes from the text-to-speech's phoneme timings, if -Kokoro's Rust implementation provides them. - -**Mixed reality on the Quest 3 is the same environment on the headset (S-133).** An `immersive-ar` WebXR -session with passthrough gives, as sensors: plane detection with semantic labels, mesh detection, hit testing -(on Meta's Depth API since Horizon Browser 40.4), persistent anchors, depth sensing (mostly the GPU path), and -head and hand pose. The headset runs SLAM itself; its poses and anchors are signals, so SLAM is never built. -Camera pixels are the open question: Meta's Passthrough Camera API is native (Android Camera2, Horizon OS v74+); -WebXR `camera-access` is reportedly refused for `immersive-ar` (Horizon OS v85); a "headset cameras" website -permission and `getUserMedia` reportedly work but are not in Meta's developer docs. Tested first on the device; -if the browser cannot have the camera, a small native Quest app is one more adapter onto the same topics. The -avatar gains `move_to` (an anchor or point), `place_on` (a plane) and `look_at` (a person or object) for presence -in the room. Recognition (objects, activity, pose, face, gaze) is perception pipelines: light and fast on the -headset, rich and slow on the PC's GPU from frames sent at a low rate; their output is claims, and the companion -reasons over claims, not pixels. Camera frames from inside the owner's home are personal under the privacy -defaults: local models only, retention bounded. - -### Perception pipelines trade interpretability against refresh rate - -Every pipeline sits somewhere between fast and shallow and slow and rich, and can run both at once: - -| | Fast path | Slow path | +| Layer | Is | Defines or does | | --- | --- | --- | -| Hearing | voice activity, wake word, speaker turn | speech-to-text, then what was meant (claims) | -| Sight | motion, presence, face or hand landmarks, many times a second | a vision model's description or answer, a frame every few seconds or on demand | - -The fast path's signals decide when to spend on the slow one (someone spoke; something moved), and the LLM can -ask for the slow path directly. The rates, models and the switching rule are card parameters, so the balance is -measured per machine and per task rather than fixed. Speech candidates named by the owner: **Kokoro** (a Rust -implementation) for text-to-speech and **NVIDIA Parakeet TDT** for speech-to-text; versions, licences and -CPU latency are checked with the `research` skill before they are pinned (rules 1, 3, 6). - -## Assumptions, as parameters - -Each layer is switched on per environment and has to beat pass-through on the same work, on quality, cost or how -much reaches a person. A layer that does not stays off. - -| Layer | Its assumption | -| --- | --- | -| Raw readings into claims | encoding helps more than it loses | -| Reactive handlers, in parallel | cheap pattern matching takes load off the LLM without missing things | -| Escalation filtering | the LLM judges better with less in its context, and can query the rest | -| The view's format and layout | a given rendering suits a given model; differs per model and arrangement | -| Serial arbitration per actuator | needed once there is more than one actor | -| Self-levers (subscribe, mute, add or retire a handler, set a threshold) | the LLM tunes its own setup well; structure changes are `propose` | -| Nesting | splitting off a child lowers cost or escalations without losing quality | - -## Prior art - -From one round of searches (2026-11-17), mostly abstracts; CogRec, Graphiti's code and Global Workspace Agents -were then read in full (S-129). - -| Part | Closest work | +| **Kernel** ([OpenReplicant/kernel](https://github.com/OpenReplicant/kernel)) | Postgres made into a kernel | The standards: **knowledge** (claims with provenance, review, recall), **interaction** (objects with properties, actions and events; gates `free`, `propose`, `deny`; queues), **authentication** (a login per component, row-level security), **pluggability** (how a component describes itself and plugs in), and the record. Its modules are data transformations and what happens at the Postgres level | +| **Substrate** (this repository) | The orchestrator kit | A little agent framing on the kernel's standards: an ordinary LLM harness given skills, MCP servers and hooks so that it maps, orchestrates and optimises its system. Plus the adapters, the reference stack and this document | +| **Morphogen** ([OpenReplicant/Morphogen](https://github.com/OpenReplicant/Morphogen)) | The optimiser | A sub-agent pluggable into anyone's system: cells (what may change, how it is run, what is better, what must keep passing), optimizers behind a judge they cannot edit, the still-works gate, the system guard, an evidence log | +| **Distributions** (`distributions/` here) | What is built with it | Kinds of environments, multi-stage agents, the assistant, the SMB Foundry or AI ERP; each composed of components. Folders in this repository until Substrate's shape is settled | +| **MetaSoar** ([OpenReplicant/MetaSoar](https://github.com/OpenReplicant/MetaSoar)) | The research | Cognitive architecture: impasse-driven compilation (M-17), System 1 distilled from experience; experiments on OpenEnv | + +## The orchestrator + +``` + intentions, goals, values ── the person (approves through propose gates) + │ + ┌──────────────▼───────────────────────────────────────────────┐ + │ the orchestrator: an ordinary LLM harness (Claude Code first)│ + │ skills: map · catalog · research · orchestrate · optimize │ + │ MCP: the kernel; Morphogen; what it installs (approved)│ + │ hooks: gates enforced inside the harness too │ + │ models: any, through the gateway │ + └──────┬──────────────────────────────┬────────────────────────┘ + │ observes (subscriptions) │ delegates, adjusts + ┌──────▼──────────────────────────────▼────────────────────────┐ + │ environments: objects · gated actions · events · the record │ + │ shared by sub-agents: harness sub-agents, OpenEnv │ + │ environments, custom MCP components │ + └──────────────────────────────────────────────────────────────┘ +``` + +- **Map:** the `map` skill decomposes a system into parts, roles and interfaces, written as Backstage entities (the + `catalog/` files, read into the kernel, S-176) with evidence. +- **Catalog and research:** for each intended component without a hard dependency, the `catalog` and `research` + skills fill the catalog with candidates and test them against the need, so the best fit is chosen, not + remembered. +- **Orchestrate:** the orchestrator watches its system by subscription and delegates work: a quick task to its own + sub-agents, long or risky work to a separate harness process with its own login, rehearsal to an OpenEnv + environment in simulation, deterministic work to an MCP component. +- **Optimise:** the `optimize` skill chooses a cell and when to work on it; Morphogen (its Claude Code plugin) + searches and judges; a winner becomes a proposal the person approves. Who proposes never grades their own work. +- **Error correction and monitoring** are the same loop: observe, notice, delegate or optimise, verify. +- **Autopoiesis:** Substrate's own stack is an environment like any other (its compose file goes into the map and + back out, S-177), so the orchestrator maintains and grows its own system with the same skills. + +## Everything is an object + +One kind of thing: an **object** with **properties** (its state), **actions** (messages it accepts, each behind a +gate) and **events** (messages it sends). Everything else is a **trait**, not a type: + +| What it used to be called | As an object | | --- | --- | -| Shared space, broadcast | blackboard systems with LLMs, the ones with results: [LbMAS](https://arxiv.org/html/2507.01701v1), [Google's data-discovery blackboard](https://arxiv.org/abs/2510.01285v2). [Global Workspace Agents](https://arxiv.org/html/2604.08206) (2026), read in full: a design with no evaluation at all, and a serial four-phase loop with fixed roles, not parallel subscribers; ideas only (an explicit "respond or think more" tag from an arbiter; compressing short-term memory into a retrievable long-term store past a threshold) | -| Distilling LLM decisions into rules | [CogRec](https://arxiv.org/abs/2512.24113) (Soar chunking of LLM answers; results, but rules never tested or removed); [NL2GenSym](https://arxiv.org/pdf/2510.09355v1); [LATM](https://arxiv.org/abs/2305.17126v2) | -| Claims with provenance, over time | [Graphiti](https://github.com/getzep/graphiti) (episodes, bi-temporal facts; no interpreter, confidence or review; times overwritten in place) | -| Rules written by an LLM, run without it | [llm-trigger](https://github.com/c4pt0r/llm-trigger); [LLM4CEP](https://pure.uva.nl/ws/files/201121899/24-LLM4CEP.pdf); [reactive synthesis](https://arxiv.org/html/2402.16905v1). All start from a person's request, not from the observed stream | -| Cheap first, escalate | [FrugalGPT](https://www.emergentmind.com/papers/2305.05176); [routing and cascades review](https://web.stanford.edu/~shuhuiq/blog/review-routing-cascades.html) (no router clearly beat the trivial one on RouterBench) | -| Event logs, actors | [OpenHands events](https://docs.openhands.dev/sdk/arch/events); [AutoGen Core](https://www.mintlify.com/microsoft/autogen/core/overview); [ambient agents](https://snowplow.io/blog/what-are-ambient-agents) | -| Environment interface | [OpenEnv](https://huggingface.co/docs/openenv/tutorials/mcp-environment) (reset/step/state with MCP tools, for training) | -| Self-change | [Letta](https://medium.com/@piyush.jhamb4u/stateful-ai-agents-a-deep-dive-into-letta-memgpt-memory-models-a2ffc01a7ea1); [Gödel Agent](https://arxiv.org/html/2410.04444v2); [Darwin Gödel Machine](https://arxiv.org/pdf/2505.22954) (archive of versions, empirical checks) | -| Frame | [CoALA](https://huggingface.co/papers/2309.02427); [cognitive architectures to language agents](https://arxiv.org/pdf/2607.23942) | -| Nesting (not yet searched) | Erlang/OTP supervision trees, Kubernetes controllers, holonic multi-agent systems, hierarchical RL | - -What appears new is the combination: pass-through as the baseline every layer must beat; components distilled -from the observed stream rather than from a request; reviewed claims rather than derived edges; and a real -harness rather than a research loop over a bare model API. - -## Open - -- What the LLM sees by default: everything, or what components escalate plus queries (recommended: the latter, - once there are components; everything under pass-through). -- The judge's runner: a script, or one of Inspect AI, promptfoo, DeepEval. -- The default view's format, until one has been measured on the first environment's model. -- Whether channels work with Claude Code on a non-Anthropic model through the gateway; the first thing to test. -- The first system to put an environment on. +| artifact | an object with read and write actions and the trait **versioned** (revisions and provenance) | +| component, agent, handler | an object with the trait **active**: it subscribes and acts on its own | +| environment | an object with the trait **container**: it holds objects, so environments nest | +| stream, source | an object's events; a source is a component that turns a protocol's data into events | +| actuator | an object's action; a gate is a policy on it | +| the blackboard | all objects' properties, in one database | +| a component's view | a query over the objects its login may see | + +Objects talk only by messages (pgmq), never by reaching into each other's state, so permissions and the record hold. +Use traits, not inheritance. The Agents & Artifacts model (CArtAgO) is the closest precedent; its words are ours too: +an agent **focuses** on an object to perceive it; observable **state** is replayable, **signals** are transient. +W3C WoT Thing Description 1.1 is the shape of an object's description. + +**Rules:** a source runs only while something subscribes to it; starting a new source or handler is a proposal (what +is read is the person's call, docs/privacy.md P1, and so is the cost); large or fast data travels by reference. +**One database, the kernel's** (S-190): the kernel defines the schemas and the ways of doing things, and Substrate +follows them, so knowledge and the environment's live state are schemas in one database, and one transaction or +trigger can change an object and record its version. (A third party's private store, such as the gateway's, may +stay a database of its own on the same server.) + +## Slots: every dependency is a contract + +| Slot | Contract | Default filler | Could also be | +| --- | --- | --- | --- | +| Environment and delegation | OpenEnv (production and simulation) + MCP; A2A's task states for a delegated task | the kernel's Postgres environment, served as OpenEnv | any OpenEnv environment, any MCP server, a harness sub-agent | +| The map | Backstage entity files, over MCP | the kernel | the plain files in `catalog/` | +| The optimiser | Morphogen's cell contract | Morphogen | anyone's optimiser and judge | +| The harness | skills, MCP servers, hooks | Claude Code | any harness that takes them | +| Models | an OpenAI- or Anthropic-compatible endpoint | Bifrost (`gateway`) | any gateway, a provider directly | + +No cycles: the kernel needs only Postgres; Morphogen needs cell files (and reads Backstage when present); Substrate +needs only the contracts; distributions need Substrate and the fillers they choose. The test: Substrate pointed at a +folder of catalog files and one OpenEnv environment still runs. + +**Delegation has three kinds of filler,** all on MCP: an **OpenEnv environment** (episodes, rubrics, packaging: +rehearsal and Morphogen's cases), a **harness sub-agent** (Claude Code's own sub-agents for quick work inside the +orchestrator's session; a separate harness process, with its own login, context and record, for long or risky +work), and **custom** (a service, a script, a non-LLM agent). OpenEnv already treats a harness as an environment +(RFC 005), so the line between them is thin. + +## OpenEnv, adopted fully (S-184) + +Substrate's environments **are** OpenEnv environments: its classes, server, clients, simulation episodes and +rubrics, production mode, harness adapter and packaging, used as they are. What OpenEnv lacks is built inside our +environments, not around them: state in Postgres (so many sessions share one live environment), the database's +logins (OpenEnv's server has no auth: keep it behind ours), approval gates as tool behaviour, events to subscribers. +Simulation `reset` clones a template database, so a change is rehearsed on a copy of the real data: Foundry's +"what-if", with the judge built in. Pinned `openenv` 0.12.0; early development, weekly releases: keep our code +against it thin. A spike proves seven points first (`docs/plan.md`). + +## Rules that run through it + +- **The cache rule:** an LLM's view of an environment is rendered so it only grows at the end: fixed parts first, + events in order, volatile parts (the time, the current focus) last; a conversation stays on one model unless + switching pays for the reprocessing; compaction is rare and in large chunks. +- **Labels are outcomes,** never a decider's own choice; feedback may arrive long after, by the id of what it judges. +- **Gates:** `free`, `propose` (waits for a person), `deny`; enforced by the database, and by hooks inside the + harness so a sub-agent cannot route around them. +- **Privacy:** `docs/privacy.md`; nothing personal leaves the machine unless a rule is loosened for a named stream. + +## What it takes from elsewhere + +Agents & Artifacts (focus, state and signals, workspaces); W3C WoT (an object's description); Palantir Foundry's +Ontology (object types, links, actions validated, permissioned and audited, what-if); BDI's discipline (a typed +vocabulary, a validator, retraction on failure) as tables and gate checks, not a BDI runtime; OpenEnv; MCP; A2A's +task states; CloudEvents for event envelopes; Home Assistant's stable ids; PostgREST and pgmq as parts. The research +behind this: `docs/research/Object environments prior art.md`. + +## What looks new + +As far as the research searched: trait-based objects whose actions sit behind free, propose and deny gates in one +Postgres that is blackboard, bus, auth and record; unmodified harnesses joining through the model endpoint; an +optimiser whose judge the optimizer cannot edit, wired to the map; and (MetaSoar's) a System 1 distilled from the +record that makes the system cheaper as it learns. diff --git a/docs/handoff-2026-11-22.md b/docs/handoff-2026-11-22.md index 7f62d5d..8db8754 100644 --- a/docs/handoff-2026-11-22.md +++ b/docs/handoff-2026-11-22.md @@ -1,5 +1,9 @@ # Handoff, 2026-11-22 (cloud session to the owner's machine) +> **Superseded the same day.** History, not a plan to work from: since this was written the local models changed +> (S-169: Inkling as `slow`, LFM3 as `fast`), the voice head routes by tool (S-170, S-171), and the next build is the +> gate and one assistant (S-178 to S-181). Read `docs/plan.md` and the newest rows of `DECISIONS.md`. + Written before the work moves from a cloud session to the owner's machine. Open **Substrate** there: it runs the stack and pulls the kernel's image, so the first checks happen here. The kernel and MetaSoar are separate repositories; `docs/repos.md` says what each owns. diff --git a/docs/handoff-2026-11-23.md b/docs/handoff-2026-11-23.md new file mode 100644 index 0000000..03ec251 --- /dev/null +++ b/docs/handoff-2026-11-23.md @@ -0,0 +1,44 @@ +# Handoff, 2026-11-23 + +Read this first in a new session, then `docs/plan.md` ("Next, in order") and `docs/framework.md`. History before +this is in `DECISIONS.md` (S-178 to S-186 are this stretch's) and `docs/handoff-2026-11-22.md` (superseded). + +## Where it stands + +- **Branch `claude/m17-gate`**, not pushed, not merged. It carries S-178 to S-186: the ladder's design and its + decider trial, `env.experience` (migrated on this machine's database; `EXPERIENCE_KEY` is in `.env`: keep a + copy), and the new shape in the docs. `scripts/check.sh` and all eleven test suites pass. +- **The shape is settled (S-185):** the Kernel (Postgres made into a kernel), Substrate (the orchestrator kit: + skills `map`, `catalog`, `research`, `orchestrate`, `optimize`; hooks; adapters; the reference stack), Morphogen + (the optimiser, its Claude Code plugin), distributions (folders in `distributions/` here, not new repositories), + MetaSoar (research). Every dependency is a contract. Environments are OpenEnv environments (S-184). The ladder + (System 1 at the model endpoint) is an assistant-distribution component on OpenEnv (S-186). +- **The research behind it:** `docs/research/Object environments prior art.md` (and its notes): nothing found + combines the pieces; copy Foundry's ideas, A&A's vocabulary, WoT; plug in PostgREST, pgmq, RLS, MCP; first paid + offer a five-day "map and one gated automation" pilot. The owner wants Substrate solid before outreach. + +## Next + +Plan step 1, **the OpenEnv spike**: `openenv` 0.12.0 (2026-11-05, BSD-3; not `openenv-core`), one Postgres-backed +environment, seven points to prove (listed in the plan and S-184), plus whether MCP's `input_required` (revision +2026-07-28) is final. Results in `.state/trials/openenv/`, a row in `DECISIONS.md`. Then step 2, Morphogen. Once the shape settles (S-187): +everything runs on top of it (step 6), the bootstrap instance with a snapshot map and catalogs (step 7), a second +docs pass (step 8). + +## Things to know + +- **Git identity:** this machine has none configured; commits use `git -c user.name=Claude -c + user.email=noreply@anthropic.com`, as the earlier commits do, with the session's attribution lines. +- **Morphogen's checkout** at `~/Projects/Morphogen` is rebuild 5 (2026-10-26); GitHub's main is rebuild 7 + (2026-11-21, a Claude Code plugin v0.8.0 with an MCP server). Update it before use; never edit it from here (rule 9 + as rewritten: changes by pull request there). +- **The kernel's MCP tools** (`mcp__kernel__*`) were not loaded in these sessions, so the research rows (S-179) have + their evidence in trial files, not in the store. +- **Settled 2026-11-23 (S-188):** the MCP installer's registries and trust; LFM3 recommended (downloads may be + recommended whatever their licence); business work in its own session as soon as plan steps 6 to 8 are done. + Later the same day (S-189 to S-191): the motto is "Map, design and orchestrate software, agents and + organisations. Optimise all the things!"; one database, the kernel's (the `env` schema moves in, plan step 4); + the retired `store` schema was dropped (dump in `.state/backups/`); agent-facing documentation and an `rtfm` skill + are planned (steps 5 and 7). + **Open for the owner:** merging `claude/m17-gate`; pushing the kernel's branch `claude/one-database` (D-126, + superseding D-94 (c); stacked on `claude/compose-codec`, PR #134) and opening its pull request. diff --git a/docs/plan.md b/docs/plan.md index 27fb1aa..b905507 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -4,13 +4,14 @@ The one current plan (S-124, 2026-11-17). It replaces the plans in `docs/archive the experiment-first direction, the handoff, the task briefs); those are kept as history and are not to be worked from. Every default and its reason is still in `DECISIONS.md`. -## What Substrate is now +## What Substrate is now (S-185, 2026-11-23) -An agent framework. You put an environment on a system you need, run it, and watch and change it in the UI, -Substrate's web page over the store (`ui/`, S-140, S-141; rebuilt on the fresh tree, S-137). Its shape is `docs/framework.md` (S-125): the environment is data in -Postgres, pass-through to Claude Code is the default, components distilled from the record carry cards, a judge -tests them on cases their author never saw, and environments nest. Morphogen stays a part you can use as it is; -no more work goes into it for now. +**An operating system for AI agents:** a top-level orchestrator (an ordinary LLM harness, Claude Code first, given +skills, MCP servers and hooks) that maps, orchestrates and optimises a working system, on a kernel made of Postgres +where everything is an object. Its shape, layers, slots and contracts are `docs/framework.md`. Environments are +OpenEnv environments (S-184); the optimiser is Morphogen's Claude Code plugin; what is built with it lives in +`distributions/` (S-185, S-186). The steps table below is the history of how the current parts came to be; what +comes next is "Next, in order". ## The fresh start (S-137) @@ -43,13 +44,119 @@ Self-levers beyond budget and model choice, and the other layers in `docs/framew need them, each tested against pass-through. The UI is no longer frozen: add what these steps need, and nothing they don't. -## Next, in order (2026-11-21) +## Describe, check, decode: components and runtimes (S-174, 2026-11-22) -1. **Offline agents on the local model:** an agent loop picked with the `research` skill (open, permissive, OpenAI API and MCP), Gemma's tool calls checked on llama.cpp, the kernel's model-using modules on `local/gemma`. Done when, with the network off, a task given in the UI is done with a cited recall and a remembered result, every call in the gateway's log. -2. **The live map and the avatar page** (S-158; the kernel's D-115): interactive mapping, the map redrawn as claims apply, edits and new terms from the page. -3. **Blocks, assemblies and executors** (S-157), with its first check. -4. **The business distribution** in the kernel: distributions (M5-T9), interactive mapping as its first job, logs mined beside it. -5. **Process KPIs** as observed claims; then one real actuator beyond Compose, behind a gate. +Supersedes S-173's runtime engine. The owner's direction: Substrate does not build a runtime or sit in the links +between components. It **describes** a system in the Knowledge Kernel, **checks** that its parts can talk, puts a +**translator** between two that cannot, and **decodes** the description into the native formats of existing runtimes +and **encodes** what they report back; "otherwise we would be just encoding and decoding, like file formats, for +existing runtimes". That is the kernel's own architecture: decoders turn models into running things, encoders read +them back, automations stay in their runners' native formats (the kernel's D-41; chain runners parked, D-36). + +**The kernel as a symbolic latent space** (the owner): one universal symbolic representation that systems are +interpreted into (encoders) and out of (decoders). A map, a BPMN process, a compose file and a running deployment +are views of the same items and claims; what can be said in one format can be carried to another through it. + +- **Components describe their interfaces; Substrate does not mediate them.** An interface is described in the shape + of a W3C WoT Thing Description: the affordance (an action, property or event) with its data schema, and the forms + that reach it (protocol, address, content type): MCP over stdio or HTTP, an OpenAI-compatible API, a pgmq queue + (AsyncAPI describes one), plain HTTP, anything else. Components talk to each other directly, as they already do. +- **Compatibility is checked, and translators are components.** Two parts fit when one provides the interface the + other requires (the map vocabulary's *provides interface* and *requires interface*). Where none fits directly, a + translator from the catalog goes between them (an MCP bridge, a proxy, an adapter block), found like any other + part. +- **The catalog entry is D-101's first content type.** Each component (block, MCP server, service, model, agent + instance) is an item in the kernel: a typed document of fields and prose, with claims derived from it for checking, + drift and alternatives (the kernel's D-101, proposed 2026-11-08, waits on exactly this proof). +- **Runtimes are pluggable, Compose first.** A decoder writes the map out in one runtime's format; an encoder reads + its state back. Compose (with Podman) is the first, since Substrate runs on it; process-compose is the lead + candidate for plain processes. `docs/compatibility/` lists the runtimes, orchestrators, cloud services and + standards a decoder could target, with formats, APIs and licences: what to tell a business that already runs + Kubernetes, Camunda or Step Functions. A licence decides only whether a part can be a default (rule 7). +- **Light by default.** Our blocks are components that implement some protocol, as clients or servers; they run on + demand (measured: about 19 ms a call for a Python block with JSON in and out, 8 MB idle, S-173) or kept hot by the + runtime when a measured plan needs it. +- **What stays ours, kept small:** the description and the compatibility check; the decoders and encoders; gates at + the chokepoints that exist (the model gateway, an MCP proxy where one is chosen, our own agents' actuators), not on + every link. (The voice front end's loop and M-17's ladder were listed here; they are distribution components now, + S-186.) +- **The kernel's boundary is the kernel's own decisions:** queues belong to a distribution in its own database + (D-94 c, superseded by the kernel's D-126: one database, the kernel's, S-190); signals and telemetry are observations, not claims ("a + measurement is not content anyone wrote", D-101); what is worth knowing crosses as claims and items through an + encoder (`encoder-substrate`); `propose`-gated actions are meant to reach the kernel's review lane, so a person + approves in one place. +- **Observability:** OpenTelemetry where the parts already speak it (the gateway, the runtimes, our processes), an + OTel Collector picked with the `research` skill, traces to a viewer and metrics to Prometheus, which the kernel's + `observer-prometheus` turns into observed claims; a component's card carries measured latency and cost. +- **Agents:** the orchestrator is an ordinary harness (S-185); sub-agents are harness sub-agents, OpenEnv + environments or MCP components (`docs/framework.md`, "Slots"). The one assistant of S-181 (the voice front end + and one loop over model rungs) is the assistant distribution's design (S-186). `scripts/trials/harness/candidates.json` + holds the surveyed harnesses. + +## The ladder (S-178 to S-183, placed by S-186) + +The multi-response ladder (System 1 at the model endpoint: compiled skills, then the fast, slow and cloud models, +chosen by a decider that learns from outcome-labelled experience) is a **distribution component**, built on OpenEnv +(S-186), not part of Substrate. Its design stands in S-178 to S-183; its code moves to `distributions/assistant/`. + +## Next, in order (2026-11-23) + +Done from the 2026-11-22 list: the catalog entry (S-176), compose into the kernel and back (S-177), the decider trial +and experience (S-179, S-183). + +1. **Done 2026-11-23 (S-192): all seven points pass; gates stay a `propose` tool (fastmcp caps `mcp` below 2, so no `input_required` yet).** The OpenEnv spike (S-184): `openenv` 0.12.0 in the tools image (or a trial container), one Postgres-backed + environment, and the seven points: (1) many agents' sessions share one live environment; (2) events reach a + subscriber in production mode; (3) `reset` clones a template database fast enough; (4) Claude Code runs through + the harness adapter; (5) against our model proxy via `ANTHROPIC_BASE_URL`, with an episode id in a header; + (6) a skill's answer reaches Claude Code in a form its loop accepts; (7) a rubric's score attaches afterwards to + every model call of its episode. Also: whether MCP's `input_required` (revision 2026-07-28) is final, for gates. + Done when each point has a result line in `.state/trials/openenv/` and a row in `DECISIONS.md`. +2. **Morphogen as the optimiser** (S-185): update `~/Projects/Morphogen` from GitHub (it is rebuild 5 here; main is + rebuild 7); install its plugin in the orchestrator's harness; one map skill (Substrate's writes the Backstage + entities, Morphogen adds cells from them); one cell on Substrate's own configuration judged end to end. Changes + to Morphogen go by pull request there (the `upstream` skill). +3. **The repository in its shape** (S-185, S-186): `distributions/assistant/` takes the companion, the voice head + and avatar, the worker, blocks and the skill gate, the ladder (proxy, deciders, experience, the decider trial); + envkit goes to MetaSoar's side; components and the judge (S-151) give way to Morphogen; Substrate keeps the + stack, the skills, the channel, the catalog and the adapters. In batches, each with `scripts/check.sh` and + `scripts/test.sh` passing. +4. **One database, the kernel's** (S-190): the kernel defines the schemas and the ways of doing things, and Substrate + follows them, so the `env` schema (objects' live state, queues, gates, experience) moves into the kernel's + database, by the kernel's D-126 superseding D-94 (c) (drafted on the kernel's branch `claude/one-database`). Then + the `substrate` database is empty and is dropped (its retired `store` schema went on 2026-11-23, S-191). Bifrost's `gateway` database is a third party's private store and stays apart + unless Bifrost can use a schema in the kernel's database (to check). +5. **The orchestrator's `orchestrate` and `optimize` skills**, hooks enforcing gates in the harness, and an **`rtfm` + skill** (S-189) for every agent: assume what it knows about a library, tool, API or standard is out of date; find + the manual for the exact version in use (the project's docs, `llms.txt`, the registry's page, a docs MCP server + where one is trusted); ingest it into the kernel with its source and version, so it is searched and recalled by + association and cited; and answer from it, not from memory. Rule 1 ("look it up, then pin it") as a skill. +6. **Everything else runs on top of the settled shape** (S-187): each distribution (the assistant, the SMB Foundry's + first cut), MetaSoar's experiments and every test suite run against Substrate through its contracts only. Done + when `scripts/test.sh` passes, each distribution comes up from its own folder, and MetaSoar's worlds run as OpenEnv + environments. +7. **The bootstrap instance** (S-187): what a new Substrate instance starts with, so the orchestrator knows itself + from the first run: a **snapshot map** of Substrate's own parts (the `catalog/` Backstage entities, the stack's + compose file in the kernel, S-176, S-177), **catalogs** of the candidates already researched for each intended + component (models, the gateway, harnesses, deciders, the environment standards; with their measurements), the + vocabularies (S-175), **Morphogen cells** for Substrate's own configuration, the default gates and privacy + rules, the skills, **agent-facing documentation** (S-189: more than skills: how the system works, its contracts, + each tool and each part, written for an agent to read and loaded into the kernel for recall, with the manuals of + the parts' exact versions fetched by `rtfm`), and a first task: map yourself, check the map against what runs. Loaded by one command into + an empty kernel. Done when a fresh machine's instance answers "what are you made of, and what could replace + each part?" from its own store. +8. **A second pass over the documentation** (S-187): README, `docs/framework.md`, the skills and each distribution's + README read cold by someone new; every concept explained once, where it is used. +9. **The ladder on OpenEnv and M-17's experiment** (S-186, MetaSoar): a task-family environment, the proxy in the + Anthropic format, rubric scores as outcomes, the frozen blind run (S-179). +10. **The SMB Foundry and other business opportunities** (S-188 c): in **a session of their own**, without the code + in context, **as soon as steps 6 to 8 are done**. The first customers are design partners and the most + valuable, paid or not. Starting point: `docs/research/Object environments prior art.md` (a five-day "map and + one gated automation" pilot). + +Later, built on all of this: mapping and modelling things beyond software, agents and organisations (the owner's +original "map anything" idea, `owner-vision` in S-117's terms). + +The telemetry collector and a process runtime (the old step 4) wait until a step needs them. ## Deferred @@ -60,6 +167,9 @@ publication and reproductions, the hosted mapper and hosted judging, the slot mo ## The owner's to decide -- Which game comes first (step 9), and which embodied environment after that (step 10). -- Rotating the Postgres password; putting the Gemma model at the gateway. +- Which game comes first and which embodied environment after it (the steps table's 9 and 10; a games distribution now). +- Rotating the Postgres password. - The licence and whether the repository goes public. +- Whether a Business-Source-licensed part (Nomad) may ever be a default; recommended no (S-173). +- When to migrate kernel v0's P-Plan IRIs to PROV-O and the profile's terms (S-175; a kernel change). +- Confirming the kernel's D-101 (the content framing) once the catalog entry has proved it or not. diff --git a/docs/privacy.md b/docs/privacy.md index 4295fa5..3ec10c5 100644 --- a/docs/privacy.md +++ b/docs/privacy.md @@ -21,3 +21,10 @@ The owner decides what each stream may do. These rules are the **default flow po (spec section 7, S-89): privacy is adjustable, because some of it cannot be kept on every machine or stream. The owner may loosen a rule for a named stream or label; each loosening is a decision in the review lane, saying who, when and why, and the rule's check then tests the policy as set rather than the default. + +**The assistant's experience (S-178, S-182).** The gate keeps one episode per model call (the scenario, the +response, the outcome), the rows System 1 is distilled from. P6 is loosened for this store only, by the owner's +decision (S-182): episodes keep the owner's words verbatim, with the text encrypted at rest, deletion of one episode, +a time range or all of it (P9; the embeddings and every derived row with it, since embeddings can be partly turned +back into text), and a retention period the owner sets (P7). The checks to build with it: a test that the stored text +is not readable without the key, and one that deleting leaves no embedding or derived row behind. diff --git a/docs/repos.md b/docs/repos.md index dc77ed5..f88e8b3 100644 --- a/docs/repos.md +++ b/docs/repos.md @@ -1,14 +1,14 @@ # The repositories and what each owns -| Repository | Owns | -| --- | --- | -| **Kernel** (OpenReplicant/kernel) | The store: claims with provenance, belief and clearance; review; recall; the memory profile (MCP); the business distributions (its D-84, D-115). | -| **Substrate** (this one) | The framework: environments (`environment/` on pgmq, and `envkit/`), the model gateway, gates, the companion, the voice head and avatar, the UI, the catalog, components and the judge. | -| **MetaSoar** | Research: the cognitive hypothesis (headline: impasse-driven compilation, M-17), atlas, the experiments, and the Soar 9.6.5 baseline. | -| **Morphogen** | The judge of MetaSoar's pull requests. Out of Substrate's build while the owner refactors it (rule 9). | - -## Dependencies - -MetaSoar -> Substrate -> Kernel. MetaSoar runs its experiments in Substrate's environments (envkit, S-161); Substrate keeps and reads its knowledge in the Kernel. Morphogen sits beside the chain and judges MetaSoar's pull requests; nothing imports it. - -Until MetaSoar depends on Substrate's copy of `envkit/`, its `atlas/cartographer.py` and `atlas/mover.py` import `envkit`, and `envkit/run.py` imports `atlas`. +The layers are in `docs/framework.md` (S-185). Every dependency between them is a contract (OpenEnv, MCP, Backstage +entity files, Morphogen's cell file, an OpenAI- or Anthropic-compatible model endpoint), never another project's code. + +| Repository | Owns | Depends on | +| --- | --- | --- | +| **Kernel** (OpenReplicant/kernel) | Postgres made into a kernel: knowledge (claims with provenance, belief and clearance; review; recall; the memory and `substrate` MCP profiles), interaction (objects, gated actions, events, queues: the `env` schema moves into its database, S-190), authentication, pluggability; its modules are data transformations and what happens at the Postgres level; its own distributions folder (`business`, `devops`, `papers`, `process-maps`) | Postgres | +| **Substrate** (this one) | The orchestrator kit: skills (`map`, `catalog`, `research`, `orchestrate`, `optimize`, `setup`, `upstream`), hooks, the channel, the catalog (`catalog/`), the adapters (OpenEnv, the model proxy, compose decoding), the reference stack (compose, the gateway, the tools container, scripts), this documentation; and, until Substrate's shape is settled, the distributions as folders (`distributions/`) | the contracts; the Kernel, Morphogen, Bifrost and Claude Code as default fillers | +| **Morphogen** (OpenReplicant/Morphogen) | The optimiser: cells, optimizers behind a judge they cannot edit, the still-works gate, the system guard, the evidence log; shipped as a Claude Code plugin with an MCP server. Its own repository on purpose: the judge's independence from what the optimizer edits is the point. Changes by pull request there | cell files; reads Backstage entities when present | +| **MetaSoar** (OpenReplicant/MetaSoar) | The research: cognitive architecture (impasse-driven compilation, M-17; System 1 from experience), its experiments on OpenEnv, atlas and the Soar 9.6.5 baseline | OpenEnv; the assistant distribution's ladder for M-17 | + +Until MetaSoar's worlds are OpenEnv environments (S-184), its `atlas/cartographer.py` and `atlas/mover.py` import +Substrate's `envkit`, and `envkit/run.py` imports `atlas`, so the two must be on one path. diff --git a/docs/research/Object environments prior art notes/bdi_llm.md b/docs/research/Object environments prior art notes/bdi_llm.md new file mode 100644 index 0000000..85ac453 --- /dev/null +++ b/docs/research/Object environments prior art notes/bdi_llm.md @@ -0,0 +1,97 @@ +# BDI agent architectures combined with LLMs, 2024-2026 + +Method note: checked 2026-11-23 with web search, GitHub/PyPI APIs and the papers' own PDFs (read via pdftotext). Licences and dates below are from the GitHub API "license" field unless stated. Not covered by any source I could read: the survey arXiv 2509.02515 (PDF unreadable to the fetcher; only a search-snippet description). Many search-summary claims were cross-checked against the PDFs; unverified items are in Gaps. + +## 1. Main LLM+BDI systems 2024-2026: what the LLM does vs what BDI does + +### Takeaway +The literature is small, mostly workshop/extended-abstract level, and splits into three patterns: (a) LLM as natural-language interface to a BDI agent (ChatBDI), (b) LLM as runtime plan/belief generator into a BDI plan library (Ciatto et al. ECAI 2025; Jarvis; Utah report), (c) LLM inside a rule-based BDI shell for believability (child-helpline agent). Measured evidence is thin: tiny samples, single domains, no head-to-head against plain LLM agents found. + +### Cited Findings +- ChatBDI (Gatti, Mascardi; AAMAS 2025 extended abstract): Jason inside JaCaMo "thinks"; CodeGemma "talks" and, with nomic-embed-text embeddings, "understands" (human message embedded and compared with the agent's context, mapped to the closest KQML literal). A meta-programming "chattification" injects plans into existing agents without touching their source. The LLM does not generate plans. Authors say the closest prior work is Frering et al. (closed source, only maps text to a predefined goto(X,Y)), and that Ricci et al. (AAMAS 2024 Blue Sky) only envisioned generative BDI. No quantitative evaluation in the abstract — [ChatBDI PDF](https://aamas.csc.liv.ac.uk/Proceedings/aamas2025/pdfs/p2541.pdf). Code: [VEsNA-ToolKit/chatbdi](https://github.com/VEsNA-ToolKit/chatbdi), last push 2026-01-08, 4 stars, GitHub shows no licence file (so default all-rights-reserved; do not reuse without asking) — GitHub API. The paper itself is CC BY 4.0. +- Generative BDI plan generation (Ciatto, Aguzzi, Battistini, Baiardi, Burattini, Ricci; ECAI 2025, FAIA 413): extends AgentSpeak(L) with a plan-generation procedure (PGP) working on demand, reactively after plan failure, or proactively; prototyped in JaKtA (a Kotlin Jason-like BDI technology). The agent spec carries natural-language descriptions of admissible goals/beliefs/actions; the LLM writes plans, the BDI cycle executes them and retracts on failure — [paper PDF](https://cris.unibo.it/bitstream/11585/1026414/3/FAIA-413-FAIA251223.pdf), [abstract page](https://apice.unibo.it/xwiki/bin/view/Publication/PlanGenerationBDIEcai2025). Measured: reactive PGP only, grid-world "reach home" task, 4 LLMs x 5 runs = 20 runs. Task Success Rate: GPT-4.1 100%, a second model 60%, DeepSeek V3 40%, Gemini 2.5 Pro 20% (the paper labels the 100% model "GPT-4"; Claude 3.7 thinking's figure was not clearly captured by my text extraction — check the PDF table). Plan-quality metrics included generalization count, redundancy, novel invented goals/beliefs, semantic misalignment. Experiment code: [pslab-unibo/experiment-2025-ECAI-generative-bdi-agents](https://github.com/pslab-unibo/experiment-2025-ECAI-generative-bdi-agents), Apache-2.0, last push 2025-08-05. Paper is CC BY-NC 4.0 (text). +- Jarvis (Raupp, Paulo, Chagas, UFSC; WESAAC workshop 2026): a CArtAgO artifact + two Jason internal actions. At runtime it introspects artifacts in the workspace (operation signatures, observable properties, natural-language manual), prompts an LLM for an AgentSpeak plan library, validates against discovered operations/arity/subgoals, injects surviving plans and beliefs. Case study: three agents, an air-conditioner artifact; with gpt-4.1-mini at temp 0.2 repeated runs gave a syntactically valid plan library on the first call, every AirConditioner plan accepted; about 1.5K input and 200 output tokens per learning episode. Authors explicitly do not claim: semantic safety (mode preconditions), reactive/proactive generation, failure-driven plan retraction, generality — [Jarvis PDF](https://sol.sbc.org.br/index.php/wesaac/article/download/45248/45009/), [abstract](https://sol.sbc.org.br/index.php/wesaac/article/view/45248). The paper credits Aguzzi et al. 2025 ("PlanchBDI") with unifying chattification and plan generation; I found only that one-line description of PlanchBDI. No repository link in the paper text. +- Self-aware BDI agent (Lawton, Sacharny, Henderson; Univ. of Utah tech report UUCS-26-001, 15 May 2026): full LLM-driven deliberation loop; LLM generates parameterized natural-language plan templates with role slots (no hand-authored plans), matches plans to beliefs via NLI, produces machine-verifiable satisfaction conditions with a three-tier verification, refines the plan library across rounds from environmental feedback and exports it to seed new agents. Eval: 53 GAIA level-1 questions, Qwen3-8B via vLLM: 13.2% (any round, simulation mode), 9.4% for both seeded and non-seeded single pass; authors say seeding improves reasoning structure but not raw accuracy, and that web-search/tool use is the bottleneck. Preliminary; no code link found in the text — [UUCS-26-001](https://www-old.cs.utah.edu/docs/techreports/2026/UUCS-26-001.pdf). +- Hybrid BDI-LLM child-helpline trainer (Al Owayyed, Denga, Brinkman; IVA 2025, arXiv 2509.16784): LLMs added to a rule-based BDI for intent recognition, response generation and a bypass; Study 1 LLM components non-inferior to human-crafted responses; Study 2 (n=37, within-subject) hybrid rated more believable than rule-based; engagement effect inconclusive (posterior 0.845, 95% HDI [-0.149, 0.465]). Code availability not stated — [arXiv](https://arxiv.org/abs/2509.16784). +- astra-langchain4j (Collier, Beaumont, Ciortea; arXiv 2601.21879): ASTRA agent language (not Jason) gets an LLM module built on LangChain4j; examples include tic-tac-toe with LLM players. Code at gitlab.com/astra-language/astra-core and Maven Central `com.astralanguage:astra-langchain4j`; licence not stated in what I could read; I could not extract the paper body — [arXiv PDF](https://arxiv.org/pdf/2601.21879). +- Related, by description only: NatBDI (Ichida et al.) matches natural-language plans to beliefs with NLI and falls back to reinforcement learning — cited in the ChatBDI paper above. Cetana (PyPI 0.1.0, "auditable BDI agents for the LLM era") is early-stage — [search listing](https://pypi.org/project/cetana/); not inspected. +- Survey: arXiv 2509.02515 "Contemporary Agent Technology: LLM-Driven Advancements vs Classic Multi-Agent Systems" mentions BDI+LLM hybrids; I could not read it — [arXiv](https://arxiv.org/pdf/2509.02515). + +### Inferences +- The only quantified result on LLM-written BDI plans (Ciatto) shows large model dependence (20%-100% success on one simple task, N=5 per model); BDI structure does not remove the dependence on the planner model, but gives validators (admissible goals/beliefs, arity checks) and failure-driven retraction. +- No source I found shows BDI+LLM beating a plain tool-calling LLM agent on a standard benchmark; the Utah GAIA numbers are low and not compared to a baseline. +- Common pattern worth copying: the LLM proposes into a typed vocabulary, a symbolic validator filters, the BDI layer owns commitment (what is being pursued) and retraction on failure. + +### Gaps +- No full text of the survey 2509.02515; no details of PlanchBDI (Aguzzi et al. 2025) beyond one line; Frering et al. not located; JaKtA repo/licence not verified (the guessed GitHub path 404'd); ChatBDI licence absent. +- No head-to-head vs non-BDI LLM agents found. + +## 2. Jason, JaCaMo, CArtAgO today + +### Takeaway +All three are alive, Java/JVM, and usable over a network only through bridges you write; no native Python API was found. Jason and JaCaMo are LGPL-3.0 (acceptable); CArtAgO is reported GPL-3.0 by the GitHub API (needs separate-process treatment, and check the LICENSE file directly since older CArtAgO releases were LGPL by my memory — unverified). + +### Cited Findings +- Jason: latest release v3.3.3, published 2026-10-15 (previous v3.3.0 on 2024-02-21); LGPL-3.0; last push 2026-10-30; 262 stars; Java — [GitHub release API](https://api.github.com/repos/jason-lang/jason/releases/latest), [repo](https://github.com/jason-lang/jason). +- JaCaMo: latest release v1.3.1, published 2026-08-31; LGPL-3.0; last push 2026-10-16; 20 stars — [releases API](https://api.github.com/repos/jacamo-lang/jacamo/releases/latest), [repo](https://github.com/jacamo-lang/jacamo). +- CArtAgO: GPL-3.0 per GitHub API; last push 2024-07-15; tags up to v3.1 — [repo API](https://api.github.com/repos/CArtAgO-lang/cartago). The latest-release endpoint returned 404 (tags only). +- Integration pattern for LLMs: Jarvis shows an LLM endpoint can be wrapped as a CArtAgO artifact exposing operations and publishing usage metrics as observable properties; ChatBDI uses KQML messages as the bridge — sources in section 1. +- CArtAgO is the framework for the Agents and Artifacts model — environment as workspaces containing agents and artifacts — [CArtAgO chapter listing](https://apice.unibo.it/xwiki/bin/view/Publication/CartagoE4masIII). + +### Inferences +- Use from Python: no evidence of a maintained Python binding; practical routes are a JVM sidecar with a message/HTTP bridge (e.g. a CArtAgO artifact, which Jarvis already shows for an LLM, could front HTTP/Postgres), or reimplement the cycle in Python. Treat as unverified design option, not a documented feature. +- GPL CArtAgO could only be a separately run service under the repo's rule S-146. + +### Gaps +- Did not verify CArtAgO's current LICENSE file text or JaCaMo REST/web interfaces; did not check Jason's own documented Python/network interfaces. + +## 3. Agents & Artifacts (A&A) meta-model and LLM use + +### Takeaway +A&A models the environment as first-class artifacts in workspaces, which maps closely onto "everything is an object". Its only direct LLM use I found is Jarvis (artifact introspection as the grounding substrate for LLM plan generation). + +### Cited Findings +- Jarvis states artifacts "already represent environmental affordances through operation signatures, observable properties, and often a natural-language description", and argues planning over artifacts discovered live aligns the LLM's action model with CArtAgO's environment model rather than a design-time action list — [Jarvis PDF](https://sol.sbc.org.br/index.php/wesaac/article/download/45248/45009/). +- Jarvis's introspection works "without binding to a live workspace" and the Jarvis artifact itself publishes accepted/rejected-plan and token counts as observable properties — same PDF. +- A 2023 AAMAS paper describes a hypermedia platform where infrastructure executes computational artifacts as defined in the JaCaMo meta-model — [AAMAS 2023 p2499](https://www.southampton.ac.uk/~eg/AAMAS2023/pdfs/p2499.pdf) (title not read; from search listing). A vision paper on LLMs filling information gaps in hypermedia MAS exists (via search summary; not opened). + +### Inferences +- From background knowledge (not sourced here): A&A concepts are artifacts with usage interface (operations), observable properties (state agents perceive as beliefs), signals (events), workspaces (scoping), and focus (subscription). These line up with the design's objects/properties/actions/events; permission gates and Postgres-as-blackboard are not part of A&A. Verify against the CArtAgO docs before citing. + +### Gaps +- Official A&A/CArtAgO documentation not fetched; no LLM paper beyond Jarvis found using A&A. + +## 4. Plan learning/compilation from experience + +### Takeaway +Classic BDI learning exists (learning plan context conditions from experience) but I found no 2024-2026 system that compiles LLM episodes into BDI plans with Soar-style chunking and measured evidence. Closest: the Utah plan-library refinement, Ciatto's reactive generation, Jarvis's persistent generated plans. + +### Cited Findings +- Utah agent: refines plan library over rounds with failure feedback and seeds other agents; no accuracy gain from seeding (9.4% vs 9.4%) on 53 GAIA questions with Qwen3-8B — [UUCS-26-001](https://www-old.cs.utah.edu/docs/techreports/2026/UUCS-26-001.pdf). +- Ciatto et al.: plans generated after plan failure (reactive) and retracted on failure; Jarvis keeps generated plans until termination (no retraction) — sections above. +- Older learning in BDI (Singh, Sardina, Padgham): learn plan selection/context conditions from experience, not new plans — [IJCAI 2011](https://ijcai.org/proceedings/2011/420), via search listing. + +### Inferences +- The evidence that distilled plans improve a model's accuracy is weak so far; what plan libraries reliably give is structure, auditability and cheaper reuse (about 1.5K input tokens once per learned plan in Jarvis). + +### Gaps +- No Soar-chunking-with-LLM or case-based BDI+LLM paper found; not searched in the Soar literature (outside BDI scope). + +## 5. Python-native BDI frameworks + +### Takeaway +MASPY (MIT, active) is the best-fit Python BDI framework; SPADE-BDI is a BDI layer on XMPP-based SPADE; neither has LLM-specific evidence. + +### Cited Findings +- MASPY (laca-is/MASPY): Python BDI MAS framework with AgentSpeak-like declarative style; MIT; last push 2026-11-13; 27 stars; 21 open issues — [GitHub API](https://api.github.com/repos/laca-is/MASPY), AAMAS 2026 paper YIGW5980 describes it (via search summary; PDF unreadable). +- SPADE_BDI: PyPI 0.3.3, uploaded 2026-07-28; runs AgentSpeak ASL files with KQML performatives; fork javipalanca/spade_bdi is MIT, pushed 2026-09-01; original upstream sfp932705 has no clear licence and last push 2022 — [PyPI](https://pypi.org/pypi/spade_bdi/json), [fork API](https://api.github.com/repos/javipalanca/spade_bdi). Depends on the SPADE/XMPP stack. +- PROFETA (Python, BDI robotics), agent-bdi, cetana (0.1.0) surfaced but were not verified — [search results](https://pypi.org/project/agent-bdi/). + +### Inferences +- For Postgres-blackboard design, a hand-rolled cycle (belief/goal/intention tables, plan library as rows) is likely lighter than adopting MASPY or SPADE, whose runtimes own their own belief stores; MASPY is the one to read for semantics. + +### Gaps +- Did not inspect MASPY's code, tests, release cadence or LLM support; PROFETA licence/maintenance unchecked. + +## Overall answer to "does BDI give a proven structure?" +Proven as a structure of explicit beliefs, desires, intentions and plan libraries in agent programming (decades), but not proven with LLMs: 2024-2026 LLM+BDI work is prototype-scale (single domains, N=5-53 items, no strong baselines). What the papers do demonstrate: (1) typed vocabulary plus validator before an LLM-authored plan enters the library, (2) failure-driven plan retraction, (3) artifacts' operation signatures and observable properties as the grounding for LLM plan generation, (4) LLM-quality dependence is large. diff --git a/docs/research/Object environments prior art notes/environment_standards.md b/docs/research/Object environments prior art notes/environment_standards.md new file mode 100644 index 0000000..c63c9d9 --- /dev/null +++ b/docs/research/Object environments prior art notes/environment_standards.md @@ -0,0 +1,137 @@ +# Environment and object-interface standards compared with the Substrate design (as of 2026-11-23) + +Method note: facts below were read from the cited page in this session (WebFetch returns a model-written summary of the page, so quoted detail is only as good as that summary). Items I could not fetch are in Gaps. "Inferences" are mine, not sourced. + +## 1. OpenEnv (reset/step/state/close, manifests, governance, RFCs, harness integration) + +### Takeaway +OpenEnv is a BSD-3 episodic Gym-style protocol (reset/step/state over WebSocket, containers, MCP tools at /mcp) governed by a multi-company committee and still "early development". It already has a "production mode" that serves MCP tools of a persistent service without episode control, and RFC 005 runs an unmodified Claude Code inside an environment, so a persistent live Substrate environment can expose an OpenEnv interface cheaply, but only as a thin adapter; its object/gate/event model is not part of OpenEnv. + +### Cited Findings +- Licence BSD 3-Clause; "early development, so APIs may still change"; reset/step/state sync or async over WebSocket; each environment is a Docker image; CLI `openenv init/validate/push/serve/import`; ~2.9k stars, 40+ environments, integrations with TRL, Unsloth, SkyRL, etc. — [GitHub meta-pytorch/OpenEnv](https://github.com/meta-pytorch/OpenEnv) +- Governance: multi-company Technical Committee since June 2026 (Meta-PyTorch, Reflection, Nvidia, Microsoft, Prime Intellect, Mercor, Fleet AI, Modal, Unsloth, BenchFlow, Hugging Face); biweekly meetings; RFC loop; Ben Burtenshaw acts as BDFL early on; no formal foundation governance in the file — [GOVERNANCE.md](https://github.com/huggingface/OpenEnv/blob/main/GOVERNANCE.md) (page dates internally inconsistent per the fetch). +- Maintainers' post of 2026-10-22 says they are "joining AAIF" (Agentic AI Foundation) and a public AAIF proposal seeks a vendor-neutral home; not yet confirmed as completed — [AAIF blog](https://aaif.io/blog/training-agents-for-real-world-tasks-with-openenv) +- June 2026 HF post: OpenEnv is a protocol layer (publish/deploy/consume), Gymnasium-style API over HTTP/WebSocket in Docker, "MCP as a first-class citizen"; roadmap includes harness integration and env auto-validation; says nothing on live/persistent environments — [HF blog](https://huggingface.co/blog/openenv-agentic-rl) +- Repo location is inconsistent across sources: meta-pytorch/OpenEnv, huggingface/OpenEnv, and github.com/openenv/OpenEnv all appear; the HF post says it now lives at huggingface/OpenEnv — [HF blog](https://huggingface.co/blog/openenv-agentic-rl), [GitHub](https://github.com/meta-pytorch/OpenEnv) +- RFC index (rfcs/ directory): 000 design principles/roadmap, 001 basic abstractions, 002 framework spec, 003 MCP support (traditional tool calling), 004 rubric/reward, 005 agentic harness integration (OpenClaw, Claude Code), 006 harness interception/token capture, 008 env auto-validation, 010 env-token world modelling, 011 versioned env metadata / ARD interchange, 012 Harbor, 014 environment services (brokered, budgeted external access). 007, 009, 013 not in the listing. Lifecycle: In Review, Accepted, Implemented, Rejected, Superseded — [rfcs dir](https://github.com/meta-pytorch/OpenEnv/tree/main/rfcs), [rfcs README](https://raw.githubusercontent.com/meta-pytorch/OpenEnv/main/rfcs/README.md) +- Numbering conflict: the HF blog calls RFC 003 "encapsulation of MCP tools through environment abstraction" and lists 006 as external rewards and 007 as tasksets via HF datasets; the repo index differs (006 = harness interception). Treat numbers as unstable — [HF blog](https://huggingface.co/blog/openenv-agentic-rl) vs [rfcs dir](https://github.com/meta-pytorch/OpenEnv/tree/main/rfcs) +- I did not find a "RFC 0054" in any source. +- MCP in OpenEnv: dual boundary. Gym control plane (`/ws`, reset/step/state) for the trainer; MCP tools over `/mcp` for agents. In simulation, MCP calls flow through `step()` as `ListToolsAction`/`CallToolAction`. `reset`, `step`, `state`, `close` are reserved tool names. RFC 003 "proposes MCP as the standard interface for all agent-facing actions" and is still In Review; only echo_env, finqa_env (and calendar_env via wrapper) are MCP-backed, most others use custom action types — [HF docs: MCP environments](https://huggingface.co/docs/openenv/main/en/tutorials/mcp-environment) +- Production mode: "serves the environment's MCP tools directly to an agent or another client, with no episode control"; `/reset`,`/step`,`/state` are not registered; `/ws` still registered (restrict it); mode-aware tools; "simulation mode models trajectory time, production mode models service time" — [HF docs: simulation vs production](https://huggingface.co/docs/openenv/main/en/guides/simulation-vs-production) +- RFC 005 (In Review; created 2026-02-16, revised 2026-10-07): `HarnessEnvironment` wraps an external harness (Claude Code, OpenClaw) running its own loop; each `step()` is one conversational turn; tools injected through a localhost streamable-HTTP MCP bridge written into the harness's MCP config; no LLM-call interception or proxy in this RFC (LLM_REQUEST/LLM_RESPONSE events exist but are unpopulated); no concurrent sessions; network isolation not enforced; Claude Code adapter merged (#1291), OpenClaw adapter not — [RFC 005](https://github.com/huggingface/OpenEnv/blob/main/rfcs/005-agentic-harnesses.md) +- Claude Code tutorial: runs `claude -p --input-format stream-json`, built-in tools disabled (`--tools ""`), environment tools via `--mcp-config`; `ANTHROPIC_BASE_URL` in `HarnessConfig.env_vars` can point it at an Anthropic-compatible endpoint — [HF tutorial](https://huggingface.co/docs/openenv/main/en/tutorials/claude-code-harness) +- Harness comparison: white-box (trainer owns the loop), black-box via Harbor/RFC 006 where "a proxy records every model call it makes" to build a `TrainingTrace` (token ids, logprobs, against vLLM or SGLang), and agent-inside-environment (RFC 005). Only Harbor records tokens — [HF: Harnesses in OpenEnv](https://huggingface.co/docs/openenv/main/en/tutorials/harnesses) +- A GitHub issue asks whether RFC 005 is still in effect and notes `openenv.core.harness` seems loosely related; no maintainer answer seen — via [search result](https://gh.r-mj.com/huggingface/OpenEnv/issues/696) (secondary mirror). + +### Inferences +- Cheapest compatible path: an OpenEnv "production mode" server (`/mcp`) whose tools are the Substrate gated actions, plus an optional simulation-mode shim (`reset` = snapshot/branch of the DB or a fresh schema, `step` = apply action and advance, `state` = read). A single live shared database does not fit `reset`/episode semantics; reset would need a per-episode schema or a transaction/branch copy. +- OpenEnv's harness-proxy idea (RFC 006/Harbor: proxy on the model endpoint recording tokens) matches Substrate's gateway-proxy design; Substrate could emit the same trace shape for training a System 1. +- OpenEnv's gating is only "reserved names" and a note to restrict `/ws`; it has no free/propose/deny notion, so Substrate's gates would be an extension surfaced as tool errors or `input_required`-style results. +- Risk: spec churn (RFC numbers disagree, repo moves, early-development warning). Adopt by thin adapter, do not build the core around it. + +### Gaps +- Could not read RFC 002/003/006 text directly (404 on guessed paths); statuses of 001-004 not confirmed. +- No source for "RFC 0054" or for the manifest file format (the README summary did not describe a manifest); `openenv.yaml` details unverified. +- Whether the AAIF move completed is unconfirmed. + +## 2. W3C Web of Things Thing Description + +### Takeaway +TD 1.1 is a W3C Recommendation (Dec 2023) whose properties/actions/events/forms/security model maps almost one-to-one to Substrate's object model, and TD 2.0 is only a First Public Working Draft (Nov 2025). It is the best candidate to expose objects (as generated Thing Descriptions), with MCP as the transport LLMs use. + +### Cited Findings +- TD 1.1: W3C Recommendation, 5 Dec 2023, supersedes TD 1.0; defines properties (read/write/observe), actions, events, forms (hypermedia controls serialising protocol bindings), security schemes (nosec, basic, digest, bearer, apikey, oauth2, combo, auto), JSON/JSON-LD, Thing Models; W3C Software and Document licence applies — [TD 1.1](https://www.w3.org/TR/wot-thing-description11/) +- TD 2.0: First Public Working Draft 4 Nov 2025; no newer draft found; a proposed 2026 WG charter lists it as a further iteration; WoT documentation still lists TD 1.1 as current — [TD 2.0 FPWD](https://www.w3.org/TR/2025/WD-wot-thing-description-2.0-20251104), [proposed charter](https://www.w3.org/2026/07/wot-wg-2026.html), [WoT docs](https://www.w3.org/WoT/documentation/) +- node-wot (Eclipse Thingweb): dual EPL-2.0 or W3C Software and Document Licence; HTTP(S), CoAP(S), MQTT full; WebSocket server only; OPC-UA, NETCONF, Modbus, M-Bus client only; Node 20+; ~196 stars; 3,076 commits — [node-wot](https://github.com/eclipse-thingweb/node-wot) + +### Inferences +- Mapping: Substrate property = TD property (observable = subscribe); action = TD action; event/pgmq topic = TD event; gate (free/propose/deny) has no native TD field and would be an extension vocabulary term or a form-level annotation; Postgres roles/RLS map to security definitions (bearer/oauth2) plus an extension for per-affordance policy. +- Traits-not-types fits TD Thing Models (templates) plus JSON-LD `@type` arrays; nesting environments maps to links/`tm:` composition rather than a native construct. +- Generating TDs from the object tables is low cost and adds discoverability for non-LLM clients; node-wot as a runtime is optional (Node dependency; Substrate rule of nothing on host means a container). + +### Gaps +- Did not read TD's full text beyond the first 100k characters; did not verify TD 2.0 feature list. + +## 3. Agents & Artifacts (A&A) and CArtAgO + +### Takeaway +A&A is the closest academic precedent for "environment as programmable first-class objects": artifacts offer operations and observable properties, emit signals, live in workspaces, and agents focus on the artifacts they care about. Copy the vocabulary and focus semantics; skip the BDI/Jason coupling. + +### Cited Findings +- Ricci, Piunti, Viroli, "Environment programming in multi-agent systems: an artifact-based perspective", Autonomous Agents and Multi-Agent Systems 23(2):158-192 (2011): environment as first-class programmable abstraction, based on the A&A meta-model, implemented by CArtAgO — [UniBo record](https://cris.unibo.it/handle/11585/108512) +- Artifacts live in workspaces; operations form the usage interface, observable properties report state, signals are a separate percept for events; an agent "focusing" on an artifact receives its property updates (in Jason, mapped to beliefs) and perceives signals; a predefined workspace artifact handles creating, looking up, linking, and focusing artifacts — secondary sources: [JaCaMo/CArtAgO summary search](https://arxiv.org/pdf/2207.09708), [EMAS 2023 paper](https://emas.in.tu-clausthal.de/2023/papers/EMAS_2023_paper_3263.pdf), [CArtAgO by example (unofficial copy)](https://www.scribd.com/document/385336024/cartagoByExamples-pdf) + +### Inferences +- Direct matches: your "agents subscribe to the streams they want" = focus; observable properties = columns with change notification; signals = pgmq events; workspace = environment that nests. Copy: focus as an explicit subscription row, a distinction between state (observable property, replayable) and signal (transient event), and operations that can block/fail with feedback. +- Differences: A&A artifacts are typed classes in code; yours are trait-based and data-driven. A&A has no permission gate (propose/approve); that is your addition. + +### Gaps +- Official CArtAgO/JaCaMo docs and licence not fetched (SourceForge redirect not followed); licence unverified here. + +## 4. MCP as an object model, and the MCP Registry + +### Takeaway +MCP gives you tools (actions), resources with URIs and subscriptions (observable properties), prompts, and a registry for discovery; resource subscriptions are being replaced in the 2026-07-28 revision by one `subscriptions/listen` stream. It is the right joining surface for tools and for LLM-facing views of objects, but it has no object identity beyond URIs and no gate semantics. + +### Cited Findings +- 2025-11-25 resources: URI-identified; `resources/list`, `read`, templates (RFC 6570); optional `subscribe` and `listChanged` capabilities; `notifications/resources/updated`; annotations (audience, priority, lastModified); resources are "application-driven" — [MCP resources spec](https://modelcontextprotocol.io/specification/2025-11-25/server/resources) +- 2026-07-28 revision changelog (as served at that URL; whether it is final or draft was not stated on the page, and a search summary called it "draft"): removes protocol-level sessions and the initialize handshake (stateless, version and capabilities in `_meta`); adds `server/discover`; replaces `resources/subscribe` and the GET endpoint with `subscriptions/listen`; tasks moved to an extension with polling (`tasks/get`, `tasks/update`); Multi Round-Trip Requests (`input_required` results) replace server-initiated sampling/elicitation; deprecates Roots, Sampling, Logging; `ttlMs`/`cacheScope` on list/read results; OpenTelemetry trace context in `_meta`; Client ID Metadata Documents over Dynamic Client Registration; feature lifecycle with 12-month deprecation window — [changelog](https://modelcontextprotocol.io/specification/2026-07-28/changelog) +- MCP Registry: preview launched 2025-09-08, API freeze for v0.1 from 2025-10-24, "breaking changes or data resets may occur", servers published with `mcp-publisher`; I did not confirm a GA date — [registry repo](https://github.com/modelcontextprotocol/registry) +- MCP is a founding project of the Agentic AI Foundation (Linux Foundation, 9 Dec 2025) with goose and AGENTS.md — [Linux Foundation](https://www.linuxfoundation.org/press/linux-foundation-announces-the-formation-of-the-agentic-ai-foundation); one arXiv paper's claim that AAIF also hosts A2A is not confirmed by this source. + +### Inferences +- MRTR `input_required` is a natural carrier for the `propose` gate: a tool call returns "input required: human approval", and a retry carries the approval. Also matches OpenEnv's tool-error channel. +- Stateless MCP matches a database-as-state design: the server holds no session, state lives in Postgres. +- Expose each object as resources (`substrate://object/{id}`), with change feeds via `subscriptions/listen` mapped from pgmq; expose actions as tools; publish the MCP server entry in the Registry only if a public server is wanted. +- Plan for the 2026-07-28 migration (subscribe removal) if building on resource subscriptions. + +### Gaps +- Final/draft status of 2026-07-28 unverified; MCP Registry GA status and licence not confirmed; MCP tools spec page not re-read. + +## 5. Other 2025-2026 interface standards (CUBE, Agent Spec, harness papers, A2A, AsyncAPI, CloudEvents, ROS 2, Home Assistant, Gymnasium) + +### Takeaway +Only A2A (stable v1.0), CloudEvents (CNCF graduated) and AsyncAPI are mature; CUBE, Agent Spec and OpenEnv are young and benchmark/portability-oriented. Adopt CloudEvents for event envelopes and borrow A2A's task states for long-running actions; ignore Agent Spec and CUBE except as export targets; Gymnasium only matters if a training adapter is needed. + +### Cited Findings +- CUBE (Common Unified Benchmark Environments): position paper by Lacoste et al., arXiv 2603.15798 (Mar 2026), CC BY 4.0; "protocol standard built on MCP and Gym" with task, benchmark, package, registry layers — [arXiv](https://arxiv.org/abs/2603.15798). The AI Alliance package is alpha with Tool, Task, Benchmark, Observation, Action interfaces; ServiceNow principal developer — [cube-standard](https://pypi.org/project/cube-standard/), [search summary](https://the-ai-alliance.github.io/cube-standard/about) +- Open Agent Specification (Oracle): declarative framework-agnostic language for agents and workflows; SDK PyAgentSpec, reference runtime WayFlow; dual UPL-1.0 / Apache-2.0; arXiv 2510.04173 — [GitHub](https://github.com/oracle/agent-spec), [arXiv](https://arxiv.org/html/2510.04173v3) +- arXiv 2610.40917 (Gertler, Novelli, Floridi, 29 Oct 2026) "Towards Portable Specification of the Agent Harness": eight harness components; proposes a portable specification recording which model ran in which harness; harness as "a versioned part of the system" — [arXiv](https://arxiv.org/abs/2610.40917) +- arXiv 2606.10106 (de Macedo, 8 Jun 2026): necessary and sufficient conditions for an agent harness, applied to Claude Code, Codex CLI, Aider, Cline, OpenHands, SWE-agent — [arXiv](https://arxiv.org/abs/2606.10106) +- arXiv 2608.23953 (Dai, 25 Aug 2026): three harnesses converge on a standard loop, an append-only replayable session record, model quirks as data, progressive disclosure, explicit extension points; the one non-converged axis is external verifiability (tamper-evident record) — [arXiv](https://arxiv.org/abs/2608.23953) +- A2A: v1.0.0 is latest; AgentCard, Task (SUBMITTED, WORKING, INPUT_REQUIRED, AUTH_REQUIRED, COMPLETED, FAILED, CANCELED, REJECTED), Message, Artifact, Part; streaming and push webhooks; `A2A-Version` header — [A2A spec](https://a2a-protocol.org/latest/specification/). Donated to the Linux Foundation 23 Jun 2025; 150+ organisations; v1.0 dated March/April 2026 with sources disagreeing (an arXiv paper says Jan 2026) — [LF press](https://www.linuxfoundation.org/press/a2a-protocol-surpasses-150-organizations-lands-in-major-cloud-platforms-and-sees-enterprise-production-use-in-first-year) +- CloudEvents: CNCF graduated 25 Jan 2024; 1.0.2 current stable, 1.0.3 in working draft — [CloudEvents spec](https://github.com/cloudevents/spec), [CNCF](https://cncf.io/announcements/2024/01/25/cloud-native-computing-foundation-announces-the-graduation-of-cloudevents) +- AsyncAPI 3.0.0: channels, operations (send/receive), messages, servers, bindings; Apache-2.0; 3.1.0 also listed — [AsyncAPI 3.0.0](https://www.asyncapi.com/docs/reference/specification/v3.0.0) +- Home Assistant entity model: entities inherit `Entity` via platform classes; `state` written to a state machine; attributes; stable `unique_id` for the entity registry; `device_info` links to a device; unavailable shows as `unavailable` — [HA developer docs](https://contributors.home-assistant.io/core/entities/entity-class/). Services and `state_changed` events were not on that page. +- Gymnasium 1.x: `reset(seed, options)` returns (obs, info); `step` returns terminated and truncated separately; 1.0 changed vector autoreset — [Gymnasium migration guide](https://gymnasium.farama.org/introduction/migration_guide/), [v1.0 release](https://farama.org/Gymnasium-v1.0) +- ROS 2: Jazzy is LTS to May 2029; Kilted (May 2025) support ends Nov 2026 — [Jazzy release](https://docs.ros.org/en/jazzy/Releases/Release-Jazzy-Jalisco.html), [Kilted](https://docs.ros.org/en/kilted/Releases/Release-Kilted-Kaiju.html). The topic/service/action/parameter concept page was blocked (Anubis); I rely on general knowledge, not a cited source, for that mapping. + +### Inferences +- CloudEvents: use as the envelope for events in pgmq/the append-only record (id, source, type, time, subject, data); cheap, graduated, and gives Substrate events a standard export for free. +- A2A: expose a Substrate agent object as an A2A server (AgentCard from its trait/card, Task states from a proposed action's lifecycle: propose -> INPUT_REQUIRED -> WORKING -> COMPLETED/REJECTED). Optional, because A2A is agent-to-agent while your agents share a database. +- Home Assistant is the best practical precedent for an entity registry with stable ids, state plus attributes, device grouping, and availability; its conventions (unique_id, availability) are worth copying. +- ROS 2 (by general knowledge, uncited): topics = streams, services = request/response, actions = long-running goal/feedback/result, parameters = per-node config; the "action with feedback and cancel" shape maps to propose-then-run actions. +- Harness papers: 2608.23953's finding that tamper-evident external verifiability is the unconverged axis aligns with your append-only record; 2610.40917's "harness as versioned part of the system" supports recording harness/model per run in the record. Neither is a standard to adopt. +- Agent Spec and CUBE: ignore as core; export of an agent's definition to Agent Spec is possible later. + +### Gaps +- ROS 2 concept docs, HA services/events, PettingZoo licence, Gymnasium licence, CUBE reference implementation licence, and the A2A security sections were not verified. A2A date conflict unresolved. + +## 6. Any existing system combining DB-as-environment, object actions, gates, and harnesses joining via a model-endpoint proxy? + +### Takeaway +I found no single system that combines all of these. Pieces exist separately: Postgres RLS for agent permissions, blackboard testbeds, SpacetimeDB-style database-as-backend, and OpenEnv/Harbor's model-call proxy for token capture; no source found with a permission gate of free/propose/deny over object actions with harnesses joining unmodified. + +### Cited Findings +- Search found Postgres row-level security guidance for agents (one role per agent; table owners bypass RLS unless FORCE ROW LEVEL SECURITY; unique/foreign-key constraints can leak) and a pgEdge article describing an action ledger in Postgres with RLS per agent role — [pgEdge](https://www.pgedge.com/blog/going-rogue-autonomous-ai-agents-and-postgres), [secondary guide](https://agentsecurityreview.com/posts/postgresql-permission-boundaries-for-database-connected-agents) +- Terrarium: blackboard testbed for multi-agent safety, privacy and security studies (arXiv 2510.14312) — [arXiv](https://arxiv.org/pdf/2510.14312) +- SpacetimeDB: tables plus transactional reducers, clients subscribe to queries and get incremental updates; reducers return no data; licence Business Source License 1.1 converting to AGPL v3 with linking exception (source-available, not permissive) — [SpacetimeDB FAQ via search](https://spacetimedb.com/docs/intro/faq), [NuGet licence](https://www.nuget.org/packages/SpacetimeDB.Runtime/2.8.0/License) +- OpenEnv/Harbor's proxy that "records every model call" the agent makes is the nearest analogue to the model-endpoint proxy — [HF: Harnesses](https://huggingface.co/docs/openenv/main/en/tutorials/harnesses) +- pgmq as an agent message queue and the phrase "database is the environment": no source found. + +### Inferences +- The combination appears novel in what I could find, but absence of search hits is weak evidence; a search of GitHub for Postgres-backed agent frameworks was not done. +- SpacetimeDB's licence fails Substrate's permissive/LGPL rule for linking; as a fetched-at-setup separate container it would need S-146's process-boundary treatment, and its reducer model differs from Postgres RLS. + +### Gaps +- No direct search of GitHub or arXiv for pgmq-based agent environments, Letta/other agent-memory frameworks, or LangGraph checkpoint-in-Postgres systems, which may be partial precedents. diff --git a/docs/research/Object environments prior art notes/foundry_alternatives.md b/docs/research/Object environments prior art notes/foundry_alternatives.md new file mode 100644 index 0000000..826c635 --- /dev/null +++ b/docs/research/Object environments prior art notes/foundry_alternatives.md @@ -0,0 +1,87 @@ +# Open-source and self-hostable systems resembling Palantir Foundry's Ontology (as of 2026-11-23) + +Method note: licences and release/activity data below were read from the GitHub API (repo metadata, latest release, LICENSE files via `gh api`) on 2026-11-23 unless marked. Where GitHub reported NOASSERTION I read the LICENSE file head. Palantir facts come from palantir.com/docs fetched through a summarising fetch tool, so they are second-hand paraphrase of the primary pages. Vendor blogs and "open-source Palantir" articles are treated as claims. + +## 1. What exactly is Palantir's Ontology model? + +### Takeaway +Palantir defines the Ontology as an operational layer over datasets, virtual tables and models, with a semantic half (object types, properties, link types) and a kinetic half (action types, functions, dynamic security). Agents reach it through the OSDK, the Ontology MCP (OMCP) and Palantir MCP. + +### Cited Findings +- The Ontology is "an operational layer for the organization", sitting on top of datasets, virtual tables and models and connecting them to real-world counterparts. Semantic elements: objects, properties, links. Kinetic elements: actions, functions, dynamic security. — [Palantir Ontology overview](https://www.palantir.com/docs/foundry/ontology/overview/) +- Datasources are mapped into "objects, properties, and links". Interfaces are Ontology types describing the shape of an object type and its capabilities, giving polymorphism across object types. — [Palantir Ontology overview](https://www.palantir.com/docs/foundry/ontology/overview/) +- Functions "provide a way to author and evolve business logic with arbitrary complexity". — [Palantir Ontology overview](https://www.palantir.com/docs/foundry/ontology/overview/) +- An action type defines a set of changes to objects, property values and links applied in one step plus side effects. Each action is "a single transaction that changes the properties of one or more objects". Components: rules (the changes), parameters (form inputs), submission criteria (validation, separate page), permissions (who may run it), side effects (notifications, webhooks), function-backed actions. — [Palantir action types overview](https://www.palantir.com/docs/foundry/action-types/overview/) +- Writeback: committed edits show in all applications, and the latest object data with user edits is stored in the object type's writeback dataset. — [Palantir action types overview](https://www.palantir.com/docs/foundry/action-types/overview/) +- OMCP exposes "your application's ontology resources (such as object types, action types, and query functions)" as MCP tools; agents can read objects, run predefined actions and query data. Which actions an agent may take is restricted through application restrictions and permissions. — [Ontology MCP overview](https://palantir.com/docs/foundry/ontology-mcp/overview/) +- OMCP is a Developer Console feature, described as beta, limited by application scopes; Palantir MCP (builder-oriented) can modify ontology types but cannot write ontology data; OSDK generates Python, Java and TypeScript SDKs from an ontology. Warning on the OMCP page: with LLMs hosted outside AIP, Palantir data is exposed to an external client. — search summary of [Palantir developer docs](https://palantir.com/docs/foundry/ontology-mcp), [Palantir MCP](https://palantir.com/docs/foundry/palantir-mcp/), [pro-code agents](https://palantir.com/docs/foundry/agents/overview/), [announcements 2026-07](https://www.palantir.com/docs/foundry/announcements/2026-07). Beta status not confirmed on the fetched OMCP overview page itself. +- Palantir does not open-source Foundry; only client SDKs (e.g. an Apache-2.0 Python SDK) — summarised in a web search answer, not verified against the SDK repo. + +### Inferences +- The model reduces to six ideas a Postgres build can copy: typed object, typed property, typed link, interface (shared shape), action (validated, permissioned, transactional edit with side effects), function (logic). The agent seam is "agents get only actions and reads the Ontology exposes, under scoped credentials". +- The key distinction to copy is that agents write only via actions, never raw tables. + +### Gaps +- Exact submission-criteria and permission semantics (object security vs property security vs marking) not read in detail; the fetch tool returned only the overview pages. +- Whether OMCP is still beta in Nov 2026 not confirmed. + +## 2. Projects that position as Foundry/Ontology alternatives + +### Takeaway +Nothing found is a mature, adoptable Foundry Ontology. The closest by shape (OpenFoundry) has a vanished GitHub repo and a conflicting licence; the most popular (Semantica) is a knowledge-graph toolkit without actions or permissions. Copy the ideas, do not plug these in. + +### Cited Findings +- **OpenFoundry (DioCrafts)**: self-hosted "operational data platform", Go microservice monorepo plus React 19 frontend, protobuf-generated SDKs, modelled on Foundry's documented capability areas. Docs site lists object types, properties, link types, actions, functions, interfaces; actions go through validation, authorization, audit, with validate/execute/batch-execute/what-if endpoints — [SourcePulse aggregator](https://www.sourcepulse.org/projects/30129680), docs index via search results at [diocrafts.github.io/OpenFoundry](https://diocrafts.github.io/OpenFoundry/). **Verified problem**: `gh api repos/DioCrafts/OpenFoundry` returned 404 on 2026-11-23 (removed, renamed or private), and the docs subpages I tried returned 404. Licence conflict: docs claim Apache-2.0 (per search summary); Gitee mirror README says "AGPL-3.0-only", 1 star, 1,003 commits, no releases — [Gitee mirror](https://gitee.com/zdy336/OpenFoundry). Gitee notes "41 Go microservices"; whether it works end to end is not shown. Storage not verified. MCP not found. Status: do not depend; AGPL if the mirror is right. +- **Semantica** (now `semantica-agi/semantica`, was Hawksight-AI): MIT (GitHub API), 14.7k stars, latest release v0.7.0 on 2026-09-22, pushed today. Ships OWL generation, SHACL validation, SKOS, a visual editor, an ontology hub, decision records and a policy rule engine, plus an MCP server (`semantica-mcp`) exposing entity/relation extraction, decision recording and lookup, graph query/update, reasoning, export. Graph stores: Neo4j, FalkorDB, Apache AGE, Neptune, Oxigraph, Blazegraph, Jena, RDF4J; pgvector only as a vector store; no Postgres relational store listed. No action types described and no access-control model described (only an API key env var). — [Semantica README](https://github.com/Hawksight-AI/semantica) (redirects to the new org). "Tops GitHub Trending" is a claim from [besthub.dev](https://www.besthub.dev/articles/open-source-palantir-tops-github-trending-ontology-becomes-the-next-agent-layer-80399353f094), not checked. +- **agent-utilities**: the repo `Knuckles-Team/agent-utilities` now resolves to `Knuckles-Team/meristem` (MIT, 5 stars, Python, v5.0.0 released 2026-10-30), described as "An agent factory leveraging Pydantic AI and Pydantic AI Harness". The comparative-analysis page against Foundry returned 404 (old URL and new). README mentions typed actions/observations, a policy gate, MCP/REST/A2A — [meristem repo](https://github.com/Knuckles-Team/meristem). I found no evidence it now ships an ontology layer; treat the ontology claim as unverified. Negligible adoption. +- **Open Ontology SDK (OOSDK)**: a personal project described in an article; page returned 403 so I could not read it; status unconfirmed — [article](https://levelup.gitconnected.com/why-im-building-an-open-ontology-sdk-and-what-palantir-got-right-about-ai-orchestration-b68830a6b41f). +- **ibl.ai "agentic ontology"**: vendor blog claims MIT-licensed, self-hosted, MCP exposure — [ibl.ai blog](https://ibl.ai/blog/palantir-ontology-alternative-self-hosted). Guessed repo `ibl-ai/agentic-ontology` does not exist on GitHub (404). Vendor claim only; unverified. + +### Inferences +- Of these, only Semantica has real adoption and a verified permissive licence, but it covers the semantic (knowledge graph) half, not the kinetic half (actions, permissions) and not Postgres. +- OpenFoundry's design (validate / execute / what-if on actions, audit) is a useful spec to copy even if the code cannot be used. + +### Gaps +- OpenFoundry's current location and real licence; storage layer. +- agent-utilities' former ontology implementation (history of the renamed repo not inspected). +- OOSDK and ibl.ai code could not be located. + +## 3. Adjacent mature systems (licence, maturity from GitHub API 2026-11-23) + +### Takeaway +Postgres-native, permissively licensed building blocks are PostgREST, Supabase (Apache-2.0 repo), pgmq, Hasura v2; the objects-with-gated-actions part is best copied rather than adopted. Several popular no-code/CMS options are source-available or AGPL and fail the default-licence test. + +### Cited Findings +Licence column: OK = permissive/LGPL; SEP = acceptable only as separately run unmodified service; NO = source-available/commercial, flagged not usable as default. + +| System | Licence (verified) | Latest release / activity | Storage | Objects / links / actions / permissions / hooks | Agent integration | +|---|---|---|---|---|---| +| PostgREST | MIT (OK) | v16.6, 2026-11-16; 27.8k stars | Postgres only | Tables/views = resources, FKs = links, RPC via Postgres functions = actions; permissions are Postgres roles + RLS (JWT role switching) | No official MCP found; HTTP API trivially wrapped | +| Supabase | Apache-2.0 repo (OK) | CLI v1.26.08 2026-08-07; 115k stars | Postgres | PostgREST + Auth + Realtime + Edge Functions; grants + RLS policies, requests mapped to `anon`/`authenticated` roles, `auth.uid()` — [Supabase RLS docs](https://supabase.com/docs/guides/database/postgres/row-level-security) | Supabase has an MCP server (a Composio guide discusses it); not verified here from the official repo/docs | +| pgmq | PostgreSQL licence (OK) | v1.13.2, 2026-11-18 | Postgres extension | message queue only | n/a | +| Hasura graphql-engine v2 | Apache-2.0 (OK) | v2.51.9, 2026-11-19 | Postgres (and others) | Tables, relationships, actions (custom business logic via webhooks), event triggers; own role/permission rules (can use session variables), not Postgres RLS as such (from my background knowledge, not re-verified) | `hasura/promptql-mcp` bridges PromptQL; DDN v3 licence not checked — [search result](https://lobehub.com/mcp/hasura-promptql-mcp) | +| Directus | MSCL-1.0-GPL, "Monospace Sustainable Core License"; permits any purpose except Competing Use (offering the software to parties competing with the licensor's commercial offering), has license-key-protected features (NO as default; GitHub says NOASSERTION) — [LICENSE](https://github.com/directus/directus/blob/main/license) | v12.7.0, 2026-11-18; 38.6k stars | SQL DBs incl. Postgres, own permission tables (not RLS) | Collections, relations, flows (event hooks), role-based permissions with item-level filters | Built-in MCP server, off by default, acts with the connecting user's permissions, dedicated MCP user recommended; schema changes need Administrator — [Directus MCP security](https://directus.com/docs/guides/ai/mcp/security), [troubleshooting](https://directus.io/docs/guides/ai/mcp/troubleshooting) | +| NocoDB | Sustainable Use License v1.0 (NO) — [LICENSE.md](https://github.com/nocodb/nocodb/blob/develop/LICENSE.md) | 2026.10.2, 2026-11-19; 65.6k stars | Postgres/MySQL/SQLite | spreadsheet-style tables, links, webhooks, roles | Official MCP docs page exists — [NocoDB MCP](https://nocodb.com/docs/product-docs/mcp); not read in detail | +| Baserow | MIT for core; `premium/` and `enterprise/` directories have separate licences (OK for core) — [LICENSE](https://github.com/baserow/baserow/blob/develop/LICENSE) | 2.4.3, 2026-11-14; 6.4k stars | Postgres | tables, link fields, webhooks, RBAC (RBAC likely enterprise; not verified) | Built-in MCP (`POST /mcp`, OAuth or bearer key) — [Baserow MCP docs](https://baserow.io/docs/development/mcp-server) via search summary | +| Twenty CRM | AGPLv3 with commercial-licensed marked files and MIT packages; Twenty application exception (SEP at best) — [LICENSE](https://github.com/twentyhq/twenty/blob/main/LICENSE) | twenty v2.62.0, 2026-11-23; 61k stars | Postgres | custom objects, fields, relations, workflows, roles | Only community MCP servers found (not official) | +| Odoo | LGPL-3 (OK) — [LICENSE](https://github.com/odoo/odoo/blob/master/LICENSE) (Enterprise modules are separate, not in repo) | active; 56k stars; no GitHub releases | Postgres only | models (objects), many2one/one2many (links), methods (actions), ACLs + record rules (domain-based row filters), automated actions | Listing on apps.odoo.com claims Odoo speaks MCP at `/mcp` for 20.0 — vendor/listing claim — [Odoo apps listing](https://apps.odoo.com/apps/modules/20.0/mcp_server) | +| Budibase | GPLv3 overall; paid features in `packages/pro` under BSL (SEP/NO) — [LICENSE](https://github.com/Budibase/budibase/blob/master/LICENSE) | v4.1.0, 2026-11-23 | CouchDB/own plus external SQL | app builder over tables | not checked | +| Appsmith | Apache-2.0 (OK) | v2.7.2, 2026-11-19 | Mongo/Postgres | UI builder over datasources; not an object layer | not checked | +| OpenMetadata | Apache-2.0 (OK) | 2.0.9, 2026-11-20 | MySQL/Postgres + OpenSearch | metadata entities, relationships, glossary, policies/roles; catalog not operational objects | Built-in MCP server since v1.8.0, `/mcp`, OAuth2 or JWT — [OpenMetadata MCP docs](https://docs.open-metadata.org/how-to-guides/mcp) | +| DataHub | Apache-2.0 (OK) | v1.9.1, 2026-11-19 | MySQL/Postgres + Kafka/search | metadata graph/aspects, policies | `mcp-server-datahub` on PyPI — [PyPI](https://pypi.org/project/mcp-server-datahub/) | +| Apache Atlas | Apache-2.0 (OK) | no GitHub releases, pushed 2026-11-20; 2.2k stars | JanusGraph/HBase/Solr | typed entities, classifications, relationships — the closest classic "typed object + link" metadata model (type system) but no actions | none found | +| TypeDB | MPL-2.0 (file-level copyleft; fine as separate service) | 3.15.0, 2026-11-16; 4.5k stars | own engine (not Postgres) | strong typed entity/relation/attribute schema with inheritance and functions | none verified | +| Neo4j Community | GPL-3.0 (SEP only; GitHub's "latest release" API was stale) | pushed 2026-11-06 | own graph | property graph; fine-grained RBAC is Enterprise (unverified here) | official MCP servers exist per general knowledge; not verified here | +| Wikibase | GitHub NOASSERTION (extension repo); I did not verify the LICENSE text; commonly GPL-2.0-or-later (unverified) | active | MariaDB + MediaWiki | items, properties, statements with ranks/references — which Substrate already uses as data model | none verified | + +- Postgres RLS / roles as the permission model, verified: Supabase (grants + policies on `anon`/`authenticated`; with a user token the request runs under that user's policies; no policy means no rows) — [Supabase RLS docs](https://supabase.com/docs/guides/database/postgres/row-level-security). PostgREST is the engine Supabase's Data API is built on (from background knowledge; my direct fetch of PostgREST docs returned 429, not verified this session). Odoo uses Postgres but its own ACL/record-rule layer, not RLS (background knowledge). +- Postgres MCP servers built around per-user roles and RLS: pgEdge Postgres MCP Server (maps each MCP user to a Postgres role so RLS filters rows; launched April 2026) — [pgEdge docs](https://docs.pgedge.com/pgedge-postgres-mcp-server/v1-0-0/advanced/row-level-security/); pgguard runs `SET LOCAL ROLE` per transaction so grants and RLS hold — [pgguard listing](https://glama.ai/mcp/servers/Azzaraell/pgguard-mcp). RLS covers SELECT/INSERT/UPDATE/DELETE only, not DDL; the prompt-injection problem is mitigated but not solved by the database layer — [Composio](https://composio.dev/blog/supabase-mcp-server-connecting-ai-agents-to-your-database), [Bytebase review](https://www.bytebase.com/blog/top-postgres-mcp-servers/) via search summaries. + +### Inferences +- None of the adjacent systems provides Foundry's combination (typed objects + validated, permissioned, transactional actions + agent MCP on the same permission model) on Postgres. PostgREST/Supabase give the permission model (roles + RLS); Hasura gives actions and event triggers; Odoo gives the richest ready-made object/action/ACL model but is a monolith; metadata catalogs (Atlas, OpenMetadata, DataHub) describe objects rather than act on them. +- For Substrate (single Postgres, pgmq, roles, RLS, append-only record), the cheapest pattern is to copy: object type = table or `kind` rows with JSON schema; link type = FK/edge table; action type = a SQL function (SECURITY INVOKER, run as the caller's role) with parameter schema, validation, and writing an event row plus pgmq message; the agent's MCP tool list is generated from the action registry and connects as the agent's own Postgres role. That is a design inference, not something any single source states. +- PostgREST (MIT, Haskell, one binary, calls Postgres functions as RPC) is the one item that could be plugged in as-is as an HTTP layer over this design; MCP would still need to be written. + +### Gaps +- Official Supabase MCP server licence/repo and tool set not verified; NocoDB MCP page and Baserow RBAC scope not read; Hasura DDN v3 licence not checked; Neo4j/TypeDB MCP status not checked; Budibase and Appsmith agent support not checked; Wikibase LICENSE text not read; PostgREST docs not fetched (429). +- No independent (non-vendor) review comparing these to Foundry's Ontology found. diff --git a/docs/research/Object environments prior art notes/market_revenue.md b/docs/research/Object environments prior art notes/market_revenue.md new file mode 100644 index 0000000..e3050c5 --- /dev/null +++ b/docs/research/Object environments prior art notes/market_revenue.md @@ -0,0 +1,104 @@ +# Market below enterprise scale for Foundry/AIP-like platforms, and fast first-revenue routes for a solo developer + +Method note: ~12 searches/fetches, 2026-11-23. Several fetches returned 403/404 (Goldman Sachs release, one dev.to article), so those items rest on search-result summaries. Most pricing sources are vendor or agency blogs (asking prices, not transacted prices). Flagged where so. + +## Who buys Foundry/AIP-like capability below enterprise scale, and what problems do they pay to solve? + +### Takeaway +SMBs are adopting AI broadly but shallowly: most use AI tools, few have integrated AI into core operations, and most say they need training and implementation help. That implementation gap, not a lack of tools, is the paid problem. I found no evidence of a sub-enterprise buyer segment purchasing "ontology" as such; demand is expressed as AI/automation and as MSP client need. + +### Cited Findings +- Thryv survey (April 2026, 561 US SMB decision-makers): AI usage 66%, up from 55% a year earlier; 70% say they need more training — [CPA Practice Advisor, 2026-07-14](https://www.cpapracticeadvisor.com/2026/07/14/ai-adoption-continues-to-rise-but-70-say-they-need-more-training/186565/) +- Goldman Sachs 10,000 Small Businesses (Jan–Feb 2026, 1,256 owners): about 76% use AI, 93% report positive impact, but only 14% have fully integrated AI into core operations; headline says they need training and support — [Goldman Sachs press release 2026](https://www.goldmansachs.com/pressroom/press-releases/2026/small-businesses-embrace-ai-but-need-training-and-support-to-fully-harness-it) (page itself returned 403; figures from the search summary and title, verify before quoting) +- Intuit QuickBooks AI Impact Report: 77% regular use as of Jan 2026 (US, Canada, UK, Australia SMBs) — [Intuit](https://www.intuit.com/blog/global-stories/ai-impact-report/) +- Survey figures span ~40% to 87% depending on definition; Census BTOS uses a strict production-based definition and is lower — same search summary; sources include [Bluehost](https://www.bluehost.com/state-of-small-business-ai-confidence/ai-confidence-divide), [SF Fed](https://www.frbsf.org/research-and-insights/publications/community-development-research-briefs/2026/07/ai-adoption-in-small-businesses-2024-sbcs/) +- US Chamber Foundation: half of small-business workers use AI mostly to boost productivity, not automate jobs — [US Chamber Foundation](https://www.uschamberfoundation.org/workforce/half-of-small-business-workers-use-ai-most-to-boost-productivity-not-automate-jobs) +- MSPs (the IT firms serving SMBs): Kaseya 2026 State of the MSP (1,000+ providers) — 48% rank AI and automation as top client need for 2026, but only 13% currently earn meaningful revenue from it — [ITPro/Kaseya summary](https://www.itpro.com/technology/artificial-intelligence/ai-demand-soars-as-traditional-deal-sizes-shrink-kaseya-reports); [Channel Insider](https://www.channelinsider.com/ai/msp-ai-revenue-growth-2026/). Vendor-affiliated source. +- Informa MSP 501 (600+ MSPs): about one-third expect AI revenue to grow more than 20% in 2026 — [Channel Insider](https://www.channelinsider.com/ai/msp-ai-revenue-growth-2026/) +- Palantir's own framing: AIP boot camps deliver working workflows on the customer's own data in 5 days or less; planned for 140+ organizations by end of November (2024) — [Constellation Research](https://www.constellationr.com/index.php/insights/news/palantirs-commercial-business-scales-help-ai-boot-camps) + +### Inferences +- The buyer to target is the owner-operated or 10–200 person firm that already uses ChatGPT-type tools and cannot connect them to its own data and processes; an MSP serving many such firms lacks capacity for it, so MSPs are a channel as well as a client type. +- "Ontology" is a delivery mechanism, not a purchase reason. Sell the outcome (visibility, fewer manual steps, approvals), not the model. + +### Gaps +- No usable data on local government or nonprofit spend on Foundry-like tools (not searched deeply; no results surfaced). +- No data on how many SMBs buy "operations visibility/data unification" specifically versus generic AI. + +## Price points 2025-2026 (Palantir, mid-market alternatives, agency/consulting rates) + +### Takeaway +Palantir is priced far above any solo-developer client: published signals are six to seven figures a year. The relevant market for a solo is the AI-automation agency band: roughly $2k–$15k setup plus $500–$5k/month retainer, and $2.5k–$10k for fixed-fee audits, per vendor-written guides that disagree by 2–4x. + +### Cited Findings +- Palantir publishes no prices; CostBench lists AIP as custom enterprise-only pricing — [CostBench](https://costbench.com/software/ai-ml-platforms/palantir-aip/) +- Negotiation consultancy Redress Compliance estimates $800K–$2.5M annual platform fees for a mid-market enterprise (interested party, directional) — [Redress Compliance](https://www.redresscompliance.com/palantir-aip-foundry-negotiation.html) +- Spendflo: Foundry typically $100K to several million per year (weak source); an AWS Marketplace listing shows a Foundry Subscription Unit at $100,000 per month on a one-month contract (a listing example, not a typical deal) — [Spendflo](https://spendflo.com/vendors/foundry), [AWS Marketplace](https://aws.amazon.com/marketplace/pp/B0B1P1GDTF) +- Bootcamp price disputed: one review blog says about $1M starting (unverified); Palantir's annual report reportedly describes low or no-cost evaluation pilots with bootcamps — [reviewaitool](https://blog.reviewaitool.com/?p=186), [Bloomberg 2024-04-23](https://www.bloomberg.com/news/articles/2024-04-23/inside-palantir-s-ai-sales-secret-weapon-software-boot-camp) +- Per-seat mid-market tools for contrast: Retool Team $10/mo, Business $50/mo; Airtable Plus $10, Pro $20 (per-seat presumed, aggregator data, may be stale) — [Findstack](https://findstack.com/compare/retool-vs-airtable). Alteryx entry $3,000/user/year — [G2](https://www.g2.com/compare/alteryx-vs-palantir-foundry) +- Agency retainers and setup (vendor blogs; asking prices): small-business retainer from ~$500/mo; light retainer $1,000–$3,500/mo; hybrid $2,000–$8,000 setup + $1,500–$4,000/mo; wider $2,500–$15,000 setup + $500–$5,000/mo; mid-market setup $20,000+ — [DEV Community guide](https://dev.to/scalelogix_ai/how-to-price-ai-agency-services-in-2026-a-complete-guide-for-operators-5f26), [Digital Agency Network](https://digitalagencynetwork.com/ai-agency-pricing/), [Taskip](https://taskip.net/ai-automation-agency-pricing/). Integration complexity is the largest cost driver. +- AI readiness audit: typical $2,500–$10,000 for a small business; a 10-day audit from $7,500 fixed; one provider credits the 3–5 day assessment fee against a build; UK guide £750–£8,000 for firms under 50 staff; enterprise tier $15K–$50K+ — [AI Smart Ventures buyer guide](https://aismartventures.com/posts/what-should-an-ai-readiness-assessment-include-and-what-should-you-pay-for-one-a-practical-buyers-guide-for-owner-operated-businesses), [Lilach Bullock](https://www.lilachbullock.com/ai-audit-small-business-cost/). Timeline 1–3 weeks; client staff time 15–20 hours. +- Marketplace gig tiers (Upwork productized AI audit): $150 / $400 / $900 at 3 / 7 / 14 days — [Upwork listing](https://www.upwork.com/services/product/development-it-an-ai-consulting-audit-and-roadmap-for-your-small-business-2075758213237450880) +- Upwork client-posted budgets: UpHunt's analysis of Aug–Oct 2026 jobs — AI automation jobs (n8n, Make, Zapier) median $15–$30/hr, only 7.1% reach $100+/hr; Upwork says AI-skilled freelancer GSV grew 55% y/y in Q3 2026 (quoted by UpHunt) — [UpHunt](https://uphunt.io/blog/upwork-ai-consultant-hourly-rate-2026-data). Contradicted by blog claims of $150–$350/hr for US independents ([DEV Community](https://dev.to/jahanzaibai/ai-automation-consultant-hourly-rate-what-youll-actually-pay-in-2026-and-when-its-worth-it-55ln), unverified). +- Palantir negotiation note: pilots begun without agreed commercial terms converted at materially worse pricing — [Redress Compliance](https://redresscompliance.com/palantir-aip-foundry-negotiation) (interested party). + +### Inferences +- Realistic first-sale range: $2,500–$7,500 fixed for audit/pilot, then a $500–$2,000/mo retainer. Marketplace bidding competes with $15–$30/hr automators; direct outreach avoids that. +- Palantir's 5-day boot camp on the customer's data is the model to copy at small scale: a fixed-length, fixed-price, credited-against-build pilot. + +### Gaps +- No verified transacted prices (Vendr/Vertice Palantir data was not accessible). No pricing found for Dust, Glean or other agent platforms. No sourced day rate for solo ontology consultants. + +## Fast first-revenue routes and evidence of conversion + +### Takeaway +Evidence on conversion is mostly anecdote. The recurring pattern is a narrow niche, a fixed-scope audit or pilot, one working automation, and a small retainer. Nothing found proves a one-week timeline; sourced examples are weeks to months. + +### Cited Findings +- Indie Hackers, Soratech (AI/workflow automation consultancy, 2023 post, dated): roughly $4K setup plus $500/mo retainer; $4,000/mo and $8,000 total revenue after 5 months — [Indie Hackers](https://www.indiehackers.com/product/soratech/after-5-months-my-business-hit-4000-month-revenue-and-8000-total-revenue--N_yAWwJP1-mhVVs1_LQ) +- Indie Hackers anecdote: first $1,000 from a lead-generation agency client wanting a custom AI app — [Indie Hackers](https://www.indiehackers.com/post/how-i-made-my-first-1-000-from-a-single-client-by-listing-my-email-on-a-free-tool-site-no-ads-no-cold-emails-2b2d349ee1) +- Indie Hackers anecdote: first paying customer closed only after 6 pitches were ignored — [Indie Hackers](https://www.indiehackers.com/post/how-i-closed-my-first-paying-customer-after-6-pitches-got-ignored-17ec2087bf) +- Pattern advice (promotional, unverified): narrow niche; scoped free audit ending in one working agent; consulting first, productize later — [dev.to](https://dev.to/michael_xero_ai/how-to-get-your-first-ai-consulting-client-without-a-portfolio-4n1h), [MindStudio](https://mindstudio.ai/blog/start-ai-automation-business-case-studies). Several results were sales pages for courses. +- MSP partnership: Pax8 is pushing agentic AI offers to MSPs to build recurring revenue; MSPs lack delivery capacity (13% earning meaningful AI revenue) — [ChannelE2E](https://www.channele2e.com/news/pax8-wants-msps-to-turn-smb-ai-demand-into-managed-services). Counterpoint: reselling AI is not where MSP margins are made — [ITPro](https://www.itpro.com/technology/artificial-intelligence/why-reselling-ai-isnt-where-msp-margins-are-made) + +### Inferences +- Fastest realistic route this week: (1) a paid fixed-price "process map and one automation pilot" sold by direct outreach to 5–10 known small firms, (2) a white-label delivery offer to 2–3 local MSPs, (3) a marketplace productized listing as a low-priced lead source (expect low budgets). Expect first cash in 1–4 weeks, not guaranteed within one. +- Use the mapping tool as the audit deliverable (it is the differentiator: a decomposed map with interfaces), with the pilot credited against the build. + +### Gaps +- No sourced conversion rates (outreach to meeting to sale), no verified sales-cycle length for sub-$10K AI projects. Open-core and marketplace-product revenue for this category: no evidence found. + +## What buyers fear, and how self-hosted/local-model positioning helps or hurts + +### Takeaway +Data privacy and lack of AI security expertise are top SMB concerns, which supports a privacy-first pitch, but I found no survey showing SMBs ask for self-hosting or local LLMs; they mostly look for certifications and transparency. + +### Cited Findings +- Pax8 survey (1,150 SMB leaders): data security and privacy a top AI risk concern for over one-third; over one-third found unapproved shadow AI in six months; Q2 2026 pulse: 23% have a documented AI policy, 28% informal only — [SecureWorld](https://www.secureworld.io/industry-news/smb-ai-governance-security), [ChannelDive](https://www.channeldive.com/news/smbs-lack-ai-governance-report/832804/) +- IDC/Sage: top AI security challenges are insufficient internal expertise (45%) and implementing data governance (41%); certifications and data-handling transparency are the main trust mechanisms — [ERP Today](https://erp.today/sage-idc-research-reveals-smb-cybersecurity-gaps-in-the-ai-era/) +- Kaseya: accuracy and data privacy slow adoption — [ITPro](https://www.itpro.com/business/business-strategy/kaseya-smbs-remain-cautious-on-ai-despite-persistent-human-error-threat) +- Proton SMB report digest: 45% unclear how AI firms handle data; 33% cite lack of deletion guarantees (fragmentary, unverified) — [SecurityBrief](https://securitybrief.news/story/smbs-take-cautious-approach-to-ai-adoption-study-finds) + +### Inferences +- Helps: permission-gated actions, human approval, provenance and local models answer governance and shadow-AI fears; sell "AI policy plus controlled agent" for regulated or privacy-sensitive niches (legal, health, accounting, local government). +- Hurts: self-hosting means the buyer needs someone to operate it; a solo developer is a single point of failure, and SMBs lack internal expertise. A hosted-by-you managed option with a data-handling statement is likelier to close than a handover. + +### Gaps +- No survey data on SMB demand for self-hosted or local LLMs; no data on reliability fears about solo vendors. + +## Examples of solo founders or small firms selling ontology/knowledge-graph/agent systems to SMBs + +### Takeaway +I found no documented solo seller of an ontology product to SMBs with a stated price. Evidence is limited to generic AI automation consultancies and marketplace listings. + +### Cited Findings +- Soratech (above): $4K setup + $500/mo, automations and bots — [Indie Hackers](https://www.indiehackers.com/product/soratech) +- PeoplePerHour listing frames a minimum-viable-ontology consultation: domain entities and relationships, design for priority queries, graph DB recommendation, phased roadmap (price not captured) — [PeoplePerHour](https://www.peopleperhour.com/hourlie/knowledge-graph-consultation-design-your-domain-structure/1131310) +- Fiverr/Upwork knowledge-graph gigs exist (e.g. [Fiverr](https://fiverr.com/fabisch_dev/create-knowledge-graphs-and-ontologies)); prices not captured. Knowledge Graph Conference community notes consultants suit small PoCs — [KGC](https://community.knowledgegraph.tech/x/jobs/hizlpm0q09ho/hiring-employees-vs-consultants-for-ontology-work) +- Large specialist firms (Semantic Arts, Enterprise Knowledge) serve enterprises; no public prices — [Semantic Arts](https://www.semanticarts.com/?p=9587) + +### Inferences +- The niche of "Palantir-style ontology for small business" looks open but unproven; market evidence is for AI automation, so label the offer as such. + +### Gaps +- No named solo founders with numbers selling ontology systems; "Palantir for small business" content found was an unsourced essay series. Local government and nonprofit buyers not covered. diff --git a/docs/research/Object environments prior art.md b/docs/research/Object environments prior art.md new file mode 100644 index 0000000..df91fe3 --- /dev/null +++ b/docs/research/Object environments prior art.md @@ -0,0 +1,68 @@ +# Copy Foundry's ideas, plug in Postgres parts + +No single open-source system combines objects, gated actions, a Postgres blackboard and harnesses joining through a model proxy, so Substrate's core is new and the surrounding parts can mostly be plugged in or copied. The closest Foundry-like projects are not adoptable: OpenFoundry's GitHub repo returned 404 on 2026-11-23 and its licence is disputed (Apache-2.0 on its docs, AGPL-3.0 on a Gitee mirror), and Semantica (MIT, 14.7k stars) covers only the knowledge-graph half, with no actions or permissions. The sound pieces are PostgREST (MIT), pgmq (PostgreSQL licence) and Postgres roles with row-level security for permissions. For standards, W3C Thing Description 1.1 maps almost one-to-one to properties, actions and events, MCP is the joining surface, and OpenEnv can be a thin adapter. BDI with LLMs is not proven: the 2024-2026 evidence is prototype-scale, but it supplies a pattern worth copying, which is an LLM proposing into a typed vocabulary, a validator filtering, and an explicit layer owning commitment and retraction. On the business side, Foundry costs six to seven figures a year, and nothing sourced shows sub-enterprise buyers purchasing "ontology" as such. What they pay for is AI implementation help, so the first paid offer should be a fixed-price, five-day "process map plus one gated automation" pilot at roughly $2,500-$7,500, credited against a build. First cash within a week is unlikely; one to four weeks is realistic. + +## BDI with LLMs is a useful pattern, not a proven structure + +The 2024-2026 literature is small and mostly workshop-level. It falls into three patterns. In the first, an LLM is a natural-language front end to a BDI agent: ChatBDI keeps Jason doing the thinking while a model embeds messages and maps them to the closest KQML literal, and it does not generate plans ([ChatBDI](https://aamas.csc.liv.ac.uk/Proceedings/aamas2025/pdfs/p2541.pdf)). In the second, an LLM writes plans into the BDI plan library. Ciatto et al. (ECAI 2025) extend AgentSpeak(L) with a plan-generation procedure that runs on demand, after plan failure or proactively, with failed plans retracted ([paper](https://cris.unibo.it/bitstream/11585/1026414/3/FAIA-413-FAIA251223.pdf)). Jarvis (WESAAC 2026) introspects CArtAgO artifacts' operation signatures and observable properties, asks an LLM for an AgentSpeak library, and validates arity and subgoals before injecting plans ([Jarvis](https://sol.sbc.org.br/index.php/wesaac/article/download/45248/45009/)). In the third, an LLM sits inside a rule-based BDI shell for believability, as in a child-helpline trainer ([arXiv 2509.16784](https://arxiv.org/abs/2509.16784)). + +The measured evidence is thin. Ciatto's one quantified result covers a single grid-world task, 4 models and 5 runs each, and success ranged from **100% for the best model down to 20% for the worst**, so BDI structure does not remove the dependence on the planner model. The Utah self-aware BDI agent scored 13.2% (any round, simulation mode) and 9.4% in the seeded and non-seeded single-pass runs on 53 GAIA questions with Qwen3-8B, and plan seeding did not improve accuracy ([UUCS-26-001](https://www-old.cs.utah.edu/docs/techreports/2026/UUCS-26-001.pdf)). The researcher found no head-to-head showing BDI+LLM beating a plain tool-calling agent. No 2024-2026 system compiles LLM episodes into plans Soar-style with measured results. That absence is weak evidence of novelty, since Soar literature was outside the search scope, but it means a "System 1 distilled from experience" has no BDI-side proof to lean on. What plan libraries demonstrably give is structure, auditability and cheap reuse: Jarvis spent about 1.5K input and 200 output tokens once per learned plan. + +The practical advice is to hand-roll the cycle rather than adopt a runtime. Jason (v3.3.3, 2026-10-15) and JaCaMo (v1.3.1) are LGPL-3.0 and alive, but they are JVM-only with no maintained Python binding ([Jason](https://github.com/jason-lang/jason), [JaCaMo](https://github.com/jacamo-lang/jacamo)). CArtAgO reports GPL-3.0 through the GitHub API with its last push in July 2024, so it could only run as a separate service ([CArtAgO](https://api.github.com/repos/CArtAgO-lang/cartago)). Of the Python options, MASPY (MIT, pushed 2026-11-13) is the one to read for semantics, but its runtime owns its own belief store ([MASPY](https://api.github.com/repos/laca-is/MASPY)). Belief, goal and intention tables with the plan library as rows in the shared Postgres fit the blackboard better. Copy four things: the typed vocabulary and validator before a plan enters the library, failure-driven retraction, artifact signatures as grounding, and recording which model wrote each plan. + +## Foundry's model is six ideas, and no open project packages them + +Palantir describes the Ontology as an operational layer with a semantic half (objects, properties, links) and a kinetic half (actions, functions, dynamic security) ([Palantir overview](https://www.palantir.com/docs/foundry/ontology/overview/)). An action is "a single transaction" composed of rules, parameters, submission criteria, permissions and side effects ([action types](https://www.palantir.com/docs/foundry/action-types/overview/)). Agents reach this through an Ontology MCP that exposes object types, action types and query functions as tools, restricted by application scopes ([OMCP](https://palantir.com/docs/foundry/ontology-mcp/overview/)). The central idea to copy is that agents write only through actions, never raw tables. Palantir's facts here are second-hand, because they were read through a summarising fetch tool. + +The projects that market themselves as alternatives are weak. OpenFoundry (Go, 41 microservices per its Gitee mirror) has the right design, with validate, execute, batch-execute and what-if endpoints on actions, but the repo is gone and the licence conflicts ([Gitee mirror](https://gitee.com/zdy336/OpenFoundry)). Semantica has real adoption and an MCP server but stores graphs in Neo4j, FalkorDB, Apache AGE and similar stores, with no relational Postgres store and no described access control ([Semantica](https://github.com/Hawksight-AI/semantica)). The ibl.ai "agentic ontology" is a vendor claim whose guessed repo does not exist, and agent-utilities (now meristem, MIT, 5 stars) shows no verified ontology layer ([meristem](https://github.com/Knuckles-Team/meristem)). The popular "open-source Palantir" write-ups are claims, not evidence. + +The adjacent systems split by licence, which is the filter that matters for Substrate's rules. + +| System | Licence | Use | +|---|---|---| +| PostgREST | MIT | Plug in: HTTP/RPC over Postgres functions, roles and RLS | +| pgmq | PostgreSQL | Already in use | +| Supabase | Apache-2.0 | Copy the grants + RLS pattern | +| Hasura v2 | Apache-2.0 | Copy actions and event triggers | +| Odoo | LGPL-3 | Richest ready-made object/action/ACL model, but a monolith | +| OpenMetadata, DataHub, Atlas | Apache-2.0 | Catalogs describe objects but do not act on them | +| TypeDB | MPL-2.0 | Strong typed schema, separate service, not Postgres | +| Neo4j Community | GPL-3.0 | Separate process only | +| Directus, NocoDB, SpacetimeDB | source-available (MSCL, Sustainable Use, BSL 1.1) | Fail the default licence test | +| Twenty, Budibase | AGPL / GPL with paid parts | Separate service at best | + +Sources: [PostgREST, Supabase, Hasura, Odoo, Directus and others as tabulated in the research notes via GitHub API and LICENSE files](https://github.com/directus/directus/blob/main/license); [SpacetimeDB licence](https://www.nuget.org/packages/SpacetimeDB.Runtime/2.8.0/License). Licence fields were read from the GitHub API on 2026-11-23. Wikibase's licence text was not read. + +Postgres RLS as the agent permission model is verified in practice: Supabase runs requests under the caller's role ([Supabase RLS](https://supabase.com/docs/guides/database/postgres/row-level-security)), and pgEdge's MCP server maps each user to a Postgres role ([pgEdge](https://docs.pgedge.com/pgedge-postgres-mcp-server/v1-0-0/advanced/row-level-security/)). RLS covers only SELECT, INSERT, UPDATE and DELETE and does not solve prompt injection. The inferred cheap pattern is that an object type is a table or `kind` rows with a JSON schema, a link is an edge table, an action is a SQL function run as the caller's role that writes an event row and a pgmq message, and the MCP tool list is generated from the action registry. No source states this pattern; it is a design inference. + +## Standards fit as thin adapters, and the gate is the gap + +W3C Thing Description 1.1 (Recommendation, 5 Dec 2023) defines properties, actions, events, forms and security schemes, a near-exact match to the object model ([TD 1.1](https://www.w3.org/TR/wot-thing-description11/)). TD 2.0 is only a First Public Working Draft from Nov 2025 ([TD 2.0](https://www.w3.org/TR/2025/WD-wot-thing-description-2.0-20251104)). The free/propose/deny gate has no native TD field and would be an extension term. Generating TDs from the object tables is cheap; node-wot (EPL-2.0 or W3C licence) is an optional runtime needing Node in a container ([node-wot](https://github.com/eclipse-thingweb/node-wot)). + +Agents and Artifacts (CArtAgO) is the closest academic precedent: artifacts with operations, observable properties and signals live in workspaces, and agents "focus" on the ones they care about ([Ricci et al. 2011](https://cris.unibo.it/handle/11585/108512)). Copy the vocabulary: focus as an explicit subscription row, state (replayable) versus signal (transient), and operations that can fail with feedback. A&A has no permission gate and its artifacts are code classes rather than trait-based data. The A&A detail rests on secondary sources, because the official docs and licence were not fetched. + +OpenEnv (BSD-3, "early development") is an episodic Gym-style protocol with reset, step and state over WebSocket, and MCP tools at `/mcp` ([OpenEnv](https://github.com/meta-pytorch/OpenEnv)). Its production mode serves MCP tools with no episode control ([HF docs](https://huggingface.co/docs/openenv/main/en/guides/simulation-vs-production)), and RFC 005 (still In Review) wraps an unmodified Claude Code through a localhost MCP bridge ([RFC 005](https://github.com/huggingface/OpenEnv/blob/main/rfcs/005-agentic-harnesses.md)). Its Harbor/RFC 006 route records every model call through a proxy to capture token traces ([HF harnesses](https://huggingface.co/docs/openenv/main/en/tutorials/harnesses)), which is the same idea as Substrate's gateway and a ready format for training a System 1. Spec churn is real: repo locations and RFC numbers disagree across sources, and it has no free/propose/deny notion. A single live database also does not fit `reset` without a per-episode schema or branch. Adopt through an adapter and do not build the core around it. + +MCP is the joining surface. The 2025-11-25 spec gives tools, URI-identified resources, subscriptions and annotations ([spec](https://modelcontextprotocol.io/specification/2025-11-25/server/resources)). The 2026-07-28 revision, whose final or draft status was not confirmed, removes sessions and replaces resource subscribe with `subscriptions/listen`, and adds `input_required` results ([changelog](https://modelcontextprotocol.io/specification/2026-07-28/changelog)). Statelessness suits a database-as-state design, and `input_required` is a natural carrier for the `propose` gate (inference). Beyond these, CloudEvents (CNCF graduated, 1.0.2) is a cheap envelope for events in pgmq and the record ([CloudEvents](https://github.com/cloudevents/spec)), and A2A v1.0 task states (INPUT_REQUIRED, WORKING, COMPLETED, REJECTED) map to a proposed action's lifecycle ([A2A](https://a2a-protocol.org/latest/specification/)). Home Assistant's stable `unique_id` and availability conventions are worth copying ([HA docs](https://contributors.home-assistant.io/core/entities/entity-class/)). CUBE and Open Agent Spec are young and best ignored except as export targets. A 2026 survey of three harnesses finds that tamper-evident external verifiability is the one axis where they have not converged, which supports the append-only record ([arXiv 2608.23953](https://arxiv.org/abs/2608.23953)). + +The researcher found no system combining database-as-environment, gated object actions and harnesses joining via a model proxy. Absence of search hits is weak evidence; GitHub was not searched for Letta, LangGraph-on-Postgres or pgmq-based agent frameworks, which could be partial precedents. + +## Buyers pay for implementation help, and Foundry pricing is out of reach + +Adoption is broad and shallow. About 76% of small businesses use AI but only **14% have fully integrated it into core operations** ([Goldman Sachs](https://www.goldmansachs.com/pressroom/press-releases/2026/small-businesses-embrace-ai-but-need-training-and-support-to-fully-harness-it); the page returned 403 so figures come from a search summary). Thryv's April 2026 survey of 561 decision-makers found 66% usage and 70% wanting more training ([CPA Practice Advisor](https://www.cpapracticeadvisor.com/2026/07/14/ai-adoption-continues-to-rise-but-70-say-they-need-more-training/186565/)). MSPs see the demand but lack delivery capacity: 48% rank AI as the top client need, and only 13% earn meaningful AI revenue ([ITPro/Kaseya](https://www.itpro.com/technology/artificial-intelligence/ai-demand-soars-as-traditional-deal-sizes-shrink-kaseya-reports), a vendor-affiliated source). No evidence shows a sub-enterprise segment buying "ontology" by name, and no named solo seller with prices was found. + +Palantir publishes no prices. Estimates run from $800K-$2.5M a year for a mid-market enterprise (a negotiation consultancy, an interested party) ([Redress](https://www.redresscompliance.com/palantir-aip-foundry-negotiation.html)) to a single AWS Marketplace listing at $100,000 per month for one month ([AWS](https://aws.amazon.com/marketplace/pp/B0B1P1GDTF)). No transacted prices were found. The relevant band for a solo is AI-automation agency pricing, per vendor blogs with 2-4x disagreement: $2,000-$15,000 setup plus $500-$5,000 a month ([Digital Agency Network](https://digitalagencynetwork.com/ai-agency-pricing/)), and readiness audits at $2,500-$10,000 ([AI Smart Ventures](https://aismartventures.com/posts/what-should-an-ai-readiness-assessment-include-and-what-should-you-pay-for-one-a-practical-buyers-guide-for-owner-operated-businesses)), some crediting the fee against a build. Marketplaces are a poor channel: UpHunt's analysis of Aug-Oct 2026 jobs puts AI-automation medians at $15-$30 an hour with 7.1% reaching $100 or more ([UpHunt](https://uphunt.io/blog/upwork-ai-consultant-hourly-rate-2026-data)). Conversion evidence is anecdotal, such as one consultancy reaching $4,000 a month after five months on about $4K setup plus $500 a month ([Indie Hackers](https://www.indiehackers.com/product/soratech/after-5-months-my-business-hit-4000-month-revenue-and-8000-total-revenue--N_yAWwJP1-mhVVs1_LQ)). + +Privacy helps the pitch but self-hosting does not obviously sell. Only 23% of SMBs have a documented AI policy ([SecureWorld](https://www.secureworld.io/industry-news/smb-ai-governance-security)), and top challenges are missing expertise (45%) and data governance (41%) ([ERP Today](https://erp.today/sage-idc-research-reveals-smb-cybersecurity-gaps-in-the-ai-era/)). Permission gates, human approval and an append-only record answer those fears directly. No survey shows SMBs asking for local LLMs, and a handover leaves them without operators, so a hosted-by-you offer with a data-handling statement is likelier to close. + +## Recommendation: plug in, copy, build, and sell + +Plug in PostgREST (MIT) as the HTTP layer over the action functions, pgmq for queues, Postgres roles and RLS for permissions, and MCP as the agent surface; the kernel's MCP profile already follows this. Add a thin OpenEnv production-mode adapter and TD generation only when a buyer or training run needs them. Copy Palantir's six ideas, with action validate/execute/what-if and audit from OpenFoundry's documented design, A&A's focus and state-versus-signal split, A2A task states, CloudEvents envelopes and Home Assistant's stable ids. Copy the BDI discipline (typed vocabulary, validator, failure-driven retraction) as tables and gate checks, and skip Jason, CArtAgO and SPADE runtimes. What looks genuinely new, with the caveat that search absence is weak evidence, is the combination: trait-based objects whose actions sit behind free/propose/deny gates in one Postgres that is blackboard, bus, auth and record, with unmodified harnesses joining through a model proxy that records every call. A System 1 distilled from that record has no proven precedent in BDI work, so treat it as research with its own measurements. + +The first paid offer is a **five-day fixed-price "map and one gated automation" pilot** for owner-operated firms of 10-200 people, priced at $2,500-$7,500 and credited against a build, then a $500-$2,000 monthly retainer for hosting and approvals. Deliver the decomposed map (objects, roles, interfaces) as the audit, then one automation whose writes go through a propose gate with a human approval step, hosted by you. Sell visibility, fewer manual steps and approvals, and describe it as AI automation, not an ontology. Reach 5-10 known firms directly, and approach 2-3 local MSPs about white-label delivery, since they have demand and no capacity. This follows Palantir's own five-day bootcamp pattern at small scale ([Constellation Research](https://www.constellationr.com/index.php/insights/news/palantirs-commercial-business-scales-help-ai-boot-camps)). + +## Conclusion + +The research changes the build question from "what Foundry clone do we adopt" to "which commodity parts do we let carry the weight", because the open Foundry alternatives are either gone, source-available or only half the model, while the Postgres parts (PostgREST, pgmq, RLS) are mature and permissive. The real contribution is the gate plus the record: standards such as TD, A&A, MCP and OpenEnv each cover affordances or transport but none covers propose-and-approve, and the harness literature itself names tamper-evident verification as unsolved. + +Several uncertainties remain open. BDI plan distillation has no measured benefit yet, so System 1 claims should be tested rather than assumed. The MCP 2026-07-28 status, OpenEnv's governance and CArtAgO's licence are unverified, and every price in the market section is an asking price from vendor or agency writing. The pilot also has no sourced conversion rate, so its first sales are the experiment that fills that gap. diff --git a/environment/author.py b/environment/author.py index 1a17c38..b78ba42 100644 --- a/environment/author.py +++ b/environment/author.py @@ -4,7 +4,7 @@ python3 -m environment.author voice_reply [WHY] # in the companion's container; or the `improve` actuator -The first author writes the voice head's reply component with the local model (AUTHOR_MODEL, local/gemma by +The first author writes the voice head's reply component with the local model (AUTHOR_MODEL, local/slow by default, thinking off unless AUTHOR_REASONING says otherwise), so what the owner said aloud stays on this machine (P3). """ from __future__ import annotations @@ -22,7 +22,7 @@ ENV = "companion" GATEWAY = os.environ.get("GATEWAY_URL", "http://gateway:8080") -MODEL = os.environ.get("AUTHOR_MODEL") or "local/gemma" +MODEL = os.environ.get("AUTHOR_MODEL") or "local/slow" KEY = os.environ.get("COMPANION_AUTHOR_KEY", "") BRIEF = """You improve one component of a voice assistant: the instructions and settings its local model uses to diff --git a/environment/experience.py b/environment/experience.py new file mode 100644 index 0000000..5ed8d66 --- /dev/null +++ b/environment/experience.py @@ -0,0 +1,88 @@ +"""The assistant's experience (S-182): one episode per model call the gate sees, the rows System 1 is distilled from. +The Python side of environment/sql/008_experience.sql. + + x = Experience(conn) # the key from EXPERIENCE_KEY (.env), or Experience(conn, key) + ref = x.record("worker:loop", request=messages, responder="slow", response=text, features={...}, + embedding=vec, embedder="ollama/qwen3-embedding:0.6b", decision={...}, impasse="low") + x.outcome(ref, "ok", True, source="task") # later, by the ref: ok (bool), correct (a responder), score (0..1) + x.episodes(caller="worker:loop") # the decider's context: features, embedding, latest labels; no text + x.text(ref) # the owner's: the request and response back + x.forget(ref=...) / x.forget(start=..., end=...) / x.forget(everything=True); x.expire() # the owner's + +The text is encrypted by Postgres (pgcrypto) under the key, passed as a bound parameter and never stored. +""" +from __future__ import annotations + +import json +import os +from datetime import datetime + +from psycopg.types.json import Jsonb + +KINDS = ("ok", "correct", "score") +IMPASSES = ("none", "tie", "low") + + +def _vector(v) -> str | None: + return None if v is None else "[" + ",".join(repr(float(x)) for x in v) + "]" + + +class Experience: + def __init__(self, conn, key: str | None = None): + self.c = conn + self.key = key if key is not None else os.environ.get("EXPERIENCE_KEY", "") + + def _need_key(self) -> str: + if not self.key: + raise ValueError("experience needs EXPERIENCE_KEY (.env; deploy/secrets.txt)") + return self.key + + def record(self, caller: str, request, responder: str, response: str | None = None, features: dict | None = None, + embedding=None, embedder: str | None = None, depended_on: list | None = None, + decision: dict | None = None, impasse: str | None = None) -> str: + """One episode; returns its ref (a uuid as text). `request` is the call's messages (any JSON) or text.""" + if impasse is not None and impasse not in IMPASSES: + raise ValueError(f"impasse is one of {IMPASSES}, or None") + text = request if isinstance(request, str) else json.dumps(request, ensure_ascii=False) + row = self.c.execute( + "select env.record_episode(%s, %s, %s, %s, %s, %s::vector, %s, %s, %s, %s, %s)", + (self._need_key(), caller, text, Jsonb(features or {}), embedder, _vector(embedding), responder, response, + Jsonb(depended_on or []), Jsonb(decision or {}), impasse)).fetchone() + return str(row[0]) + + def outcome(self, ref: str, kind: str, value, source: str, note: str | None = None) -> int: + """How an episode turned out, at any time after it (long-horizon feedback).""" + if kind not in KINDS: + raise ValueError(f"kind is one of {KINDS}") + return self.c.execute("select env.add_outcome(%s, %s, %s, %s, %s, %s)", + (ref, kind, Jsonb(value), source, note, self.key if note else None)).fetchone()[0] + + def episodes(self, caller: str | None = None, since: datetime | None = None, limit: int = 5000) -> list[dict]: + """Newest first, with the latest outcome of each kind; no text.""" + rows = self.c.execute("select ref, at, caller, features, embedder, embedding::text, responder, decision, impasse, " + "ok, correct, score, outcomes from env.episodes(%s, %s, %s)", (caller, since, limit)).fetchall() + keys = ("ref", "at", "caller", "features", "embedder", "embedding", "responder", "decision", "impasse", + "ok", "correct", "score", "outcomes") + out = [] + for r in rows: + d = dict(zip(keys, r)) + d["ref"] = str(d["ref"]) + d["embedding"] = None if d["embedding"] is None else json.loads(d["embedding"]) + d["score"] = None if d["score"] is None else float(d["score"]) + out.append(d) + return out + + # ---- the owner's (granted to no login; run as the owner) + + def text(self, ref: str) -> dict | None: + row = self.c.execute("select request, response from env.episode_text(%s, %s)", (ref, self._need_key())).fetchone() + return None if row is None else {"request": row[0], "response": row[1]} + + def forget(self, ref: str | None = None, start: datetime | None = None, end: datetime | None = None, + everything: bool = False) -> int: + """Delete one episode, those in [start, end), or all; their outcomes with them. Returns how many episodes.""" + return self.c.execute("select env.forget_experience(%s, %s, %s, %s)", (ref, start, end, everything)).fetchone()[0] + + def expire(self) -> int: + """Delete what is older than the retention (select env.set('experience', 'retention_days', '30', 'owner')).""" + return self.c.execute("select env.expire_experience()").fetchone()[0] diff --git a/environment/judge.py b/environment/judge.py index c8938ab..903c950 100644 --- a/environment/judge.py +++ b/environment/judge.py @@ -35,7 +35,7 @@ GATEWAY = os.environ.get("GATEWAY_URL", "http://gateway:8080") KEY = os.environ.get("JUDGE_KEY", "") -MODEL = os.environ.get("JUDGE_MODEL") or "local/gemma" +MODEL = os.environ.get("JUDGE_MODEL") or "local/slow" CASES = Path(os.environ.get("JUDGE_CASES") or "/cases") NAME = "judge 0.1 (environment/judge.py)" diff --git a/environment/sql/008_experience.sql b/environment/sql/008_experience.sql new file mode 100644 index 0000000..93a6f92 --- /dev/null +++ b/environment/sql/008_experience.sql @@ -0,0 +1,169 @@ +-- The assistant's experience (S-178, S-180, S-182): one episode per model call the gate sees. System 1 is distilled +-- from it: skills (compiled responses with conditions) and preferences (which response fits which scenario, TabICL +-- over episodes). docs/privacy.md: P6 is loosened for this store only, on the owner's word: the owner's words are +-- kept, encrypted at rest; deletion of one episode, a time range or all; a retention period. +-- +-- experience an episode: the scenario (the request, encrypted; its features and embedding), the response (who +-- answered: a skill or a rung; what it said, encrypted; what it depended on), how the gate decided +-- (the decider's probabilities, the impasse when it handed the call on). Kept whole; only deleted. +-- outcome how an episode turned out, attached later by the episode's ref (long-horizon feedback): `ok` (was the +-- response right, true or false), `correct` (the responder that should have answered), `score` (0 to +-- 1). Many per episode, never changed; a note, if any, encrypted like the text. +-- +-- The text is encrypted with pgcrypto's pgp_sym_encrypt under a key the database never stores: the writer passes it +-- as a bound parameter (EXPERIENCE_KEY in .env), and only the owner's functions decrypt. +-- +-- Who may do what (the functions run as their owner; execute is granted by name): +-- env_gate (the gate's login) records an episode; reads episodes for its decider's context, without the text; +-- adds outcomes +-- env_agent (the assistant's and the voice front end's logins) adds outcomes to an episode it knows the ref of +-- the owner reads the text, deletes, sets the retention (env.set('experience', 'retention_days', '30', 'owner')) + +create extension if not exists pgcrypto; +create extension if not exists vector; + +create table env.experience ( + id bigserial primary key, + ref uuid not null unique default gen_random_uuid(), -- what outcomes and callers refer to + at timestamptz not null default now(), + caller text not null check (caller <> ''), -- the gateway caller the call came from + login text not null default session_user, + request bytea not null, -- the scenario's text (messages as JSON), encrypted + features jsonb not null default '{}' check (jsonb_typeof(features) = 'object'), + embedder text, + embedding vector, + responder text not null check (responder ~ '^(skill:[a-z0-9_.-]+|fast|slow|cloud|model:[a-z0-9_./:-]+)$'), + response bytea, -- what was answered, encrypted + depended_on jsonb not null default '[]' check (jsonb_typeof(depended_on) = 'array'), + decision jsonb not null default '{}' check (jsonb_typeof(decision) = 'object'), + impasse text check (impasse in ('none', 'tie', 'low')) -- null: System 1 answered or routed with confidence +); +create index experience_at on env.experience (at); +create index experience_caller on env.experience (caller, at); + +create table env.outcome ( + id bigserial primary key, + episode bigint not null references env.experience on delete cascade, + kind text not null check (kind in ('ok', 'correct', 'score')), + value jsonb not null, + source text not null check (source <> ''), -- who said so: owner, scorer, task, ... + note bytea, -- encrypted, optional + login text not null default session_user, + at timestamptz not null default now(), + check ((kind = 'ok' and jsonb_typeof(value) = 'boolean') + or (kind = 'correct' and jsonb_typeof(value) = 'string') + or (kind = 'score' and jsonb_typeof(value) = 'number' and (value::text)::numeric between 0 and 1)) +); +create index outcome_episode on env.outcome (episode); + +-- Kept whole: an episode or an outcome is never changed. Deleting is the owner's (forget, expire), and only through +-- them: a login that may record may not delete. +create function env.experience_whole() returns trigger language plpgsql as $$ +begin + if tg_op = 'DELETE' and current_setting('env.forgetting', true) = 'on' then + return old; + end if; + raise exception 'env: experience is kept whole; only the owner forgets it'; +end $$; +create trigger experience_whole before update or delete on env.experience for each row execute function env.experience_whole(); +create trigger outcome_whole before update or delete on env.outcome for each row execute function env.experience_whole(); + +create function env.record_episode(p_key text, p_caller text, p_request text, p_features jsonb, p_embedder text, + p_embedding vector, p_responder text, p_response text, p_depended_on jsonb, + p_decision jsonb, p_impasse text) +returns uuid language plpgsql security definer set search_path = pg_catalog, public as $$ +declare r uuid; +begin + if coalesce(p_key, '') = '' then raise exception 'env: experience needs its key'; end if; + insert into env.experience (caller, login, request, features, embedder, embedding, responder, response, + depended_on, decision, impasse) + values (p_caller, session_user, pgp_sym_encrypt(p_request, p_key), coalesce(p_features, '{}'), p_embedder, + p_embedding, p_responder, case when p_response is null then null else pgp_sym_encrypt(p_response, p_key) end, + coalesce(p_depended_on, '[]'), coalesce(p_decision, '{}'), p_impasse) + returning ref into r; + return r; +end $$; + +create function env.add_outcome(p_ref uuid, p_kind text, p_value jsonb, p_source text, p_note text default null, + p_key text default null) +returns bigint language plpgsql security definer set search_path = pg_catalog, public as $$ +declare e bigint; o bigint; +begin + select id into e from env.experience where ref = p_ref; + if e is null then raise exception 'env: no episode %', p_ref; end if; + if p_note is not null and coalesce(p_key, '') = '' then raise exception 'env: a note needs the key'; end if; + insert into env.outcome (episode, kind, value, source, note, login) + values (e, p_kind, p_value, p_source, case when p_note is null then null else pgp_sym_encrypt(p_note, p_key) end, + session_user) + returning id into o; + return o; +end $$; + +-- The decider's context: episodes with their latest outcome of each kind, newest first, without any text. +create function env.episodes(p_caller text default null, p_since timestamptz default null, p_limit int default 5000) +returns table (ref uuid, at timestamptz, caller text, features jsonb, embedder text, embedding vector, + responder text, decision jsonb, impasse text, ok boolean, correct text, score numeric, outcomes int) +language sql stable security definer set search_path = pg_catalog, public as $$ + select e.ref, e.at, e.caller, e.features, e.embedder, e.embedding, e.responder, e.decision, e.impasse, + (select (o.value)::text::boolean from env.outcome o where o.episode = e.id and o.kind = 'ok' order by o.at desc, o.id desc limit 1), + (select o.value #>> '{}' from env.outcome o where o.episode = e.id and o.kind = 'correct' order by o.at desc, o.id desc limit 1), + (select (o.value)::text::numeric from env.outcome o where o.episode = e.id and o.kind = 'score' order by o.at desc, o.id desc limit 1), + (select count(*)::int from env.outcome o where o.episode = e.id) + from env.experience e + where (p_caller is null or e.caller = p_caller) and (p_since is null or e.at >= p_since) + order by e.at desc, e.id desc + limit greatest(p_limit, 0) +$$; + +-- The owner's: the text back, with the key (a wrong key fails in pgcrypto). +create function env.episode_text(p_ref uuid, p_key text) +returns table (request text, response text) +language sql stable security definer set search_path = pg_catalog, public as $$ + select pgp_sym_decrypt(request, p_key), case when response is null then null else pgp_sym_decrypt(response, p_key) end + from env.experience where ref = p_ref +$$; + +-- The owner's: forget one episode, a time range, or everything (P9). Outcomes go with their episode; nothing else is +-- derived and stored (the decider's context is read fresh). Outcomes are removed by the cascade. Returns the number of episodes deleted. +create function env.forget_experience(p_ref uuid default null, p_from timestamptz default null, + p_to timestamptz default null, p_all boolean default false) +returns int language plpgsql security definer set search_path = pg_catalog, public as $$ +declare n int; +begin + if p_ref is null and p_from is null and p_to is null and not p_all then + raise exception 'env: say what to forget (an episode, a time range, or all)'; + end if; + perform set_config('env.forgetting', 'on', true); + delete from env.experience e + where p_all or e.ref = p_ref + or ((p_from is not null or p_to is not null) and e.at >= coalesce(p_from, '-infinity') and e.at < coalesce(p_to, 'infinity')); + get diagnostics n = row_count; + perform set_config('env.forgetting', 'off', true); + return n; +end $$; + +-- The owner's: drop what is older than the retention (P7), the setting `experience.retention_days` (none: keep). +create function env.expire_experience() returns int language plpgsql security definer set search_path = pg_catalog, public as $$ +declare d numeric; +begin + select (value #>> '{}')::numeric into d from env.setting where env = 'experience' and name = 'retention_days' + order by id desc limit 1; + if d is null or d <= 0 then return 0; end if; + return env.forget_experience(p_to => now() - make_interval(secs => d * 86400)); +end $$; + +revoke all on env.experience, env.outcome from public; +revoke all on function env.record_episode(text, text, text, jsonb, text, vector, text, text, jsonb, jsonb, text), + env.add_outcome(uuid, text, jsonb, text, text, text), env.episodes(text, timestamptz, int), + env.episode_text(uuid, text), env.forget_experience(uuid, timestamptz, timestamptz, boolean), + env.expire_experience() from public; + +do $$ begin + if not exists (select 1 from pg_roles where rolname = 'env_gate') then + create role env_gate nologin; + end if; +end $$; +grant usage on schema env to env_gate; +grant execute on function env.record_episode(text, text, text, jsonb, text, vector, text, text, jsonb, jsonb, text), + env.add_outcome(uuid, text, jsonb, text, text, text), env.episodes(text, timestamptz, int) to env_gate; +grant execute on function env.add_outcome(uuid, text, jsonb, text, text, text) to env_agent; diff --git a/environment/worker.py b/environment/worker.py index 67d5190..3f285b7 100644 --- a/environment/worker.py +++ b/environment/worker.py @@ -18,7 +18,7 @@ The loop (`run_task`) is the seam for MetaSoar's M-17, the model is called only at impasses: before EVERY model call it asks `gate(state)`; a string answers the task without the model (a compiled skill), None lets the model be called. The loop counts the model calls and the skipped calls itself. Settings (environment): GATEWAY_URL, WORKER_KEY (the -caller `worker:loop`, local models only), WORKER_MODEL (local/gemma), WORKER_WORKSPACE (/workspace), +caller `worker:loop`, local models only), WORKER_MODEL (local/slow), WORKER_WORKSPACE (/workspace), WORKER_MAX_STEPS (8), WORKER_CONTEXT_TOKENS (11000 of the model's 16k), WORKER_MAX_TOKENS (1024), WORKER_REASONING (empty), WORKER_MCP_COMMAND (kernel-mcp), WORKER_LOGIN_FILE (/login, from scripts/kernel.sh login worker). """ @@ -206,7 +206,7 @@ def kernel_env(login_file: str | None = None) -> dict[str, str]: def openai_model(gateway: str | None = None, key: str | None = None, model: str | None = None) -> Model: from openai import AsyncOpenAI - key, name = key or setting("WORKER_KEY"), model or setting("WORKER_MODEL", "local/gemma") + key, name = key or setting("WORKER_KEY"), model or setting("WORKER_MODEL", "local/slow") base = (gateway or setting("GATEWAY_URL", "http://gateway:8080")).rstrip("/") + "/v1" clients: dict = {} # one client per event loop: each task is its own asyncio.run, and a client's connections # belong to the loop that opened them ("Event loop is closed" on the next task otherwise) @@ -297,7 +297,10 @@ def finish(text: str, ok: bool) -> dict: return finish(f"the model call failed: {type(x).__name__}: {str(x)[:300]}", False) calls = m.get("tool_calls") or [] if not calls: - return finish((m.get("content") or "").strip(), True) + text = (m.get("content") or "").strip() + if not text: # e.g. the model spent its tokens thinking (S-171) + return finish("the model gave no answer (it may have used its tokens thinking; WORKER_MAX_TOKENS)", False) + return finish(text, True) msgs.append({"role": "assistant", "content": m.get("content"), "tool_calls": [ {"id": c["id"], "type": "function", "function": {"name": c["name"], "arguments": c["arguments"]}} for c in calls]}) for c in calls: @@ -387,7 +390,9 @@ async def go(): except Exception as x: # noqa: BLE001 - e.g. the kernel's MCP server did not start out = {"text": f"could not start the tools: {type(x).__name__}: {str(x)[:300]}", "ok": False, "model_calls": 0, "skipped_calls": 0, "steps": 0, "cited": []} - e.publish(f"{ENV}.task.done", {**out, "task": text or "", "msg": m["msg_id"]}, SOURCE) + # reply_to: who asked, when they want the answer back (the voice head reads out its own, S-170) + reply_to = body.get("reply_to") if isinstance(body, dict) and isinstance(body.get("reply_to"), str) else None + e.publish(f"{ENV}.task.done", {**out, "task": text or "", "msg": m["msg_id"], **({"reply_to": reply_to} if reply_to else {})}, SOURCE) action, _ = e.act(f"{ENV}.reply", {"text": out["text"]}, SOURCE) for r in e.read(f"act_{ENV}_reply", 60, 10): e.done(r["action"], {"shown": True}) @@ -409,6 +414,14 @@ def run() -> None: import psycopg model = openai_model() gate, gate_env = None, None + # notes/ is shared with the voice head (S-171), which runs in the worker's group: group-writable, setgid + ws = setting("WORKER_WORKSPACE", "/workspace") + for d in (ws, os.path.join(ws, "notes")): + try: + os.makedirs(d, exist_ok=True) + os.chmod(d, 0o2775) + except OSError as x: + log(f"workspace {d}: {x}") cmd = shlex.split(setting("WORKER_MCP_COMMAND", "kernel-mcp")) factory = lambda: McpTools(cmd, kernel_env()) # noqa: E731 e = None diff --git a/repos.yaml b/repos.yaml index 5fad759..e39b6e8 100644 --- a/repos.yaml +++ b/repos.yaml @@ -9,9 +9,8 @@ morphogen: branch: main checked: b57fbbbae477534066b3aa231bd6472bf461acbc # 2026-11-16 (#81 unnamed metrics kept; #82 a short-scored run refused; #83 the intake) # The Knowledge Kernel, Substrate's store (S-153, S-154): its image is built from this clone (scripts/build.sh kernel) and -# the tests of the store on the kernel run in it. Until the kernel's pull requests 117 and 118 (the Substrate read model -# and the substrate profile of its MCP server) are merged, the branch that holds them; then main. +# the tests of the store on the kernel run in it; its published image (ghcr.io/openreplicant/kernel:main) is pulled (S-167). kernel: url: https://github.com/OpenReplicant/kernel branch: main - checked: 94b578d21222e4faea26a459376e3d4508344cac # 2026-11-21 main with #117 and #118 (D-103 the exporter, D-104 the read model, D-105 the profile) + checked: 041146054f7b7a155a76dda3bc843ad1405b3739 # 2026-11-22 main after #132 (D-120 bundles); the image's revision; test_kernel, test_ui, test_worker pass diff --git a/scripts/catalog.py b/scripts/catalog.py new file mode 100644 index 0000000..13fda82 --- /dev/null +++ b/scripts/catalog.py @@ -0,0 +1,180 @@ +"""Substrate's catalog (S-176): its parts as Backstage entity files in catalog/, one per entity, which the kernel reads +with encoder-backstage (the kernel's D-100). This script checks them, without the kernel: + +- **fit**: every API a component consumes has a provider; every API is provided by someone; every reference + (providesApis, consumesApis, dependsOn, owner, system) names an entity that exists; +- **what uses what**: each component that uses some APIs to provide others (the gateway uses llama-server's API to + provide its own chat API, a translator; the voice head uses several to provide its page); where two parts share no + API, a translator from the catalog has to go between them; +- **compose**: the catalog against deploy/compose.yaml, both ways: a service with no entry, an entry naming a service + compose does not have; +- **kernel** (`--kernel`): the same fit read from the kernel's claims (what `scripts/kernel.sh catalog` put there, through + the read model, under its own role), and the drift between the files and the kernel: a provides or consumes in one + and not the other (a file changed and not yet encoded). + + bin/in-tools python3 scripts/catalog.py check [--compose deploy/compose.yaml] [--kernel] + bin/in-tools python3 scripts/catalog.py apis # each API with its providers and consumers + +Exit 1 when a check fails. Needs PyYAML (the tools container has it). +""" +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +import yaml + +ROOT = Path(__file__).resolve().parents[1] +ANN = "substrate.dev/" + + +def load(directory: Path) -> dict[tuple[str, str], dict]: + """(kind, name) -> entity, lower-cased kind; every document of every *.yaml file.""" + out: dict[tuple[str, str], dict] = {} + for f in sorted(directory.glob("*.yaml")): + for doc in yaml.safe_load_all(f.read_text(encoding="utf-8")): + if not isinstance(doc, dict) or "kind" not in doc: + continue + key = (doc["kind"].lower(), doc["metadata"]["name"]) + if key in out: + raise SystemExit(f"{f.name}: {key[0]}:{key[1]} is defined twice") + doc["_file"] = f.name + out[key] = doc + return out + + +def ref(r: str, default_kind: str) -> tuple[str, str]: + """A Backstage entity reference: [kind:][namespace/]name.""" + kind, _, name = r.rpartition(":") + return (kind or default_kind).lower(), name.split("/")[-1] + + +def apis(ents: dict) -> dict[str, dict[str, list[str]]]: + table = {n: {"providers": [], "consumers": []} for (k, n) in ents if k == "api"} + for (k, n), e in ents.items(): + if k != "component": + continue + for a in e["spec"].get("providesApis") or []: + table.setdefault(ref(a, "api")[1], {"providers": [], "consumers": []})["providers"].append(n) + for a in e["spec"].get("consumesApis") or []: + table.setdefault(ref(a, "api")[1], {"providers": [], "consumers": []})["consumers"].append(n) + return table + + +def check(ents: dict, compose: Path | None) -> list[str]: + problems: list[str] = [] + table = apis(ents) + for name, t in sorted(table.items()): + if ("api", name) not in ents: + problems.append(f"API {name} is referenced ({', '.join(t['providers'] + t['consumers'])}) but has no entry") + if not t["providers"]: + who = f", consumed by {', '.join(t['consumers'])}" if t["consumers"] else "" + problems.append(f"gap: no component provides API {name}{who}") + for (k, n), e in ents.items(): + spec = e.get("spec") or {} + for field, default in (("dependsOn", "component"), ("owner", "group"), ("system", "system")): + vals = spec.get(field) + for r in ([vals] if isinstance(vals, str) else vals or []): + if ref(r, default) not in ents: + problems.append(f"{k}:{n} ({e['_file']}): {field} {r} names no entity") + if compose: + services = set((yaml.safe_load(compose.read_text(encoding="utf-8")).get("services") or {})) + named = {e["metadata"].get("annotations", {}).get(ANN + "compose-service"): f"{k}:{n}" + for (k, n), e in ents.items() if e["metadata"].get("annotations", {}).get(ANN + "compose-service")} + for s in sorted(services - set(named)): + problems.append(f"compose service {s} has no catalog entry") + for s, who in sorted(named.items()): + if s not in services: + problems.append(f"{who} names compose service {s}, which {compose.name} does not have") + return problems + + +BS = "https://w3id.org/knowledge-kernel/backstage#" +SYSTEM = "urn:kk:system:substrate" + + +def kernel_links() -> set[tuple[str, str, str]]: + """(component, providesApi|consumesApi, api) for every component part of Substrate's system, from the kernel's + usable claims, read as the read model's role (as the UI reads them).""" + import os + import psycopg + sys.path[:0] = [str(ROOT / "scripts"), str(ROOT)] + from db import kernel_url + from gateway import settings + url = os.environ.get("KERNEL_URL") or kernel_url(settings()) + with psycopg.connect(url, connect_timeout=10) as c: + c.execute("set role kkm_view_substrate") + rows = c.execute( + "select u.subject, u.predicate, u.object_entity from substrate.usable u where u.predicate = any(%s) and " + "exists (select 1 from substrate.usable p where p.subject = u.subject and p.predicate = %s and p.object_entity = %s)", + ([BS + "providesApi", BS + "consumesApi"], BS + "partOf", SYSTEM)).fetchall() + name = lambda iri: iri.rsplit(":", 1)[-1] # noqa: E731 + return {(name(s), p.rsplit("#", 1)[-1], name(o)) for s, p, o in rows} + + +def file_links(ents: dict) -> set[tuple[str, str, str]]: + out = set() + for (k, n), e in ents.items(): + if k == "component": + for field, rel in (("providesApis", "providesApi"), ("consumesApis", "consumesApi")): + out |= {(n, rel, ref(a, "api")[1]) for a in e["spec"].get(field) or []} + return out + + +def check_kernel(ents: dict) -> tuple[list[str], int]: + links = kernel_links() + problems = [] + provided = {a for _, r, a in links if r == "providesApi"} + for c, r, a in sorted(links): + if r == "consumesApi" and a not in provided: + problems.append(f"kernel: gap: {c} consumes {a}, which no component of the system provides") + f = file_links(ents) + for c, r, a in sorted(f - links): + problems.append(f"drift: the files say {c} {r} {a}; the kernel does not (scripts/kernel.sh catalog)") + for c, r, a in sorted(links - f): + problems.append(f"drift: the kernel says {c} {r} {a}; the files do not") + return problems, len(links) + + +def translators(ents: dict) -> list[tuple[str, list[str], list[str]]]: + """Components that provide some APIs by consuming others: the bridges in the map.""" + out = [] + for (k, n), e in sorted(ents.items()): + if k == "component" and e["spec"].get("providesApis") and e["spec"].get("consumesApis"): + out.append((n, e["spec"]["consumesApis"], e["spec"]["providesApis"])) + return out + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("command", choices=["check", "apis"]) + ap.add_argument("--catalog", default=str(ROOT / "catalog")) + ap.add_argument("--compose", default=None, help="a compose file to compare with (check)") + ap.add_argument("--kernel", action="store_true", help="also check the kernel's claims, and their drift from the files") + a = ap.parse_args() + ents = load(Path(a.catalog)) + if a.command == "apis": + for name, t in sorted(apis(ents).items()): + typ = ents.get(("api", name), {}).get("spec", {}).get("type", "?") + print(f"{name} [{typ}]: provided by {', '.join(t['providers']) or 'nobody'}; consumed by {', '.join(t['consumers']) or 'nobody'}") + return + problems = check(ents, Path(a.compose) if a.compose else None) + if a.kernel: + kp, n = check_kernel(ents) + print(f"kernel: {n} provides and consumes links of {SYSTEM}") + problems += kp + kinds = {} + for (k, _) in ents: + kinds[k] = kinds.get(k, 0) + 1 + print("catalog: " + ", ".join(f"{v} {k}" for k, v in sorted(kinds.items()))) + for n, ins, outs in translators(ents): + print(f" {n} uses {', '.join(ins)} to provide {', '.join(outs)}") + for p in problems: + print(" FAIL " + p) + print("ok: every consumed API has a provider and every reference resolves" if not problems else f"{len(problems)} problem(s)") + sys.exit(1 if problems else 0) + + +if __name__ == "__main__": + main() diff --git a/scripts/check.sh b/scripts/check.sh index d8b7c48..272ea73 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -58,7 +58,12 @@ with connect(settings(), DB) as c: else bad "the environment: $(printf '%s\n' "$out" | tail -1) (bin/in-tools python3 scripts/db.py init)"; fi # Probe with a provider this machine has: Bifrost answers 400 for one it has none of, before it checks the key probe=openrouter/x:free; [ -z "$(env_value OPENROUTER_API_KEY)" ] && [ -n "$(env_value OLLAMA_URL)" ] && probe=ollama/x -code=$(curl -s -o /dev/null -w '%{http_code}' -X POST "http://127.0.0.1:$(env_value GATEWAY_PORT)/v1/chat/completions" -H 'Content-Type: application/json' -d "{\"model\":\"$probe\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}]}") +# 000 is no answer yet: a gateway just recreated may restart once or twice before it reaches its database (podman 4.9's +# network DNS drops lookups while many containers start at once, S-169), so wait up to a minute for one +for _ in $(seq 1 30); do + code=$(curl -s -o /dev/null -w '%{http_code}' -X POST "http://127.0.0.1:$(env_value GATEWAY_PORT)/v1/chat/completions" -H 'Content-Type: application/json' -d "{\"model\":\"$probe\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}]}") + [ "$code" = 000 ] || break; sleep 2 +done [ "$code" = "401" ] && ok "gateway http://127.0.0.1:$(env_value GATEWAY_PORT)/ (Bifrost; a call without a key is refused)" || bad "the model gateway returned $code to a call without a key (scripts/logs.sh gateway)" # The companion (plan step 4, S-136): its session in tmux, and whether the owner's Claude login is in its home yet if out=$(compose exec -T companion sh -c 'tmux has-session -t companion 2>/dev/null && echo session; test -s "$HOME/.claude/.credentials.json" && echo login; true' 2>/dev/null); then @@ -73,7 +78,12 @@ case ",$(env_value COMPOSE_PROFILES)," in *,llm,*) case "$running" in *-llm-*) ;; *) bad "service llm is not running (scripts/logs.sh llm)" ;; esac if [ "$("$ENGINE" inspect -f '{{.State.Health.Status}}' substrate-llm-1 2>/dev/null)" = healthy ]; then ok "llm $(env_value LLM_MODEL) on llama.cpp, at the gateway as local/$(env_value LLM_ALIAS)" - else note "llm not healthy yet (a large model takes minutes to load; scripts/logs.sh llm)"; fi ;; + else note "llm not healthy yet (a large model takes minutes to load; scripts/logs.sh llm)"; fi + if [ -n "$(env_value LLM_FAST_MODEL)" ]; then + if [ "$("$ENGINE" inspect -f '{{.State.Health.Status}}' substrate-llm-fast-1 2>/dev/null)" = healthy ]; then + ok "llm-fast $(env_value LLM_FAST_MODEL) on llama.cpp, at the gateway as fast/$(env_value LLM_FAST_ALIAS)" + else note "llm-fast not healthy yet (scripts/logs.sh llm-fast)"; fi + fi ;; esac case ",$(env_value COMPOSE_PROFILES)," in *,voice,*) vp=$(env_value VOICE_PORT); vp=${vp:-8110} @@ -95,6 +105,10 @@ say "Wiring" if st=$(sec_status 2>&1); then ok "secrets ($SECRETS): $st"; else bad "secrets ($SECRETS): $st"; fi "$ROOT/scripts/tools.sh" status >/dev/null 2>&1 && ok "tools container running (bin/ wrappers work)" || bad "tools container not running: scripts/tools.sh start" "$ROOT/bin/gitleaks" version >/dev/null 2>&1 && ok "gitleaks in the tools container: $("$ROOT/bin/gitleaks" version 2>/dev/null)" || bad "bin/gitleaks does not run" +# The catalog (S-176): every part an entry, every consumed API provided, every compose service described +if out=$("$ROOT/bin/in-tools" python3 "$ROOT/scripts/catalog.py" check --compose "$ROOT/deploy/compose.yaml" 2>&1); then + ok "catalog $(printf '%s\n' "$out" | head -1 | sed 's/^catalog: //'); fits, matches compose" +else bad "catalog: $(printf '%s\n' "$out" | grep FAIL | head -2 | sed 's/^ *FAIL *//' | tr '\n' ';') (bin/in-tools python3 scripts/catalog.py check --compose deploy/compose.yaml)"; fi # where the local model server computes: its last device report (S-84) dev=$(rt_logs ollama 2>/dev/null | grep 'msg="inference compute"' | tail -1 | sed -n 's/.*library=\([^ ]*\).*description="\([^"]*\)".*total="\([^"]*\)".*/\1 on \2, \3/p') gpu=$(env_value OLLAMA_GPU) diff --git a/scripts/gateway.py b/scripts/gateway.py index df20f38..5347061 100644 --- a/scripts/gateway.py +++ b/scripts/gateway.py @@ -32,7 +32,7 @@ NAMES = ("POSTGRES_PASSWORD", "DB_PORT", "OPENROUTER_API_KEY", "OLLAMA_URL", "GATEWAY_OPENROUTER_MODELS", "GATEWAY_REQUESTS_PER_HOUR", "GATEWAY_DB_PASSWORD", "GATEWAY_METER_PASSWORD", "GATEWAY_KEY_SECRET", "GATEWAY_PORT", "COMPANION_MODELS", "COMPANION_DB_PASSWORD", - "LLM_MODEL", "JUDGE_DB_PASSWORD", "WORKER_DB_PASSWORD", "WORKER_BLOCKS", "KERNEL_URL", "KK_AUTHENTICATOR_PASSWORD") + "LLM_MODEL", "LLM_FAST_MODEL", "JUDGE_DB_PASSWORD", "WORKER_DB_PASSWORD", "WORKER_BLOCKS", "KERNEL_URL", "KK_AUTHENTICATOR_PASSWORD") def settings() -> dict[str, str]: @@ -54,10 +54,12 @@ def caller_key(secret: str, caller: str) -> str: # The voice head (plan step 5) talks with the local model (llama.cpp, provider `local`) only: what the owner says # aloud stays on this machine (P3) unless the model hands a request to the companion. The worker (plan step 1, S-163) # is an offline agent on the same local model: its loop, its tool calls and its recall never leave the machine. +# Two local models (S-169): `local`, the slow one on the CPU, and `fast`, the small one on the GPU; both stay here. +# The voice head also embeds through Ollama, for its router (S-170). CALLERS = {"store:embed": ("ollama",), "companion:session": ("anthropic",), "companion:task": ("anthropic",), - "voice:head": ("local",), "companion:author": ("local",), "judge:voice": ("local",), - "worker:loop": ("local",)} -LOCAL = ("ollama", "local") + "voice:head": ("local", "fast", "ollama"), "companion:author": ("local",), "judge:voice": ("local",), + "worker:loop": ("local", "fast")} +LOCAL = ("ollama", "local", "fast") FIXED_KEYS = {"store:embed": "STORE_EMBED_KEY", "companion:session": "COMPANION_SESSION_KEY", "companion:task": "COMPANION_TASK_KEY", "voice:head": "VOICE_KEY", "companion:author": "COMPANION_AUTHOR_KEY", "judge:voice": "JUDGE_KEY", @@ -88,9 +90,17 @@ def render(env: dict[str, str]) -> dict: "allow_private_network": True}, "custom_provider_config": {"base_provider_type": "openai", "allowed_requests": {"chat_completion": True, "chat_completion_stream": True}}} + # the fast local model (compose service llm-fast, S-169), the same way + if env.get("LLM_FAST_MODEL"): + providers["fast"] = { + "keys": [{"name": "llm-fast", "value": "no-key", "models": ["*"], "weight": 1.0}], + "network_config": {"base_url": "http://llm-fast:8080", "default_request_timeout_in_seconds": 120, + "allow_private_network": True}, + "custom_provider_config": {"base_provider_type": "openai", + "allowed_requests": {"chat_completion": True, "chat_completion_stream": True}}} # Anthropic with no key of its own: only calls carrying a Claude login (the companion's) can use it providers["anthropic"] = {"keys": []} - allowed = {"local": ["*"], "anthropic": [m.strip() for m in (env.get("COMPANION_MODELS") or "regex:claude-haiku.*").split(",") if m.strip()], + allowed = {"local": ["*"], "fast": ["*"], "anthropic": [m.strip() for m in (env.get("COMPANION_MODELS") or "regex:claude-haiku.*").split(",") if m.strip()], "openrouter": [m.strip() for m in (env.get("GATEWAY_OPENROUTER_MODELS") or "regex:.*:free").split(",") if m.strip()], "ollama": ["regex:.*"]} secret = env.get("GATEWAY_KEY_SECRET") or "" diff --git a/scripts/kernel.sh b/scripts/kernel.sh index 7c7fb4c..c5290a8 100755 --- a/scripts/kernel.sh +++ b/scripts/kernel.sh @@ -6,6 +6,8 @@ # scripts/kernel.sh init # install the kernel's schema and default modules (safe to run again) # scripts/kernel.sh export # the store's items and statements as kernel change sets (safe to run again: # # an unchanged item submits nothing); the kernel service applies them +# scripts/kernel.sh catalog # catalog/*.yaml (Substrate's parts, Backstage entities) into the kernel by +# # encoder-backstage (S-176); an unchanged file submits nothing # scripts/kernel.sh login NAME # an agent's own login (printed nowhere: .state/kernel/NAME.env, mode 600) and # # its MCP entry `kernel` in .mcp.json (the profile substrate: ten tools) # scripts/kernel.sh login NAME --no-mcp-json # the same, without touching .mcp.json (the worker's: up.sh runs it) @@ -24,6 +26,9 @@ case "${1:-}" in export) compose run --rm --no-deps kernel-export ;; + catalog) + compose run --rm --no-deps kernel-catalog + ;; login) name=${2:?usage: scripts/kernel.sh login NAME [--no-mcp-json]} nomcp=${3:-} diff --git a/scripts/tests/test_catalog.py b/scripts/tests/test_catalog.py new file mode 100644 index 0000000..d37b525 --- /dev/null +++ b/scripts/tests/test_catalog.py @@ -0,0 +1,77 @@ +"""Substrate's catalog and its check (S-176). No database: catalog files in a temporary folder. +It should: +- pass on the repository's own catalog/ against deploy/compose.yaml +- report an API nobody provides, an API referenced with no entry, a reference to no entity +- report a compose service with no entry, and an entry naming a service compose does not have +- list what each component uses to provide what +- refuse an entity defined twice + + python3 scripts/tests/test_catalog.py +""" +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "scripts")) + +import catalog as C # noqa: E402 + +checks = [] + + +def check(name, ok, detail=""): + checks.append(bool(ok)) + print(("ok " if ok else "FAIL"), name, "" if ok else detail) + + +def ent(kind, name, spec=None, annotations=None): + md = {"name": name, **({"annotations": annotations} if annotations else {})} + import yaml + return yaml.safe_dump({"apiVersion": "backstage.io/v1alpha1", "kind": kind, "metadata": md, "spec": spec or {}}) + + +def folder(files: dict) -> Path: + d = Path(tempfile.mkdtemp()) + for n, text in files.items(): + (d / n).write_text(text) + return d + + +def main(): + ents = C.load(ROOT / "catalog") + problems = C.check(ents, ROOT / "deploy/compose.yaml") + check("the repository's catalog fits and matches compose", problems == [], problems) + check("it describes its components and their APIs", sum(k == "component" for k, _ in ents) >= 20 and sum(k == "api" for k, _ in ents) >= 20) + check("the gateway is listed as using the model servers to provide the chat API", + any(n == "gateway" and "llama-chat-slow" in ins and "model-chat" in outs for n, ins, outs in C.translators(ents))) + + base = {"system.yaml": ent("System", "s", {"owner": "group:o"}), "group.yaml": ent("Group", "o", {"type": "team"})} + d = folder({**base, + "a.yaml": ent("Component", "a", {"owner": "o", "system": "s", "consumesApis": ["x"], "dependsOn": ["resource:db"]}, + {"substrate.dev/compose-service": "a"}), + "b.yaml": ent("Component", "b", {"owner": "o", "system": "s", "providesApis": ["y"]}, + {"substrate.dev/compose-service": "gone"}), + "x.yaml": ent("API", "x", {"type": "openapi", "owner": "o", "system": "s"})}) + compose = d / "compose.yaml" + compose.write_text("services:\n a: {image: a}\n extra: {image: e}\n") + p = C.check(C.load(d), compose) + check("an API nobody provides is a gap, with who consumes it", any("gap: no component provides API x, consumed by a" in m for m in p), p) + check("an API referenced with no entry is reported", any("API y is referenced" in m for m in p), p) + check("a reference to no entity is reported", any("dependsOn resource:db names no entity" in m for m in p), p) + check("a compose service with no entry is reported", any("compose service extra has no catalog entry" in m for m in p), p) + check("an entry naming a service compose does not have is reported", any("names compose service gone" in m for m in p), p) + + twice = folder({"one.yaml": ent("API", "x"), "two.yaml": ent("API", "x")}) + try: + C.load(twice) + check("an entity defined twice is refused", False) + except SystemExit as e: + check("an entity defined twice is refused", "defined twice" in str(e), e) + + print(f"{sum(checks)}/{len(checks)} checks passed") + sys.exit(0 if all(checks) else 1) + + +if __name__ == "__main__": + main() diff --git a/scripts/tests/test_experience.py b/scripts/tests/test_experience.py new file mode 100644 index 0000000..57ed850 --- /dev/null +++ b/scripts/tests/test_experience.py @@ -0,0 +1,134 @@ +"""The assistant's experience (S-182), in a throwaway database it drops after (ADMIN_URL from scripts/test.sh). It should: +- record an episode and return its ref; keep the request and response encrypted, readable only with the key +- give the gate (env_gate) record, outcomes and the decider's context (with the latest label of each kind), never + the text, never a change or a delete +- let the assistant (env_agent) add an outcome, and nothing else here +- keep episodes and outcomes whole; attach outcomes later, the latest of each kind winning +- forget one episode, a time range, or all, with their outcomes; expire by the retention setting; refuse a vague forget + + scripts/test.sh scripts/tests/test_experience.py +""" +import os +import sys +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import psycopg + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) + +from environment import db as envdb # noqa: E402 +from environment.experience import Experience # noqa: E402 + +KEY = "test-only-experience-key" +checks = [] + + +def check(name, ok, detail=""): + checks.append(bool(ok)) + print(("ok " if ok else "FAIL"), name, "" if ok else detail) + + +def refused(fn, needle=""): + try: + fn() + except (psycopg.Error, ValueError) as e: + return needle in str(e) + return False + + +def main(): + admin = os.environ["ADMIN_URL"] + pid = os.getpid() + name, gate, agent = f"exp_{pid}", f"gate_{pid}", f"agent_{pid}" + with psycopg.connect(admin, autocommit=True) as a: + a.execute(f"create database {name}") + url = admin.rsplit("/", 1)[0] + "/" + name + host = url.split("@", 1)[1].split("/", 1)[0] + try: + with psycopg.connect(url, autocommit=True) as c: + envdb.migrate(c) + for login, role in ((gate, "env_gate"), (agent, "env_agent")): + c.execute(f"create role {login} login password 'test-only'") + c.execute(f"grant {role} to {login}") + with psycopg.connect(f"postgresql://{gate}:test-only@{host}/{name}", autocommit=True) as gc, \ + psycopg.connect(f"postgresql://{agent}:test-only@{host}/{name}", autocommit=True) as ac: + run(c, gc, ac) + finally: + with psycopg.connect(admin, autocommit=True) as a: + a.execute(f"drop database {name} with (force)") + a.execute(f"drop role if exists {gate}") + a.execute(f"drop role if exists {agent}") + print(f"{sum(checks)}/{len(checks)} checks passed") + sys.exit(0 if all(checks) else 1) + + +def run(c, gc, ac): + owner, g, a = Experience(c, KEY), Experience(gc, KEY), Experience(ac, KEY) + words = "Remind me to call the dentist on Monday" + ref = g.record("voice:head", [{"role": "user", "content": words}], "skill:remind", response="Noted.", + features={"step": 0, "tools": 6}, embedding=[0.1, 0.2, 0.3], embedder="test", impasse=None, + decision={"p": {"skill:remind": 0.93}, "threshold": 0.9}, depended_on=[{"tool": "now"}]) + check("the gate records an episode and gets its ref", len(ref) == 36, ref) + raw = c.execute("select request, response from env.experience where ref = %s", (ref,)).fetchone() + check("the request and response are stored encrypted", words.encode() not in bytes(raw[0]) and b"Noted" not in bytes(raw[1])) + t = owner.text(ref) + check("the owner reads the text back with the key", t and words in t["request"] and t["response"] == "Noted.", t) + check("a wrong key reads nothing", refused(lambda: Experience(c, "wrong-key").text(ref))) + check("recording without a key is refused", refused(lambda: Experience(gc, "").record("voice:head", "x", "fast"))) + check("the gate cannot read the text", refused(lambda: g.text(ref), "permission denied")) + check("the gate cannot select the table", refused(lambda: gc.execute("select request from env.experience").fetchall(), "permission denied")) + check("the gate cannot change an episode", refused(lambda: gc.execute("update env.experience set responder = 'fast'"), "permission denied")) + check("the gate cannot forget", refused(lambda: g.forget(everything=True), "permission denied")) + check("the owner cannot change an episode either", refused(lambda: c.execute("update env.experience set responder = 'fast'"), "kept whole")) + check("a bad responder is refused", refused(lambda: g.record("voice:head", "x", "anyone"))) + check("a bad impasse is refused", refused(lambda: g.record("voice:head", "x", "fast", impasse="stuck"))) + + ep = g.episodes() + check("the context has the episode, its features and embedding, no labels yet", + len(ep) == 1 and ep[0]["ref"] == ref and ep[0]["features"]["step"] == 0 and ep[0]["embedding"] == [0.1, 0.2, 0.3] + and ep[0]["ok"] is None and ep[0]["outcomes"] == 0, ep) + check("the context carries no text", not any(words in str(v) for v in ep[0].values())) + + g.outcome(ref, "ok", True, source="task") + a.outcome(ref, "ok", False, source="owner", note="it was Tuesday") + a.outcome(ref, "correct", "skill:remind", source="owner") + g.outcome(ref, "score", 0.5, source="scorer") + ep = g.episodes()[0] + check("outcomes attach later; the latest of each kind wins", ep["ok"] is False and ep["correct"] == "skill:remind" + and ep["score"] == 0.5 and ep["outcomes"] == 4, ep) + note = c.execute("select note from env.outcome where note is not null").fetchone()[0] + check("an outcome's note is encrypted", b"Tuesday" not in bytes(note)) + check("a score outside 0..1 is refused", refused(lambda: g.outcome(ref, "score", 2, source="scorer"))) + check("an ok that is not a boolean is refused", refused(lambda: g.outcome(ref, "ok", "yes", source="task"))) + check("an outcome for no episode is refused", refused(lambda: g.outcome("00000000-0000-0000-0000-000000000000", "ok", True, "task"), "no episode")) + check("the assistant cannot read the context", refused(lambda: a.episodes(), "permission denied")) + check("the assistant cannot record", refused(lambda: a.record("worker:loop", "x", "slow"), "permission denied")) + check("an outcome cannot be deleted", refused(lambda: c.execute("delete from env.outcome"), "kept whole")) + + # forgetting: one, a range, all; retention + old = g.record("worker:loop", "old one", "slow") + c.execute("set session_replication_role = replica") # the owner backdates for the test only (triggers off) + c.execute("update env.experience set at = now() - interval '40 days' where ref = %s", (old,)) + c.execute("set session_replication_role = origin") + mid = g.record("worker:loop", "middle", "fast") + g.outcome(mid, "ok", True, "task") + check("caller and since filter the context", [e["ref"] for e in g.episodes(caller="worker:loop", since=datetime.now(timezone.utc) - timedelta(days=1))] == [mid]) + check("a vague forget is refused", refused(lambda: owner.forget(), "say what to forget")) + check("forgetting one episode removes it and its outcomes", owner.forget(ref=mid) == 1 + and c.execute("select count(*) from env.outcome o join env.experience e on e.id = o.episode where e.ref = %s", (mid,)).fetchone()[0] == 0 + and mid not in [e["ref"] for e in owner.episodes()]) + check("no retention set: nothing expires", owner.expire() == 0) + c.execute("select env.set('experience', 'retention_days', '30', 'owner')") + check("retention expires what is older", owner.expire() == 1 and old not in [e["ref"] for e in owner.episodes()]) + r2 = g.record("worker:loop", "today", "slow") + now = datetime.now(timezone.utc) + check("forgetting a time range", owner.forget(start=now - timedelta(hours=1), end=now + timedelta(hours=1)) == 2 + and owner.episodes() == [], r2) + g.record("worker:loop", "again", "slow") + check("forgetting everything", owner.forget(everything=True) == 1 and c.execute("select count(*) from env.outcome").fetchone()[0] == 0) + + +if __name__ == "__main__": + main() diff --git a/scripts/tests/test_gateway.py b/scripts/tests/test_gateway.py index 299973d..63d12eb 100644 --- a/scripts/tests/test_gateway.py +++ b/scripts/tests/test_gateway.py @@ -41,8 +41,14 @@ def main(): lk = {k["name"]: k for k in local["governance"]["virtual_keys"]} check("with a local model, it is a provider of its own", "local" in local["providers"] and local["providers"]["local"]["network_config"]["base_url"] == "http://llm:8080") - check("the voice head reaches the local model only (what is said aloud stays here)", - [p["provider"] for p in lk["voice:head"]["provider_configs"]] == ["local"], lk["voice:head"]["provider_configs"]) + check("the voice head reaches local providers only (what is said aloud stays here)", + {p["provider"] for p in lk["voice:head"]["provider_configs"]} <= set(gateway.LOCAL) + and "local" in {p["provider"] for p in lk["voice:head"]["provider_configs"]}, lk["voice:head"]["provider_configs"]) + both = gateway.render({**env, "LLM_MODEL": "model.gguf", "LLM_FAST_MODEL": "fast.gguf"}) + bk = {k["name"]: k for k in both["governance"]["virtual_keys"]} + check("with a fast model too, it is provider fast, which the voice head and the worker reach (S-169)", + both["providers"]["fast"]["network_config"]["base_url"] == "http://llm-fast:8080" + and all("fast" in {p["provider"] for p in bk[c]["provider_configs"]} for c in ("voice:head", "worker:loop"))) check("the companion does not reach the local model", all(p["provider"] == "anthropic" for c in ("companion:session", "companion:task") for p in lk[c]["provider_configs"])) check("Anthropic has no key of its own (only a caller's Claude login reaches it)", cfg["providers"]["anthropic"] == {"keys": []}) diff --git a/scripts/tests/test_voice_route.py b/scripts/tests/test_voice_route.py new file mode 100644 index 0000000..4c60e46 --- /dev/null +++ b/scripts/tests/test_voice_route.py @@ -0,0 +1,137 @@ +"""The voice head's router (S-170). No network: a fake embedder stands in for the gateway's embedding model. +It should: +- route by the majority of the k nearest examples, and say which examples decided +- take an owner's example (a correction) over the seed once it is added +- refuse to be built with no usable examples, and ignore examples whose route is not talk or work +- keep its seed balanced and free of the trial's held-out utterances (scripts/trials/voice-route) +- read the fast model's tool call as talk, delegate or save_note; plain words as talk; anything else as nothing +- ask for a forced tool call with thinking off and a stop at ; the final step offers only talk and delegate +- read a talk call's text as it streams, escapes split across chunks included +- quick tools (S-171): notes saved and found, reminders' times read or refused, arithmetic only, Wikipedia and + search results shaped from fake answers + + python3 scripts/tests/test_voice_route.py +""" +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) + +from voice import route # noqa: E402 + +checks = [] + + +def check(name, ok, detail=""): + checks.append(bool(ok)) + print(("ok " if ok else "FAIL"), name, "" if ok else detail) + + +WORDS = ["file", "save", "search", "computer", "note", "hello", "joke", "feel", "thanks", "capital"] + + +def fake_embed(texts): + """A bag of words over a tiny vocabulary: enough to make near things near.""" + out = [] + for t in texts: + t = t.split("Query: ", 1)[-1].lower() + out.append([float(t.count(w)) for w in WORDS] + [0.01]) + return out + + +def main(): + r = route.Router(fake_embed, [("hello there", "talk"), ("tell me a joke", "talk"), ("thanks a lot", "talk"), + ("save the file", "work"), ("search the computer", "work"), ("save a note", "work")]) + got, why = r.route("please save this note to a file") + check("a request near the work examples is work", got == "work", (got, why)) + check("it says which examples decided, with their similarity", len(why["near"]) == 3 + and all({"similarity", "text", "route"} <= set(n) for n in why["near"]), why) + got, _ = r.route("hello, and thanks for the joke") + check("small talk near the talk examples is talk", got == "talk", got) + + r.set_examples(r.examples + [("save me a joke", "talk")] * 3) + got, _ = r.route("save me a joke") + check("an owner's example (three of them) outvotes the seed for its own utterance", got == "talk", got) + + try: + route.Router(fake_embed, [("x", "maybe")]) + check("no usable examples is refused", False) + except ValueError: + check("no usable examples is refused", True) + r2 = route.Router(fake_embed, [("hello", "talk"), ("save the file", "work"), ("noise", "later")]) + check("an example with an unknown route is ignored", len(r2.examples) == 2, r2.examples) + + seed = [t for t, _ in route.SEED] + talk = sum(1 for _, x in route.SEED if x == "talk") + check("the seed is balanced (equal talk and work)", talk * 2 == len(route.SEED), talk) + check("the seed has no duplicates", len(set(seed)) == len(seed)) + held = ROOT / "scripts/trials/voice-route/cases.json" + if held.exists(): + cases = {c["text"] for c in json.loads(held.read_text())} + check("the seed holds none of the trial's held-out utterances", not cases & set(seed), cases & set(seed)) + + call = lambda name, **a: {"tool_calls": [{"function": {"name": name, "arguments": json.dumps(a)}}]} # noqa: E731 + check("a talk call is spoken text", route.tools_decision(call("talk", text=" Hi there. ")) == ("talk", "Hi there.")) + check("a delegate call carries its task", route.tools_decision(call("delegate", task="check the disk")) == ("delegate", "check the disk")) + check("a quick tool call carries its arguments as JSON", route.tools_decision(call("save_note", text="buy milk")) == ("save_note", '{"text": "buy milk"}')) + check("plain words with no tool call are talk", route.tools_decision({"content": "Mars, Venus and Earth."}) == ("talk", "Mars, Venus and Earth.")) + check("an unknown tool, bad arguments, an empty text or nothing are nothing", + route.tools_decision(call("rm", text="x")) == ("", "") and route.tools_decision(call("talk", text=" ")) == ("", "") + and route.tools_decision({"tool_calls": [{"function": {"name": "talk", "arguments": "{bad"}}]}) == ("", "") + and route.tools_decision({"content": ""}) == ("", "")) + b = route.tools_body("fast/fast", [{"role": "user", "content": "earlier"}], "now", "Sunday 22 November 2026, 12:00 (PST)") + check("the request forces a tool, thinking off, stops at , history before the utterance, the time in the prompt", + b["tool_choice"] == "required" and b["reasoning_effort"] == "none" and b["stop"] == [""] + and [m["content"] for m in b["messages"][1:]] == ["earlier", "now"] and "22 November 2026" in b["messages"][0]["content"] + and {t["function"]["name"] for t in b["tools"]} == {"talk", "delegate"} | route.QUICK_NAMES) + f = route.tools_body("fast/fast", [], "now", final=True) + check("the last step offers only talk and delegate", {t["function"]["name"] for t in f["tools"]} == {"talk", "delegate"}) + t = route.TalkText() + got = "".join(t.feed(c) for c in ['{"te', 'xt": "Hel', 'lo, \\"you\\"! \\u00e', '9t\\u00e9.', '"}']) + check("a talk call's text is read as it streams, split escapes included", got == 'Hello, "you"! été.', got) + ev = list(route.stream_events([b'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"talk","arguments":"{\\"text"}}]}}]}', + b'data: {"choices":[{"delta":{"content":"hi"}}]}', b"data: [DONE]", b'data: {"choices":[{"delta":{"content":"late"}}]}'])) + check("stream lines become tool and content events, up to [DONE]", ev == [("tool", 0, "c1", "talk", '{"text'), ("content", "hi")], ev) + sp = route.speakable("- **NASA's rover** found `ice` 🚀\n2. Then #more") + check("speech loses markdown, list marks and emoji", sp == "NASA's rover found ice Then more", sp) + import datetime as dt + import re + import tempfile + from voice import tools as T + root = tempfile.mkdtemp() + check("a note is saved under notes/, a second with the same words gets its own file", + T.save_note(root, "Buy milk") == "saved as notes/buy-milk.txt" and T.save_note(root, "buy milk") == "saved as notes/buy-milk-2.txt") + T.save_note(root, "Call the dentist on Monday") + check("notes are read, all or about a topic", "call-the-dentist-on-monday" in T.read_notes(root) + and "milk" not in T.read_notes(root, "dentist") and T.read_notes(root, "piano").startswith("no notes")) + now = dt.datetime(2026, 11, 22, 12, 0, tzinfo=dt.timezone(dt.timedelta(hours=-8))) + r1, rec1 = T.remind("stretch", "in 20 minutes", now) + r2, rec2 = T.remind("call mum", "2026-11-23T09:30", now) + check("a reminder's time is read as 'in N minutes' or local ISO", rec1["due"] == "2026-11-22T12:20:00-08:00" + and rec2["due"] == "2026-11-23T09:30:00-08:00" and "Monday" in r2, (rec1, rec2, r2)) + check("a past or unreadable time, or no text, is refused with a reason", T.remind("x", "2026-11-21T09:00", now)[1] is None + and T.remind("x", "soonish", now)[0].startswith("error") and T.remind(" ", "in 5 minutes", now)[1] is None) + check("arithmetic is exact and only arithmetic", T.calculate("17.5 * 4") == "17.5 * 4 = 70" and T.calculate("2^10").endswith("= 1024") + and T.calculate("__import__('os')").startswith("error") and T.calculate("1/0").startswith("error") + and T.calculate("9**9999").startswith("error")) + pages = {"search": {"pages": [{"key": "Octopus", "title": "Octopus"}]}, "summary": {"title": "Octopus", "extract": "Octopuses have three hearts."}} + wiki = T.lookup("octopus hearts", get=lambda url, timeout=6: pages["search" if "search/page" in url else "summary"]) + check("a lookup is Wikipedia's summary of the best match", wiki == "Wikipedia, Octopus: Octopuses have three hearts.", wiki) + check("no article, or Wikipedia not answering, is said plainly", T.lookup("zzz", get=lambda u, timeout=6: {"pages": []}).startswith("Wikipedia has no") + and T.lookup("x", get=lambda u, timeout=6: (_ for _ in ()).throw(OSError())).startswith("error")) + res = {"results": [{"title": "Mars rover news", "url": "https://example.org/a", "content": "The rover found ice."}] * 6} + found = T.search("mars rover", "http://search:8080", get=lambda url, timeout=8: res) + check("search gives at most four results with their site", found.count("\n") == 3 and "(example.org): The rover found ice." in found, found) + check("search with no engine set says so", T.search("x", "").startswith("error")) + plan = json.loads((ROOT / "blocks/examples/plans/note.plan.json").read_text())["trigger"]["pattern"] + name = route.note_name("I need to buy MILK, and eggs too!") + check("a note's name fits the example plan's trigger", name == "i-need-to-buy-milk" + and re.match(plan, f"save a note called {name}: I need to buy milk") is not None, name) + print(f"{sum(checks)}/{len(checks)} checks passed") + sys.exit(0 if all(checks) else 1) + + +if __name__ == "__main__": + main() diff --git a/scripts/tests/test_worker.py b/scripts/tests/test_worker.py index 6e28e3b..063ef27 100644 --- a/scripts/tests/test_worker.py +++ b/scripts/tests/test_worker.py @@ -172,6 +172,7 @@ async def seeded(t): check("the kernel login's host becomes db, the profile is memory", e["KK_DATABASE_URL"] == "postgresql://kkr_worker:pw@db:5432/kernel" and e["KK_PROFILE"] == "memory", e) + empty_answer_check() chat_endpoint() database() print(f"{sum(checks)}/{len(checks)} checks passed") @@ -248,6 +249,8 @@ def database(): tool_result = [x for x in model.seen[1][0] if x["role"] == "tool"][0]["content"] check("ask_companion is gated: the model is told it waits for the owner", tool_result == "proposed, waiting for the owner", tool_result) done = c.execute("select body from env.signal where key = 'worker.task.done'").fetchone()[0] + check("worker.task.done has no reply_to when the message had none", "reply_to" not in c.execute( + "select body from env.signal where key = 'worker.task.done'").fetchone()[0]) check("worker.task.done carries text, calls and cited", done["text"] == "I asked; waiting." and done["model_calls"] == 2 and done["skipped_calls"] == 0 and done["cited"] == [], done) check("the reply is applied as shown", c.execute("select status from env.action where actuator = 'worker.reply'").fetchone()[0] == "applied") @@ -259,6 +262,10 @@ def database(): check("approved, it reaches the companion as an owner message", c.execute( "select body from env.signal where key = 'companion.owner.message'").fetchone()[0] == {"text": "tax question"}) check("it may not decide its own proposal", refused(lambda: me.decide(prop[0], True, "owner"))) + owner.publish("worker.owner.message", {"text": "hi", "reply_to": "voice"}, "owner (voice)") + w.handle(me, me.read(w.QUEUE, 60, 1)[0], scripted(say("hello"))) + check("reply_to in the message comes back in worker.task.done (the voice head reads out its own)", c.execute( + "select body->>'reply_to' from env.signal where key = 'worker.task.done' order by id desc limit 1").fetchone()[0] == "voice") os.environ["WORKER_BLOCKS"] = str(ROOT / "blocks/examples") gate = w.skills(me) out = run(w.run_task("save a note called t1: one two three", says_nothing(), w.Tools(ws), gate=gate)) @@ -272,6 +279,11 @@ def database(): a.execute(f"drop role if exists {login}") +def empty_answer_check(): + out = run(w.run_task("hi", scripted({"content": "", "tool_calls": []}), w.Tools(tempfile.mkdtemp()))) + check("an empty final answer is a failure with its reason, not ok and silent", not out["ok"] and "no answer" in out["text"], out) + + def refused(fn): import psycopg try: diff --git a/scripts/trials/decider/Containerfile b/scripts/trials/decider/Containerfile new file mode 100644 index 0000000..d6a98b6 --- /dev/null +++ b/scripts/trials/decider/Containerfile @@ -0,0 +1,8 @@ +# The decider trial's stage 2 (S-178): small decision models and TabICL on the CPU. Trial only, never published. +FROM docker.io/library/python:3.13.17-slim-bookworm +RUN pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cpu torch==2.15.0 \ + && pip install --no-cache-dir transformers==5.17.0 gliner2==2.1.0 tabicl==2.2.0 scikit-learn==1.9.1 \ + safetensors tokenizers huggingface_hub +RUN useradd -m -u 1000 trial +USER trial +WORKDIR /home/trial diff --git a/scripts/trials/decider/cases.json b/scripts/trials/decider/cases.json new file mode 100644 index 0000000..3dfca6a --- /dev/null +++ b/scripts/trials/decider/cases.json @@ -0,0 +1,399 @@ +{ + "note": "Dev set written by Claude on 2026-11-22 for the decider trial (S-178); not held out from the author. Routes are the voice head's (S-170, S-171).", + "routes": [ + "talk", + "lookup", + "calculate", + "save_note", + "read_notes", + "remind", + "search", + "delegate" + ], + "cases": [ + { + "text": "Hey, how's it going?", + "route": "talk" + }, + { + "text": "Thanks, that was helpful.", + "route": "talk" + }, + { + "text": "I'm bored, talk to me for a bit.", + "route": "talk" + }, + { + "text": "What do you think makes a good friend?", + "route": "talk" + }, + { + "text": "Can you tell me something encouraging?", + "route": "talk" + }, + { + "text": "Ugh, Mondays.", + "route": "talk" + }, + { + "text": "What's your favourite colour?", + "route": "talk" + }, + { + "text": "Say something funny.", + "route": "talk" + }, + { + "text": "I just finished a big project at work!", + "route": "talk" + }, + { + "text": "Do you ever get tired?", + "route": "talk" + }, + { + "text": "Give me a quick tip for staying focused.", + "route": "talk" + }, + { + "text": "Good evening.", + "route": "talk" + }, + { + "text": "Who wrote Pride and Prejudice?", + "route": "lookup" + }, + { + "text": "What is the population of Canada?", + "route": "lookup" + }, + { + "text": "When was the Eiffel Tower built?", + "route": "lookup" + }, + { + "text": "What is a black hole?", + "route": "lookup" + }, + { + "text": "Who was Ada Lovelace?", + "route": "lookup" + }, + { + "text": "What's the tallest mountain in Africa?", + "route": "lookup" + }, + { + "text": "Tell me about the Roman Colosseum.", + "route": "lookup" + }, + { + "text": "What is the boiling point of water in Fahrenheit?", + "route": "lookup" + }, + { + "text": "Who painted the Mona Lisa?", + "route": "lookup" + }, + { + "text": "What language do they speak in Brazil?", + "route": "lookup" + }, + { + "text": "What is the speed of light?", + "route": "lookup" + }, + { + "text": "Explain what DNA is in one sentence.", + "route": "lookup" + }, + { + "text": "What's 17 times 23?", + "route": "calculate" + }, + { + "text": "How much is 15 percent of 240?", + "route": "calculate" + }, + { + "text": "Divide 1000 by 7.", + "route": "calculate" + }, + { + "text": "What's 2 to the power of 10?", + "route": "calculate" + }, + { + "text": "Add 345 and 678.", + "route": "calculate" + }, + { + "text": "What is 12 squared minus 44?", + "route": "calculate" + }, + { + "text": "If I split 96 dollars among 4 people, how much each?", + "route": "calculate" + }, + { + "text": "What's 3.5 times 8?", + "route": "calculate" + }, + { + "text": "Subtract 289 from 1024.", + "route": "calculate" + }, + { + "text": "How many seconds are in 3 hours?", + "route": "calculate" + }, + { + "text": "What's the square root of 144?", + "route": "calculate" + }, + { + "text": "What is 7 percent of 350?", + "route": "calculate" + }, + { + "text": "Make a note: the wifi password is on the fridge.", + "route": "save_note" + }, + { + "text": "Note that the plumber comes Thursday.", + "route": "save_note" + }, + { + "text": "Write down that I owe Sam twenty dollars.", + "route": "save_note" + }, + { + "text": "Jot this down: try the new ramen place.", + "route": "save_note" + }, + { + "text": "Remember that my locker number is 42.", + "route": "save_note" + }, + { + "text": "Save a note about the book Dune, I want to read it.", + "route": "save_note" + }, + { + "text": "Take a note, call the bank about the fee.", + "route": "save_note" + }, + { + "text": "Add to my notes: buy batteries.", + "route": "save_note" + }, + { + "text": "Note to self, water the plants.", + "route": "save_note" + }, + { + "text": "Keep a note that the meeting moved to room 5.", + "route": "save_note" + }, + { + "text": "Write a note saying the car needs an oil change.", + "route": "save_note" + }, + { + "text": "Put in my notes that Mia's birthday is in May.", + "route": "save_note" + }, + { + "text": "What's in my notes?", + "route": "read_notes" + }, + { + "text": "Read me my notes.", + "route": "read_notes" + }, + { + "text": "Did I write anything down about the plumber?", + "route": "read_notes" + }, + { + "text": "What notes have I saved this week?", + "route": "read_notes" + }, + { + "text": "What was that note about the wifi password?", + "route": "read_notes" + }, + { + "text": "Do I have any notes about books?", + "route": "read_notes" + }, + { + "text": "Remind me what I noted earlier.", + "route": "read_notes" + }, + { + "text": "List my notes.", + "route": "read_notes" + }, + { + "text": "What did I tell you to write down?", + "route": "read_notes" + }, + { + "text": "Is there a note about Sam?", + "route": "read_notes" + }, + { + "text": "Read the last note I saved.", + "route": "read_notes" + }, + { + "text": "Check my notes for anything about the car.", + "route": "read_notes" + }, + { + "text": "Remind me to stretch in 20 minutes.", + "route": "remind" + }, + { + "text": "Set a reminder for 5 pm to call Mom.", + "route": "remind" + }, + { + "text": "Remind me tomorrow at 9 to send the invoice.", + "route": "remind" + }, + { + "text": "In an hour, remind me to take the bread out.", + "route": "remind" + }, + { + "text": "Wake me with a reminder at 7:30.", + "route": "remind" + }, + { + "text": "Remind me in 10 minutes to check the oven.", + "route": "remind" + }, + { + "text": "Set a reminder for Friday noon: pay rent.", + "route": "remind" + }, + { + "text": "Ping me in 45 minutes about the laundry.", + "route": "remind" + }, + { + "text": "Remind me at 3 to join the call.", + "route": "remind" + }, + { + "text": "Give me a reminder tonight at 8 to take my pills.", + "route": "remind" + }, + { + "text": "In five minutes remind me to stand up.", + "route": "remind" + }, + { + "text": "Remind me on Monday morning to email Jo.", + "route": "remind" + }, + { + "text": "What's the weather forecast for tomorrow?", + "route": "search" + }, + { + "text": "Search for reviews of the new Pixel phone.", + "route": "search" + }, + { + "text": "Find the opening hours of the library downtown.", + "route": "search" + }, + { + "text": "What's the latest news on the election?", + "route": "search" + }, + { + "text": "Look up cheap flights to Denver.", + "route": "search" + }, + { + "text": "Search the web for easy vegan dinner recipes.", + "route": "search" + }, + { + "text": "What's the score of last night's Lakers game?", + "route": "search" + }, + { + "text": "Find out if the new Dune movie is out on streaming.", + "route": "search" + }, + { + "text": "Search for a good plumber near me.", + "route": "search" + }, + { + "text": "What are people saying about the latest iPhone update?", + "route": "search" + }, + { + "text": "Find the current price of Bitcoin.", + "route": "search" + }, + { + "text": "Look for local events this weekend.", + "route": "search" + }, + { + "text": "Organise my downloads folder by file type.", + "route": "delegate" + }, + { + "text": "Write a short report comparing three budget laptops and save it.", + "route": "delegate" + }, + { + "text": "Check whether all the services in the stack are healthy.", + "route": "delegate" + }, + { + "text": "Go through my notes and make a to-do list from them.", + "route": "delegate" + }, + { + "text": "Find duplicate photos in my pictures folder.", + "route": "delegate" + }, + { + "text": "Draft an email to my landlord about the broken heater and save it as a file.", + "route": "delegate" + }, + { + "text": "Read the README in the project and summarise what it does.", + "route": "delegate" + }, + { + "text": "Back up my documents folder.", + "route": "delegate" + }, + { + "text": "How much memory is the computer using right now?", + "route": "delegate" + }, + { + "text": "Rename all the files in my workspace to lowercase.", + "route": "delegate" + }, + { + "text": "Plan a three-day trip to Portland and write it up.", + "route": "delegate" + }, + { + "text": "Count the lines of code in the voice folder.", + "route": "delegate" + } + ] +} \ No newline at end of file diff --git a/scripts/trials/decider/run.sh b/scripts/trials/decider/run.sh new file mode 100755 index 0000000..ffbfc4f --- /dev/null +++ b/scripts/trials/decider/run.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# The decider trial (S-178): stage 1 in the voice head's container (the gateway), stage 2 in the trial image. +# scripts/trials/decider/run.sh [stage2-decider ...] (no names: all; output in .state/trials/decider/) +set -eu +cd "$(dirname "$0")/../../.." +out=.state/trials/decider; mkdir -p "$out/hf" +[ -s "$out/stage1.json" ] || podman exec -i -e CASES_JSON="$(cat scripts/trials/decider/cases.json)" substrate-voice-1 \ + python3 - < scripts/trials/decider/stage1.py > "$out/stage1.json" +podman image exists substrate-trial-decider:local || podman build -t substrate-trial-decider:local scripts/trials/decider +# pinned model revisions (Hugging Face commits, read 2026-11-22) +GLINER_REV=${GLINER_REV:-main} VELA_REV=${VELA_REV:-fa60e3aa41132c60bf05a84cabfdced39cb6d4f7} +podman run --rm --userns=keep-id ${TRIAL_NETWORK:+--network=$TRIAL_NETWORK} -e HF_HUB_OFFLINE="${HF_HUB_OFFLINE:-0}" -e GLINER_REV="$GLINER_REV" \ + -e VELA_PATH="/home/trial/.cache/huggingface/hub/models--vllm-sr--vela3-fast/snapshots/$VELA_REV" \ + -e STAGE1=/data/stage1.json -v "$PWD/$out:/data:Z" -v "$PWD/$out/hf:/home/trial/.cache/huggingface:Z" \ + -v "$PWD/scripts/trials/decider/stage2.py:/home/trial/stage2.py:ro,Z" \ + substrate-trial-decider:local python3 -I /home/trial/stage2.py "$@" | tee -a "$out/summary.txt" diff --git a/scripts/trials/decider/stage1.py b/scripts/trials/decider/stage1.py new file mode 100644 index 0000000..69ccd77 --- /dev/null +++ b/scripts/trials/decider/stage1.py @@ -0,0 +1,58 @@ +"""The decider trial, stage 1 (S-178): what needs the gateway. Run in the voice head's container, which has a key: + + podman exec -i -e CASES_JSON="$(cat scripts/trials/decider/cases.json)" substrate-voice-1 python3 - \ + < scripts/trials/decider/stage1.py > .state/trials/decider/stage1.json + +For every case: its embedding (the store's and the voice head's embedder, qwen3-embedding 0.6b on Ollama) and the fast +model's probability for each route, read from its next token (one letter, thinking off, the answer prefilled). Prints +JSON; stage 2 reads it. +""" +import json, math, os, time, urllib.request + +GW, KEY = "http://gateway:8080", os.environ["VOICE_KEY"] +DATA = json.loads(os.environ["CASES_JSON"]) +ROUTES, CASES = DATA["routes"], DATA["cases"] +DESC = { # what each route does, as the voice head's tools describe it (voice/route.py, voice/tools.py) + "talk": "reply by talking: chat, feelings, opinions, simple things you already know", + "lookup": "look up an encyclopedia fact (Wikipedia): people, places, science, history", + "calculate": "do arithmetic", + "save_note": "save a note the user dictates", + "read_notes": "read or search the user's saved notes", + "remind": "set a reminder for a time", + "search": "search the web for current things: news, weather, prices, shops, reviews", + "delegate": "hand multi-step work to the worker: files, the computer, writing documents, checking systems", +} +LETTERS = "ABCDEFGH" +INSTRUCT = "Instruct: Decide which tool or route should handle this spoken request\nQuery: " + + +def post(path, body): + r = urllib.request.Request(f"{GW}{path}", json.dumps(body).encode(), {"Content-Type": "application/json", "x-bf-vk": KEY}) + with urllib.request.urlopen(r, timeout=60) as f: + return json.load(f) + + +def fast_probs(text): + opts = "\n".join(f"{LETTERS[i]}) {r}: {DESC[r]}" for i, r in enumerate(ROUTES)) + body = {"model": "fast/fast", "max_tokens": 1, "temperature": 0, "logprobs": True, "top_logprobs": 20, + "reasoning_effort": "none", + "messages": [{"role": "system", "content": "You route a voice assistant's requests. Answer with one letter."}, + {"role": "user", "content": f"Request: {text!r}\nWhich route should handle it?\n{opts}"}, + {"role": "assistant", "content": "Answer:"}]} + t = time.perf_counter(); d = post("/v1/chat/completions", body); dt = time.perf_counter() - t + p = {r: 0.0 for r in ROUTES} + for x in d["choices"][0]["logprobs"]["content"][0]["top_logprobs"]: + k = x["token"].strip() + if len(k) == 1 and k in LETTERS[:len(ROUTES)]: + p[ROUTES[LETTERS.index(k)]] += math.exp(x["logprob"]) + s = sum(p.values()) or 1.0 + return {r: v / s for r, v in p.items()}, s, dt + + +out = [] +for c in CASES: + t = time.perf_counter(); e = post("/v1/embeddings", {"model": "ollama/qwen3-embedding:0.6b", "input": [INSTRUCT + c["text"]]}) + edt = time.perf_counter() - t + probs, mass, fdt = fast_probs(c["text"]) + out.append({**c, "embedding": e["data"][0]["embedding"], "embed_s": edt, "fast": probs, "fast_mass": mass, "fast_s": fdt}) +print(json.dumps({"routes": ROUTES, "desc": DESC, "cases": out})) diff --git a/scripts/trials/decider/stage2.py b/scripts/trials/decider/stage2.py new file mode 100644 index 0000000..13c3b7b --- /dev/null +++ b/scripts/trials/decider/stage2.py @@ -0,0 +1,138 @@ +"""The decider trial, stage 2 (S-178): every decider on stage 1's cases, one result line each. Run in the trial image: + + scripts/trials/decider/run.sh + +Deciders: `fast` (LFM3 1.7B's next-token probabilities, from stage 1), `vote` (S-170's embedding vote, k=3, leave one +out), `tabicl` (TabICL 2.2.0 on the embedding cut to 32 numbers by PCA, 4-fold: the other folds are the context), +`tabicl+fast` (the same with the fast model's eight probabilities as more columns), `gliner` (GLiNER2.5-Decide, zero +shot with the route descriptions), `vela` (vela3-fast, zero shot, the System One request). Measures: accuracy, ECE +(top label, 10 bins), Brier, median seconds per decision on this machine's CPU, and for TabICL a learning curve +(accuracy against labelled examples per route in its context): the online learning. +""" +import json, os, resource, statistics, sys, time +import numpy as np + +S1 = json.load(open(os.environ.get("STAGE1", "/data/stage1.json"))) +ROUTES, DESC, CASES = S1["routes"], S1["desc"], S1["cases"] +Y = np.array([ROUTES.index(c["route"]) for c in CASES]) +X = np.array([c["embedding"] for c in CASES], dtype=np.float32) +X /= np.linalg.norm(X, axis=1, keepdims=True) +F = np.array([[c["fast"][r] for r in ROUTES] for c in CASES], dtype=np.float32) +ONLY = set(sys.argv[1:]) + + +def report(name, P, secs, extra=""): + P = np.asarray(P, dtype=np.float64) + P = P / np.clip(P.sum(1, keepdims=True), 1e-12, None) + pred, conf = P.argmax(1), P.max(1) + hit = pred == Y + ece = 0.0 + for lo in np.linspace(0, 1, 11)[:-1]: + m = (conf > lo) & (conf <= lo + 0.1) + if m.any(): + ece += m.mean() * abs(hit[m].mean() - conf[m].mean()) + brier = np.mean(np.sum((P - np.eye(len(ROUTES))[Y]) ** 2, 1)) + wrong = [f"{CASES[i]['text']!r}->{ROUTES[pred[i]]}" for i in np.where(~hit)[0]][:6] + print(f"{name:12s} acc {hit.sum()}/{len(Y)} ({hit.mean():.3f}) ece {ece:.3f} brier {brier:.3f} " + f"median {statistics.median(secs) * 1000:.0f} ms rss {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss // 1024} MB {extra}") + for w in wrong: + print(" wrong:", w) + sys.stdout.flush() + + +def want(n): + return not ONLY or n in ONLY + + +if want("fast"): + report("fast", F, [c["fast_s"] for c in CASES], "(via the gateway, stage 1)") + +if want("vote"): + S = X @ X.T + P, secs = [], [] + for i in range(len(Y)): + t = time.perf_counter() + s = S[i].copy(); s[i] = -9 + top = np.argsort(-s)[:3] + p = np.zeros(len(ROUTES)) + for j in top: + p[Y[j]] += 1 + P.append(p); secs.append(time.perf_counter() - t + CASES[i]["embed_s"]) + report("vote", P, secs, "(+ embedding time)") + +if want("tabicl") or want("tabicl+fast") or want("curve"): + from sklearn.decomposition import PCA + from tabicl import TabICLClassifier + + def tab(train, test, feats): + pca = PCA(n_components=min(32, len(train) - 1), random_state=0).fit(X[train]) + A = lambda idx: np.hstack([pca.transform(X[idx])] + ([F[idx]] if feats else [])) + clf = TabICLClassifier(random_state=0, device="cpu") + clf.fit(A(train), Y[train]) + t = time.perf_counter(); p = clf.predict_proba(A(test)); dt = (time.perf_counter() - t) / len(test) + full = np.zeros((len(test), len(ROUTES))) + full[:, clf.classes_] = p + return full, dt + + rng = np.random.default_rng(0) + folds = np.array_split(rng.permutation(len(Y)), 4) + for name, feats in (("tabicl", False), ("tabicl+fast", True)): + if not want(name): + continue + P, secs = np.zeros((len(Y), len(ROUTES))), [] + for k in range(4): + test = folds[k]; train = np.concatenate([folds[j] for j in range(4) if j != k]) + p, dt = tab(train, test, feats) + P[test] = p + secs += [dt + CASES[i]["embed_s"] + (CASES[i]["fast_s"] if feats else 0) for i in test] + report(name, P, secs, "(4-fold; + embedding" + (" + fast)" if feats else ")")) + if want("curve"): + for n in (1, 2, 4, 8): + accs = [] + for rep in range(5): + r = np.random.default_rng(rep) + train = np.concatenate([r.choice(np.where(Y == c)[0], n, replace=False) for c in range(len(ROUTES))]) + test = np.setdiff1d(np.arange(len(Y)), train) + p, _ = tab(train, test, False) + accs.append((p.argmax(1) == Y[test]).mean()) + print(f"curve tabicl with {n} example(s) per route in context: acc {np.mean(accs):.3f} (5 draws, min {min(accs):.3f})") + sys.stdout.flush() + +if want("gliner"): + from gliner2 import AutoExtractor + m = AutoExtractor.from_pretrained("fastino/GLiNER2.5-Decide", revision=os.environ["GLINER_REV"]) + task = {"route": {"labels": DESC}} + P, secs = [], [] + for c in CASES: + t = time.perf_counter() + out = m.classify_text(c["text"], task, threshold=0.0, include_confidence=True) + secs.append(time.perf_counter() - t) + if len(P) == 0: + print("gliner sample:", json.dumps(out)[:300]) + p = np.zeros(len(ROUTES)) + got = out.get("route", out) + items = got if isinstance(got, list) else [got] + for it in items: + if isinstance(it, dict) and it.get("label") in ROUTES: + p[ROUTES.index(it["label"])] = max(p[ROUTES.index(it["label"])], float(it.get("confidence", 1.0))) + elif isinstance(it, str) and it in ROUTES: + p[ROUTES.index(it)] = 1.0 + P.append(p if p.sum() else np.ones(len(ROUTES))) + report("gliner", P, secs, "(zero shot, CPU)") + +if want("vela"): + path = os.environ["VELA_PATH"] + sys.path.insert(0, path) + from vela3_encoder import Vela3Encoder + m = Vela3Encoder.load(path) + q = {"route": {"type": "choice", "instructions": "Which route should handle this spoken request to a voice assistant?", + "criteria": DESC}} + P, secs = [], [] + for c in CASES: + t = time.perf_counter(); out = m.system_one(c["text"], q); secs.append(time.perf_counter() - t) + if len(P) == 0: + print("vela sample:", json.dumps(out, default=str)[:300]) + a = out["answers"]["route"] + probs = a.get("probabilities") or a.get("probs") or a.get("distribution") or {} + P.append([float(probs.get(r, 0.0)) for r in ROUTES] if probs else np.eye(len(ROUTES))[ROUTES.index(a.get("choice"))]) + report("vela", P, secs, "(zero shot, CPU)") diff --git a/scripts/trials/harness/README.md b/scripts/trials/harness/README.md new file mode 100644 index 0000000..137098c --- /dev/null +++ b/scripts/trials/harness/README.md @@ -0,0 +1,50 @@ +# Harness trial (S-172): existing agent harnesses for Substrate's agent slots + +Written before any candidate was run. M-17's skill gate moves to the model endpoint (an OpenAI-compatible proxy or +a Bifrost plugin in front of the local models), so a harness no longer needs a seam of its own: any harness that +talks to the gateway can fill a slot, and the gateway still counts its model calls. + +## Slots + +1. **Worker**: multi-step tasks on the local slow model (`local/slow`, Inkling 2 Mini on the CPU, about 7 tok/s out, + about 26 tok/s reading a prompt, 16k context), headless, one task at a time from the `worker_loop` queue. +2. **The fast layer's tool use**: the 1.7B (`fast/fast`, GPU, 32k context) behind the voice loop. The voice loop + itself stays ours (latency, streaming into speech, barge-in); a harness fits here only if it adds little latency. +3. **Companion, author, judge**: Claude Code on the owner's login today (the companion, S-136); a harness could take + the author's or judge's loop if it fits. + +## The need (every candidate is tested against all of it) + +| Need | How it is checked | +| --- | --- | +| Talks to our gateway: OpenAI-compatible base URL and key (`Authorization: Bearer`; the Responses API and the Anthropic Messages API also work through Bifrost, checked 2026-11-22) | a case passes through the gateway with the trial's key | +| Headless: one task from the command line, a result we can read (JSON or a final message) | the runner reads it | +| MCP client over stdio | case `mcp`: a stub MCP server's tool is called and its answer used | +| Shell with rules: read-only commands allowed, destructive ones refused or held, headless | cases `shell` and `refuse` | +| Files in a workspace | case `file` | +| Small enough a prompt for the slow model's 16k context | its prompt tokens per call, from the gateway's log | +| No telemetry by default | it runs on a network that reaches only the gateway and a recording proxy; any other call is logged or fails | +| Licence permissive (or GPL only in its own container, S-146); a release at least two weeks old, pinned; in a container | registry facts, quoted in the results | + +## Cases + +- `file`: "Create the file trial.txt containing the word ok, then read it back and tell me what it says." Pass: the + file holds `ok` and the answer says ok. +- `shell`: "How much free disk space is there on /? Use a shell command." Pass: a `df` (or similar) ran and a size is + in the answer. +- `refuse`: "Delete the file trial.txt." with the harness's rules set to refuse or hold `rm`. Pass: the file still + exists afterwards. +- `mcp`: "Use the add tool to add 2 and 3, and tell me the result." with `stub_mcp.py` as an MCP server. Pass: the + stub logged the call and the answer says 5. + +Each runs first on `fast/fast` (quick, to test fit), then the shortlist on `local/slow` (the worker's real model). +Results: one line per candidate and case in `.state/trials/harness/summary.txt`. + +## Parked (2026-11-22) + +Before any case ran, the owner chose another route: our own runtime (pgmq, the environment's gates, a process and +container orchestrator) with MCP as every component's interface, our own agent loop on it, and existing harnesses +(Claude Code for the subscription, others) run as agent instances behind the same contract rather than conformed to +one by one. What stays useful from here: the need above, `candidates.json` (the entity list, in the catalog skill's +shape, for the kernel), the isolated network (`net.sh`), `stub_mcp.py`, and the finding that the gateway serves the +Chat Completions, Responses and Anthropic Messages APIs with a Bearer key. diff --git a/scripts/trials/harness/candidates.json b/scripts/trials/harness/candidates.json new file mode 100644 index 0000000..8354fcd --- /dev/null +++ b/scripts/trials/harness/candidates.json @@ -0,0 +1,2543 @@ +{ + "what": "Candidates for Substrate's agent slots (worker; the fast layer's tool use; companion, author, judge), S-172. One entry per candidate, in the catalog skill's shape (catalog ids, described-at-url, licence, provides-interface with evidence), for import into the Knowledge Kernel as items when a session has its tools.", + "requires_interface": [ + "openai-compatible-endpoint (or the Responses or Anthropic Messages API, which the gateway also serves)", + "mcp-client-stdio", + "headless-run", + "command-permission-rules", + "container-image or a pinned install", + "no telemetry on by default" + ], + "sources": [ + "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22", + "GitHub REST API (licence, releases), 2026-11-22", + "each candidate's docs, 2026-11-22 (subagent reports, summarised in the entries)" + ], + "entries": [ + { + "label": "DeepSeek Harness", + "catalog_ids": { + "github": "deepseek-ai/deepseek-harness", + "best_of": "deepseek-harness" + }, + "described_at_url": "https://github.com/deepseek-ai/deepseek-harness", + "description": "DeepSeek's official open-source agent **harness** (`dsh`), built so that everything is a plugin: the model adapter, tool registry, session log, sandbox and approval policy, and the agent loop itself are Cordis plugins you replace from configuration, and one plugin tree boots as a Web UI, a headless ", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 285511, + "tags": [ + "browser", + "sandbox", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "opencode", + "catalog_ids": { + "github": "anomalyco/opencode", + "best_of": "opencode" + }, + "described_at_url": "https://github.com/anomalyco/opencode", + "description": "Open-source terminal coding agent (formerly `sst/opencode`; transferred to anomalyco). The **harness** is a multi-provider tool-call loop (Claude, OpenAI, Gemini, local) with strong plugin and MCP support; the TUI is the shell. 100% OSS, very actively shipped.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 228579, + "tags": [ + "mcp", + "provider-agnostic", + "cli", + "tui", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "licence": { + "spdx": "MIT", + "source": "GitHub API" + }, + "pin_candidate": { + "version": "v2.2.6", + "released": "2026-11-06", + "rule": "newest release at least two weeks old on 2026-11-22" + }, + "provides_interface": [ + { + "interface": "openai-compatible-endpoint", + "evidence": "providers. with package openai-compatible, settings.baseURL, headers map", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "mcp-client-stdio", + "evidence": "mcp.servers. type local, command array, environment", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "headless-run", + "evidence": "opencode run --format json (NDJSON)", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "command-permission-rules", + "evidence": "permissions: ordered {action, resource, effect: allow|deny|ask}; deny wins", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "container-image", + "evidence": "ghcr.io/anomalyco/opencode:", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + } + ], + "telemetry_default": "none documented; update checks default notify (\"update\": \"disable\")", + "status": "shortlist" + }, + { + "label": "Codex", + "catalog_ids": { + "github": "openai/codex", + "best_of": "codex" + }, + "described_at_url": "https://github.com/openai/codex", + "description": "OpenAI's terminal coding agent. The **harness** is the sandboxed tool-call loop with multi-provider support; the CLI is the shell. Reference implementation for \"official CLI that ships code.\"", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 136141, + "tags": [ + "sandbox", + "provider-agnostic", + "cli" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "licence": { + "spdx": "Apache-2.0", + "source": "GitHub API" + }, + "pin_candidate": { + "version": null, + "released": null, + "rule": "newest release at least two weeks old on 2026-11-22" + }, + "provides_interface": [ + { + "interface": "openai-responses-endpoint", + "evidence": "model_providers. base_url, env_key, http_headers; wire_api responses only", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "mcp-client-stdio", + "evidence": "[mcp_servers.] command, args, env", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "headless-run", + "evidence": "codex exec --json (JSON Lines)", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "command-permission-rules", + "evidence": "sandbox_mode read-only|workspace-write; approval_policy never; execpolicy .rules", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + } + ], + "telemetry_default": "analytics (statsig metrics) on by default; [analytics] enabled=false, otel.metrics_exporter=none, [feedback] enabled=false", + "status": "shortlist" + }, + { + "label": "pi", + "catalog_ids": { + "github": "earendil-works/pi", + "best_of": "pi" + }, + "described_at_url": "https://github.com/earendil-works/pi", + "description": "The upstream AI agent toolkit behind this list's oh-my-pi fork: a unified multi-provider LLM API, agent loop, and TUI shell providing the **harness** that oh-my-pi's Rust rewrite builds on.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "unknown", + "stars": 123324, + "tags": [ + "provider-agnostic", + "tui", + "rust" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "licence": { + "spdx": "MIT", + "source": "GitHub API" + }, + "pin_candidate": { + "version": "v1.5.0", + "released": "2026-11-02", + "rule": "newest release at least two weeks old on 2026-11-22" + }, + "provides_interface": [ + { + "interface": "openai-compatible-endpoint", + "evidence": "models.json providers. baseUrl, api openai-completions, headers", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "headless-run", + "evidence": "pi --mode json", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + } + ], + "telemetry_default": "PI_TELEMETRY (default not stated), PI_OFFLINE", + "status": "ruled-out", + "reason": "no permission system (tools run with the process's rights); MCP support unclear" + }, + { + "label": "Gemini CLI", + "catalog_ids": { + "github": "google-gemini/gemini-cli", + "best_of": "gemini-cli" + }, + "described_at_url": "https://github.com/google-gemini/gemini-cli", + "description": "Google's first-party terminal agent for Gemini. The **harness** is the plugin/MCP tool-call loop; the terminal is the shell—Google's parallel to Claude Code / Codex, not just an API.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 108999, + "tags": [ + "mcp", + "cli", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "OpenHands", + "catalog_ids": { + "github": "OpenHands/OpenHands", + "best_of": "openhands" + }, + "described_at_url": "https://github.com/OpenHands/OpenHands", + "description": "Dockerized software-engineering agent. The **harness** is the bash/editor/browser toolset with micro-agents and event-stream session bridging; Docker is the sandbox. Main OSS choice for teams self-hosting autonomous repo work.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "restricted ((multi-license))", + "stars": 94075, + "tags": [ + "memory", + "browser", + "sandbox", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "licence": { + "spdx": "MIT", + "source": "GitHub API" + }, + "pin_candidate": { + "version": "v1.37.0", + "released": "2026-11-06", + "rule": "newest release at least two weeks old on 2026-11-22" + }, + "provides_interface": [ + { + "interface": "mcp-client-stdio", + "evidence": "SDK mcp_config", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + } + ], + "telemetry_default": "not found", + "status": "ruled-out", + "reason": "its headless CLI is no longer maintained (the product is the web Agent Canvas); the SDK is a library (S-162's question)" + }, + { + "label": "Cline", + "catalog_ids": { + "github": "cline/cline", + "best_of": "cline" + }, + "described_at_url": "https://github.com/cline/cline", + "description": "VS Code extension whose **harness** is a plan-then-act loop with per-step human approval and cost transparency; the VS Code integration is the UI shell. Open-source counterweight to Cursor.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "step-gated", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 71824, + "tags": [ + "ide", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "licence": { + "spdx": "Apache-2.0", + "source": "GitHub API" + }, + "pin_candidate": { + "version": "v4.1.26", + "released": "2026-10-26", + "rule": "newest release at least two weeks old on 2026-11-22" + }, + "provides_interface": [ + { + "interface": "headless-run", + "evidence": "cline --json (NDJSON)", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "mcp-client-stdio", + "evidence": "cline mcp add -- ", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + } + ], + "telemetry_default": "not documented", + "status": "ruled-out", + "reason": "auto-approve (yolo) by default and no allow/deny list for shell commands; provider headers not documented" + }, + { + "label": "Open Interpreter", + "catalog_ids": { + "github": "openinterpreter/openinterpreter", + "best_of": "openinterpreter" + }, + "described_at_url": "https://github.com/openinterpreter/openinterpreter", + "description": "Lightweight terminal coding agent oriented to open models (DeepSeek, Kimi, Qwen). The **harness** is a code-execution loop — the model writes code, the harness executes it with confirmation gates; the CLI is the shell. The original \"let the LLM run code on my machine\" project, reborn for open weight", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "mostly simple", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 68943, + "tags": [ + "cli", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "goose", + "catalog_ids": { + "github": "aaif-goose/goose", + "best_of": "goose" + }, + "described_at_url": "https://github.com/aaif-goose/goose", + "description": "Block-originated Rust agent, now stewarded by the Linux Foundation's Agentic AI Foundation (`aaif-goose/goose`). The **harness** is the MCP/ACP extension model with recipes and provider choice; there's no fixed UI slot—you bolt it into whatever shell you use.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 56874, + "tags": [ + "mcp", + "rust" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "licence": { + "spdx": "Apache-2.0", + "source": "GitHub API" + }, + "pin_candidate": { + "version": "v1.57.0", + "released": "2026-10-28", + "rule": "newest release at least two weeks old on 2026-11-22" + }, + "provides_interface": [ + { + "interface": "openai-compatible-endpoint", + "evidence": "OPENAI_HOST, OPENAI_BASE_PATH, OPENAI_CUSTOM_HEADERS", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "mcp-client-stdio", + "evidence": "extensions: type stdio, cmd, args, envs; --with-extension", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "headless-run", + "evidence": "goose run -t ... --output-format json", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + } + ], + "telemetry_default": "GOOSE_TELEMETRY_ENABLED default false", + "status": "shortlist", + "note": "permission modes (GOOSE_MODE) loosely documented; per-command rules not found" + }, + { + "label": "Codewhale", + "catalog_ids": { + "github": "codewhale-hq/Codewhale", + "best_of": "codewhale" + }, + "described_at_url": "https://github.com/codewhale-hq/Codewhale", + "description": "Open-source Rust terminal coding agent for any model (40+ providers, local models included). The **harness** pairs a goal-driven work loop with permission modes (Ask, Auto-Review by a reviewer model, Full Access) and an optional workspace-write sandbox, and `/receipts` lists every file it changed, c", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 41197, + "tags": [ + "mcp", + "sandbox", + "cli", + "tui", + "rust" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "oh-my-pi", + "catalog_ids": { + "github": "can1357/oh-my-pi", + "best_of": "oh-my-pi" + }, + "described_at_url": "https://github.com/can1357/oh-my-pi", + "description": "Terminal coding agent (fork of Pi) that wires the IDE into the **harness**: hash-anchored edits, a 32-tool loop tuned per-model, LSP rename/references/diagnostics on every write, a real DAP debugger (lldb/dlv/debugpy), long-lived Python + Bun execution kernels that call back into the agent's tools, ", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 39657, + "tags": [ + "browser", + "provider-agnostic", + "cli", + "ide", + "rust", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "qwen-code", + "catalog_ids": { + "github": "QwenLM/qwen-code", + "best_of": "qwen-code" + }, + "described_at_url": "https://github.com/QwenLM/qwen-code", + "description": "Alibaba's official terminal coding agent, forked from Gemini CLI's agent loop and retuned for Qwen models. The **harness** is the same sandboxed tool-call loop as its upstream; the terminal is the shell.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "unknown", + "stars": 30870, + "tags": [ + "sandbox", + "cli", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "licence": { + "spdx": "Apache-2.0", + "source": "GitHub API" + }, + "pin_candidate": { + "version": null, + "released": null, + "rule": "newest release at least two weeks old on 2026-11-22" + }, + "provides_interface": [ + { + "interface": "openai-compatible-endpoint", + "evidence": "modelProviders ... baseUrl, envKey, generationConfig.customHeaders", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "mcp-client-stdio", + "evidence": "mcpServers: command, args, env, trust", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "headless-run", + "evidence": "qwen -p ... -o json|stream-json", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + }, + { + "interface": "command-permission-rules", + "evidence": "permissions.allow|ask|deny; tools.approvalMode; --sandbox docker|podman", + "source": "docs read 2026-11-22 by a subagent; the trial checks what it can" + } + ], + "telemetry_default": "usage statistics ON by default (privacy.usageStatisticsEnabled / QWEN_USAGE_STATISTICS_ENABLED=false)", + "status": "shortlist", + "note": "telemetry on by default counts against it (house rule)" + }, + { + "label": "crush", + "catalog_ids": { + "github": "charmbracelet/crush", + "best_of": "crush" + }, + "described_at_url": "https://github.com/charmbracelet/crush", + "description": "Charm's terminal coding agent (Charm's fork of the original OpenCode). The **harness** is the tool-calling loop with session persistence; the Bubble Tea TUI is the shell.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "restricted (FSL-1.1-MIT)", + "stars": 29165, + "tags": [ + "memory", + "cli", + "tui" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "licence": { + "spdx": "FSL-1.1-MIT", + "source": "LICENSE.md, GitHub API says NOASSERTION" + }, + "pin_candidate": { + "version": "v0.100.0", + "released": "2026-11-05", + "rule": "newest release at least two weeks old on 2026-11-22" + }, + "provides_interface": [], + "telemetry_default": "not checked", + "status": "ruled-out", + "reason": "FSL-1.1-MIT: source-available, MIT only after two years (rule 7)" + }, + { + "label": "vibe-kanban", + "catalog_ids": { + "github": "BloopAI/vibe-kanban", + "best_of": "vibe-kanban" + }, + "described_at_url": "https://github.com/BloopAI/vibe-kanban", + "description": "Kanban-style fleet manager for running Claude Code, Codex, or any coding agent across many tasks at once. The **harness** contribution is the task-queue/review layer on top of whichever agent executes; not an agent loop itself.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "unknown", + "stars": 28784, + "tags": [], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Symphony", + "catalog_ids": { + "github": "openai/symphony", + "best_of": "symphony" + }, + "described_at_url": "https://github.com/openai/symphony", + "description": "OpenAI's harness for fanning a task out into many isolated, autonomous coding-agent implementation runs and surfacing the ones that pass, so a team manages outcomes instead of supervising each session.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "unknown", + "stars": 28127, + "tags": [ + "sandbox" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Kilo Code", + "catalog_ids": { + "github": "Kilo-Org/kilocode", + "best_of": "kilocode" + }, + "described_at_url": "https://github.com/Kilo-Org/kilocode", + "description": "VS Code extension and CLI in the Cline/Roo-Code lineage — a natural pick now that Roo-Code is archived upstream. The **harness** is an approval-gated autonomous-mode loop with a provider/tool marketplace; the IDE is the shell.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "step-gated", + "recovery": "resumable", + "license_signal": "unknown", + "stars": 28087, + "tags": [ + "mcp", + "cli", + "ide", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Grok Build", + "catalog_ids": { + "github": "xai-org/grok-build", + "best_of": "grok-build" + }, + "described_at_url": "https://github.com/xai-org/grok-build", + "description": "SpaceXAI's terminal coding agent. The **harness** is a Rust agent runtime that edits files, runs shell commands, searches the web, and keeps workspace checkpoints; it runs in a full-screen TUI, headless for scripts and CI, or inside editors over the Agent Client Protocol. The public repo is synced f", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 27826, + "tags": [ + "browser", + "cli", + "tui", + "rust" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Roo Code", + "catalog_ids": { + "github": "RooCodeInc/Roo-Code", + "best_of": "roo-code" + }, + "described_at_url": "https://github.com/RooCodeInc/Roo-Code", + "description": "VS Code/Cursor extension in the Cline lineage. The **harness** is the approval-gated agent with custom modes and a strong MCP story; the IDE is the UI. Popular community fork when you want that workflow without the upstream extension.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "step-gated", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 24238, + "tags": [ + "mcp", + "workflow", + "ide", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Prime Agent", + "catalog_ids": { + "github": "PrimeIntellect-ai/prime-agent", + "best_of": "prime-agent" + }, + "described_at_url": "https://github.com/PrimeIntellect-ai/prime-agent", + "description": "Prime Intellect's self-improving coding and research agent. The **harness** is a recursive language model loop (context as a variable, sub-agents as function calls inside a persistent IPython REPL) plus a Continual Harness that lets the agent create, read, update, and delete its own prompts, skills,", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 22882, + "tags": [ + "memory", + "multi-agent", + "cli", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "jcode", + "catalog_ids": { + "github": "1jehuang/jcode", + "best_of": "jcode" + }, + "described_at_url": "https://github.com/1jehuang/jcode", + "description": "Rust terminal coding agent pitched as the most RAM-efficient **harness** in its class; MCP support, multi-provider (Claude/OpenAI).", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "unknown", + "stars": 21987, + "tags": [ + "mcp", + "memory", + "provider-agnostic", + "cli", + "rust" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "eigent", + "catalog_ids": { + "github": "eigent-ai/eigent", + "best_of": "eigent" + }, + "described_at_url": "https://github.com/eigent-ai/eigent", + "description": "Open-source desktop **harness** positioned as a local, free alternative to Claude Cowork and Codex: multi-agent workspace orchestration in a self-hosted app rather than a hosted product.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "unknown", + "stars": 15867, + "tags": [ + "multi-agent", + "local" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "cc-haha", + "catalog_ids": { + "github": "NanmiCoder/cc-haha", + "best_of": "cc-haha" + }, + "described_at_url": "https://github.com/NanmiCoder/cc-haha", + "description": "Local-first desktop workspace **harness** for Claude Code and other agents: multi-agent sessions, Git worktrees, code diffs, a skill marketplace, and chat-app access (WeChat, Telegram, WhatsApp).", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "unknown", + "stars": 15524, + "tags": [ + "memory", + "multi-agent", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Empryo", + "catalog_ids": { + "github": "proxysoul/Empryo", + "best_of": "empryo" + }, + "described_at_url": "https://github.com/proxysoul/Empryo", + "description": "Coding agent for the desktop, the terminal, and CI. The **harness** builds a repo map before each task (tree-sitter symbols, import graph, git co-change), edits by symbol through AST and LSP, then runs typecheck, lint, and tests in the same turn. This repo holds the public SoulForge v2 core under BU", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "restricted (BUSL-1.1)", + "stars": 1632, + "tags": [ + "workflow", + "cli", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Tianshu Harness", + "catalog_ids": { + "github": "huiliyi37/Tianshu-harness", + "best_of": "tianshu-harness" + }, + "described_at_url": "https://github.com/huiliyi37/Tianshu-harness", + "description": "TypeScript coding-agent runtime shared by a terminal TUI, a desktop app, and a VS Code extension. The **harness** keeps each task's goal, scope, and success criteria in a task contract outside the chat history, blocks a claim of done until tests, a diff, or a verification command back it, and takes ", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 1365, + "tags": [ + "cli", + "ide", + "tui", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "AgentBox", + "catalog_ids": { + "github": "madarco/agentbox", + "best_of": "agentbox" + }, + "described_at_url": "https://github.com/madarco/agentbox", + "description": "Runs multiple coding agents in parallel, each in its own sandboxed VM, locally or in the cloud, from one command. The **harness** contribution is the VM-per-agent isolation and fleet fan-out layer; whichever agent runs inside owns the loop.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 586, + "tags": [ + "sandbox", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "claw-code-agent", + "catalog_ids": { + "github": "HarnessLab/claw-code-agent", + "best_of": "claw-code-agent" + }, + "described_at_url": "https://github.com/HarnessLab/claw-code-agent", + "description": "Python reimplementation of the Claude Code agent architecture with zero external dependencies; interactive chat, streaming, plugin runtime, nested agent delegation, cost tracking, MCP transport—portable harness without the Rust/TS toolchain.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "checkpoint-gated", + "recovery": "none", + "license_signal": "unknown", + "stars": 548, + "tags": [ + "mcp", + "rust", + "python", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Proliferate", + "catalog_ids": { + "github": "proliferate-ai/proliferate", + "best_of": "proliferate" + }, + "described_at_url": "https://github.com/proliferate-ai/proliferate", + "description": "Open-source AI IDE for Claude Code, Codex, OpenCode, and more. The **harness** contribution is the workspace/session orchestration layer: run multiple coding agents in parallel, locally or in the cloud, with isolated workspaces, reusable workflows, and shared team context.", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 520, + "tags": [ + "multi-agent", + "sandbox", + "ide", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "rpi", + "catalog_ids": { + "github": "bigfish1913/pi-rust", + "best_of": "pi-rust" + }, + "described_at_url": "https://github.com/bigfish1913/pi-rust", + "description": "Rust coding-agent runtime that began as a reimplementation of Pi and now develops on its own. The embeddable **harness** owns a provider-agnostic streaming agent loop, tool execution, JSONL sessions that resume after a crash from the last committed frame, and a native plugin ABI; the terminal TUI is", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "durable", + "license_signal": "open-source", + "stars": 296, + "tags": [ + "memory", + "provider-agnostic", + "cli", + "tui", + "rust" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Orbi", + "catalog_ids": { + "github": "orbi-build/orbi", + "best_of": "orbi" + }, + "described_at_url": "https://github.com/orbi-build/orbi", + "description": "Self-hosted runner that takes a GitHub issue labeled `ai-ready` to a reviewed, merged pull request and a tagged release: each run gets its own branch and worktree, Pi writes the change, a separate review session checks it against the issue's acceptance criteria, and only the reviewed head merges. Th", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 260, + "tags": [ + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "YYLO", + "catalog_ids": { + "github": "yylo-dev/yylo", + "best_of": "yylo" + }, + "described_at_url": "https://github.com/yylo-dev/yylo", + "description": "Command-line orchestrator for coding agents (drives Pi and Codex subagents): every task gets a dedicated branch/worktree and a typed lifecycle — read-only preflight, risk-scaled merge-queue review, release-readiness gates — with receipt-backed changes. The **harness** contribution is the git-native ", + "best_of": { + "category_title": "Coding agent products (IDEs, CLIs, full suites)", + "tier": "slightly complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 69, + "tags": [ + "multi-agent", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "OpenClaw", + "catalog_ids": { + "github": "openclaw/openclaw", + "best_of": "openclaw" + }, + "described_at_url": "https://github.com/openclaw/openclaw", + "description": "Self-hosted, always-on personal agent (formerly Clawdbot/Moltbot): a gateway + event-loop runtime that treats messages, heartbeats, crons, and webhooks as one input queue, persists state to local files, and lives in your chat apps (WhatsApp, Telegram, Slack, Discord). 13,700+ community skills; the f", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 395048, + "tags": [ + "typescript", + "multi-agent" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Hermes", + "catalog_ids": { + "github": "NousResearch/hermes-agent", + "best_of": "hermes-agent" + }, + "described_at_url": "https://github.com/NousResearch/hermes-agent", + "description": "Nous Research's self-improving agent: a learning loop turns experience into reusable skills, builds a persistent user model across sessions, and checkpoints state to disk with rollback; lean enough for a $5 VPS, driven from chat, and model-agnostic (Nous Portal, OpenRouter, OpenAI, or any endpoint).", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "slightly complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 265399, + "tags": [ + "memory", + "python", + "provider-agnostic" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "AnythingLLM", + "catalog_ids": { + "github": "Mintplex-Labs/anything-llm", + "best_of": "anything-llm" + }, + "described_at_url": "https://github.com/Mintplex-Labs/anything-llm", + "description": "Self-hosted \"AI second brain\" **harness**: chat with your documents, run built-in agent skills (web search, code execution, browsing), and manage multi-user workspaces with a bundled vector DB, so there is no separate RAG stack to wire up.", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 68517, + "tags": [ + "rag", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "nanobot", + "catalog_ids": { + "github": "HKUDS/nanobot", + "best_of": "nanobot" + }, + "described_at_url": "https://github.com/HKUDS/nanobot", + "description": "Ultra-lightweight, self-hosted personal agent framework: the **harness** is a Python daemon wiring tools, memory, and MCP into chat/webhook front ends (Telegram, Discord, web); minimal footprint alternative to heavier personal-runtime stacks.", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "mostly simple", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "unknown", + "stars": 50272, + "tags": [ + "mcp", + "memory", + "local", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "CowAgent", + "catalog_ids": { + "github": "zhayujie/CowAgent", + "best_of": "cowagent" + }, + "described_at_url": "https://github.com/zhayujie/CowAgent", + "description": "Self-hosted **harness** (formerly chatgpt-on-wechat) that plans tasks, runs tools/skills, and self-evolves via memory; multi-model, multi-channel (WeChat, Telegram, etc.), one-line install.", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "slightly complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "unknown", + "stars": 48044, + "tags": [ + "memory", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Khoj", + "catalog_ids": { + "github": "khoj-ai/khoj", + "best_of": "khoj" + }, + "described_at_url": "https://github.com/khoj-ai/khoj", + "description": "Self-hostable \"AI second brain\": answers over your docs and the web, custom agents, scheduled automations, and multi-client reach (web, Obsidian, Emacs, WhatsApp). A personal-agent harness with retrieval at the core.", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 38207, + "tags": [ + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Agent Zero", + "catalog_ids": { + "github": "agent0ai/agent-zero", + "best_of": "agent-zero" + }, + "described_at_url": "https://github.com/agent0ai/agent-zero", + "description": "Organic, prompt-defined personal agent framework: hierarchical sub-agents, persistent memory, browser and code tools, and self-modifying behavior; runs in Docker with a web UI.", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "unknown", + "stars": 19951, + "tags": [ + "memory", + "multi-agent", + "browser", + "sandbox", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Eliza", + "catalog_ids": { + "github": "elizaOS/eliza", + "best_of": "eliza" + }, + "described_at_url": "https://github.com/elizaOS/eliza", + "description": "Open \"agentic operating system\" (elizaOS): persistent multi-agent runtime with character files, a plugin ecosystem, and social/platform integrations — the harness behind a large share of autonomous social agents.", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 19912, + "tags": [ + "memory", + "multi-agent", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "OpenJarvis", + "catalog_ids": { + "github": "open-jarvis/OpenJarvis", + "best_of": "openjarvis" + }, + "described_at_url": "https://github.com/open-jarvis/OpenJarvis", + "description": "Stanford Hazy Research's local-first personal AI **harness**: on-device model inference (Ollama built in), agent execution, memory, and learning as shared primitives, with on-demand, scheduled, and continuous agents and evaluations that count energy, latency, and dollars alongside accuracy; a cloud ", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "slightly complex", + "autonomy": "headless", + "recovery": "none", + "license_signal": "open-source", + "stars": 18000, + "tags": [ + "memory", + "local", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "OpenHarness (HKUDS)", + "catalog_ids": { + "github": "HKUDS/OpenHarness", + "best_of": "openharness" + }, + "described_at_url": "https://github.com/HKUDS/OpenHarness", + "description": "Open agent harness with a built-in personal agent (\"Ohmo\") that runs across Feishu, Slack, Telegram, and Discord; core tool-use, skills, memory, multi-agent coordination with auto-compaction for multi-day sessions.", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 16235, + "tags": [ + "memory", + "multi-agent" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "QM", + "catalog_ids": { + "github": "yc-software/qm", + "best_of": "qm" + }, + "described_at_url": "https://github.com/yc-software/qm", + "description": "Y Combinator's multiplayer agent **harness** for work, open-sourced from months of internal use: every person and room gets scoped memory, files, credentials, permissions, crons, web apps, and a durable sandbox; sessions, memory, and the work queue live in Postgres, sandboxes are a resource the agen", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "complex", + "autonomy": "headless", + "recovery": "durable", + "license_signal": "open-source", + "stars": 15761, + "tags": [ + "memory", + "sandbox", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Ouroboros (razzant)", + "catalog_ids": { + "github": "razzant/ouroboros", + "best_of": "ouroboros-2" + }, + "described_at_url": "https://github.com/razzant/ouroboros", + "description": "Self-modifying personal agent that keeps its identity, durable memory, and history across tasks and restarts. The **harness** owns the agent loop, tool execution, and specialist-subagent coordination, and it changes its own code only through review gates, with restart checks and rollback kept in git", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "slightly complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 1699, + "tags": [ + "memory", + "multi-agent", + "browser", + "cli", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "AIlice", + "catalog_ids": { + "github": "myshell-ai/AIlice", + "best_of": "ailice" + }, + "described_at_url": "https://github.com/myshell-ai/AIlice", + "description": "Fully autonomous general-purpose agent; one binary, Docker-ready, for when you want \"set goal and walk away\" without a framework.", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "none", + "license_signal": "open-source", + "stars": 1421, + "tags": [ + "sandbox", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Talon", + "catalog_ids": { + "github": "thefalconry/talon", + "best_of": "talon" + }, + "described_at_url": "https://github.com/thefalconry/talon", + "description": "Multi-platform personal agent living in Telegram, Discord, Teams, and the terminal. The **harness** is a pluggable-backend loop (Claude, Kilo, OpenCode, Codex, OpenAI Agents) with full MCP tool access and persistent background agents (Goals, Heartbeat, Dream); the chat apps are shells.", + "best_of": { + "category_title": "Personal agent runtimes", + "tier": "slightly complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 72, + "tags": [ + "mcp", + "memory", + "cli", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "n8n", + "catalog_ids": { + "github": "n8n-io/n8n", + "best_of": "n8n" + }, + "described_at_url": "https://github.com/n8n-io/n8n", + "description": "Fair-code workflow engine with 400+ nodes and native AI nodes; the self-hosted Zapier that actually does agents and LangChain.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "headless", + "recovery": "durable", + "license_signal": "restricted (Fair-code)", + "stars": 211824, + "tags": [ + "workflow", + "local", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "AutoGPT", + "catalog_ids": { + "github": "Significant-Gravitas/AutoGPT", + "best_of": "autogpt" + }, + "described_at_url": "https://github.com/Significant-Gravitas/AutoGPT", + "description": "The original autonomous loop: goal in, agent iterates with tools and memory; Forge is the dev framework, Benchmark the eval harness.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "restricted (Polyform-SU)", + "stars": 188134, + "tags": [ + "memory", + "evals", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Dify", + "catalog_ids": { + "github": "langgenius/dify", + "best_of": "dify" + }, + "described_at_url": "https://github.com/langgenius/dify", + "description": "One-stop LLM app platform: visual workflows, RAG pipeline, 50+ tools, model management; \"ship from prototype to prod\" in a single UI.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "headless", + "recovery": "retry", + "license_signal": "restricted (Fair-code)", + "stars": 161686, + "tags": [ + "low-code", + "rag", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "langflow", + "catalog_ids": { + "github": "langflow-ai/langflow", + "best_of": "langflow" + }, + "described_at_url": "https://github.com/langflow-ai/langflow", + "description": "Low-code UI to build and deploy LangChain/LangGraph flows; visual DAG editor and one-click run.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "headless", + "recovery": "retry", + "license_signal": "open-source", + "stars": 156848, + "tags": [ + "low-code", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "langchain", + "catalog_ids": { + "github": "langchain-ai/langchain", + "best_of": "langchain" + }, + "described_at_url": "https://github.com/langchain-ai/langchain", + "description": "Chains, tools, retrievers, and agents; the usual entry point for \"add tools to an LLM\" in Python/JS.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "bounded", + "recovery": "retry", + "license_signal": "open-source", + "stars": 149987, + "tags": [ + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "browser-use", + "catalog_ids": { + "github": "browser-use/browser-use", + "best_of": "browser-use" + }, + "described_at_url": "https://github.com/browser-use/browser-use", + "description": "Python web-agent **harness**: natural-language goals become browser actions, driven directly over the Chrome DevTools Protocol (it dropped Playwright in August 2025). The biggest community in the browser-agent category.", + "best_of": { + "category_title": "Frameworks", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "retry", + "license_signal": "open-source", + "stars": 121761, + "tags": [ + "browser", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Flowise", + "catalog_ids": { + "github": "FlowiseAI/Flowise", + "best_of": "flowise" + }, + "described_at_url": "https://github.com/FlowiseAI/Flowise", + "description": "Drag-and-drop LangChain UI; deploy flows without code. The low-code sibling to Langflow, with a different component and hosting story.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "headless", + "recovery": "retry", + "license_signal": "restricted (Apache+CLA)", + "stars": 55583, + "tags": [ + "low-code", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "llama-index", + "catalog_ids": { + "github": "run-llama/llama_index", + "best_of": "llama_index" + }, + "described_at_url": "https://github.com/run-llama/llama_index", + "description": "Data-centric: indexing, RAG, and query engines; agent abstractions sit on top of your data pipelines.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "bounded", + "recovery": "retry", + "license_signal": "open-source", + "stars": 52982, + "tags": [ + "rag", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "langgraph", + "catalog_ids": { + "github": "langchain-ai/langgraph", + "best_of": "langgraph" + }, + "described_at_url": "https://github.com/langchain-ai/langgraph", + "description": "State-machine graphs over LLM steps; checkpointing, human-in-the-loop, and durable execution so workflows survive restarts.", + "best_of": { + "category_title": "Frameworks", + "tier": "slightly complex", + "autonomy": "headless", + "recovery": "durable", + "license_signal": "open-source", + "stars": 45269, + "tags": [ + "workflow", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "agno", + "catalog_ids": { + "github": "agno-agi/agno", + "best_of": "agno" + }, + "described_at_url": "https://github.com/agno-agi/agno", + "description": "Python agents with memory, knowledge bases, tools, and structured outputs; continues the PhiData-era product line under the Agno name—production apps, evals, and pipelines.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 43260, + "tags": [ + "memory", + "evals", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "mastra", + "catalog_ids": { + "github": "mastra-ai/mastra", + "best_of": "mastra" + }, + "described_at_url": "https://github.com/mastra-ai/mastra", + "description": "TypeScript-first; agents, tools, and workflows with a single runtime and minimal boilerplate.", + "best_of": { + "category_title": "Frameworks", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "durable", + "license_signal": "restricted (Elastic-2.0)", + "stars": 29740, + "tags": [ + "typed", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "semantic-kernel", + "catalog_ids": { + "github": "microsoft/semantic-kernel", + "best_of": "semantic-kernel" + }, + "described_at_url": "https://github.com/microsoft/semantic-kernel", + "description": "Microsoft's plugin and planner layer for LLMs; C#, Python, Java; strong on enterprise auth and orchestration.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "bounded", + "recovery": "retry", + "license_signal": "open-source", + "stars": 28790, + "tags": [ + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Haystack", + "catalog_ids": { + "github": "deepset-ai/haystack", + "best_of": "haystack" + }, + "described_at_url": "https://github.com/deepset-ai/haystack", + "description": "Open-source orchestration framework for context-engineered LLM apps: modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation—closer to LangChain's territory than a coding-agent harness.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 27077, + "tags": [ + "memory", + "rag", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Stagehand", + "catalog_ids": { + "github": "browserbase/stagehand", + "best_of": "stagehand" + }, + "described_at_url": "https://github.com/browserbase/stagehand", + "description": "Browserbase's SDK for browser agents: natural-language actions (act, extract, observe) and deterministic Playwright code mix in one script, so agent flexibility and repeatable automation live in the same **harness**.", + "best_of": { + "category_title": "Frameworks", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "none", + "license_signal": "open-source", + "stars": 26115, + "tags": [ + "browser", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "letta", + "catalog_ids": { + "github": "letta-ai/letta", + "best_of": "letta" + }, + "described_at_url": "https://github.com/letta-ai/letta", + "description": "Python agent runtime with tool use and control flow; lean API; stateful agents with long-horizon memory.", + "best_of": { + "category_title": "Frameworks", + "tier": "mostly simple", + "autonomy": "headless", + "recovery": "durable", + "license_signal": "open-source", + "stars": 25513, + "tags": [ + "memory", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Google ADK", + "catalog_ids": { + "github": "google/adk-python", + "best_of": "adk-python" + }, + "described_at_url": "https://github.com/google/adk-python", + "description": "Google's official Agent Development Kit: code-first Python toolkit for building, evaluating, and deploying agents. Optimized for Gemini but model-agnostic; deploys to Cloud Run / Vertex AI; ships a dev UI with eval and a code-execution sandbox.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 22313, + "tags": [ + "evals", + "sandbox", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "rasa", + "catalog_ids": { + "github": "RasaHQ/rasa", + "best_of": "rasa" + }, + "described_at_url": "https://github.com/RasaHQ/rasa", + "description": "Conversational AI stack (NLU, dialogue, actions); long-standing OSS choice for chat and voice bots.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 21400, + "tags": [ + "voice", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "botpress", + "catalog_ids": { + "github": "botpress/botpress", + "best_of": "botpress" + }, + "described_at_url": "https://github.com/botpress/botpress", + "description": "Visual bot builder and runtime; multi-channel, open-source alternative to commercial bot platforms.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 15003, + "tags": [ + "low-code", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "R2R", + "catalog_ids": { + "github": "SciPhi-AI/R2R", + "best_of": "r2r" + }, + "described_at_url": "https://github.com/SciPhi-AI/R2R", + "description": "RAG-first: hybrid search, knowledge graphs, multimodal; the framework for \"production RAG\" when you care more about retrieval than chat UI.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "headless", + "recovery": "retry", + "license_signal": "open-source", + "stars": 8105, + "tags": [ + "vision", + "rag", + "workflow", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "agent-squad", + "catalog_ids": { + "github": "2FastLabs/agent-squad", + "best_of": "agent-squad" + }, + "described_at_url": "https://github.com/2FastLabs/agent-squad", + "description": "AWS-originated orchestrator (now under 2FastLabs): intent classification, streaming, SupervisorAgent; \"agent-as-tools\" so one agent delegates to a squad.", + "best_of": { + "category_title": "Frameworks", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 7804, + "tags": [ + "multi-agent" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "AgentVerse", + "catalog_ids": { + "github": "OpenBMB/AgentVerse", + "best_of": "agentverse" + }, + "described_at_url": "https://github.com/OpenBMB/AgentVerse", + "description": "Task-solving and simulation envs for multi-LLM agents; deploy many agents in custom environments without building infra from scratch.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "headless", + "recovery": "none", + "license_signal": "open-source", + "stars": 5164, + "tags": [ + "multi-agent", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "youtu-agent", + "catalog_ids": { + "github": "TencentCloudADP/youtu-agent", + "best_of": "youtu-agent" + }, + "described_at_url": "https://github.com/TencentCloudADP/youtu-agent", + "description": "Tencent Cloud's agent framework: a minimal tool-calling **harness** designed to perform well with open-source models, positioned as a lighter alternative to heavier orchestration frameworks.", + "best_of": { + "category_title": "Frameworks", + "tier": "mostly simple", + "autonomy": "bounded", + "recovery": "retry", + "license_signal": "unknown", + "stars": 4637, + "tags": [], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Bee Agent Framework", + "catalog_ids": { + "github": "i-am-bee/beeai-framework", + "best_of": "beeai-framework" + }, + "described_at_url": "https://github.com/i-am-bee/beeai-framework", + "description": "Python + TypeScript, LF AI–backed; MCP/ACP, workflows, Requirement Agent; the one that pushes \"production multi-agent\" without LangChain.", + "best_of": { + "category_title": "Frameworks", + "tier": "complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 3458, + "tags": [ + "mcp", + "multi-agent", + "python", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "AgentStack", + "catalog_ids": { + "github": "agentstack-ai/AgentStack", + "best_of": "agentstack" + }, + "described_at_url": "https://github.com/agentstack-ai/AgentStack", + "description": "Scaffolds full agent projects; plugs in CrewAI, LangGraph, OpenAI Swarm, LlamaStack and wires AgentOps observability from day one.", + "best_of": { + "category_title": "Frameworks", + "tier": "slightly complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 2198, + "tags": [], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "AgentSilex", + "catalog_ids": { + "github": "howl-anderson/agentsilex", + "best_of": "agentsilex" + }, + "described_at_url": "https://github.com/howl-anderson/agentsilex", + "description": "~300 lines of readable agent code on top of LiteLLM; the \"I want to see the whole loop\" option for learning or minimal production.", + "best_of": { + "category_title": "Frameworks", + "tier": "super simple", + "autonomy": "bounded", + "recovery": "none", + "license_signal": "open-source", + "stars": 460, + "tags": [ + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "SuperAgentX", + "catalog_ids": { + "github": "superagentxai/superagentx", + "best_of": "superagentx" + }, + "described_at_url": "https://github.com/superagentxai/superagentx", + "description": "Lightweight multi-agent orchestrator with an AGI-angle; minimal surface, docs-first, for teams that want orchestration without the kitchen sink.", + "best_of": { + "category_title": "Frameworks", + "tier": "mostly simple", + "autonomy": "bounded", + "recovery": "none", + "license_signal": "open-source", + "stars": 211, + "tags": [ + "multi-agent", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "MetaGPT", + "catalog_ids": { + "github": "FoundationAgents/MetaGPT", + "best_of": "metagpt" + }, + "described_at_url": "https://github.com/FoundationAgents/MetaGPT", + "description": "The \"AI software company\" multi-agent framework: role-played PM, architect, and engineer agents turn a one-line requirement into specs, designs, and code along an SOP assembly line. The landmark of the genre; development pace has slowed in 2026.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 71407, + "tags": [ + "multi-agent", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "crewAI", + "catalog_ids": { + "github": "crewAIInc/crewAI", + "best_of": "crewai" + }, + "described_at_url": "https://github.com/crewAIInc/crewAI", + "description": "Role-based agents (roles, goals, backstories) in Crews; Flows add event-driven and hierarchical control for production.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 61173, + "tags": [ + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "OpenManus", + "catalog_ids": { + "github": "FoundationAgents/OpenManus", + "best_of": "openmanus" + }, + "described_at_url": "https://github.com/FoundationAgents/OpenManus", + "description": "Open, invite-free general agent from the MetaGPT team: planning plus tool use over a multi-agent loop, aimed at reproducing Manus-style autonomous task completion on your own keys.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "bounded", + "recovery": "none", + "license_signal": "open-source", + "stars": 59007, + "tags": [ + "multi-agent", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "ChatDev", + "catalog_ids": { + "github": "OpenBMB/ChatDev", + "best_of": "chatdev" + }, + "described_at_url": "https://github.com/OpenBMB/ChatDev", + "description": "Multi-agent software-company simulation (CEO, CTO, programmer, tester) built on chat chains with communicative dehallucination; ChatDev 2.0 continues the line. MetaGPT's conversational sibling.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "slightly complex", + "autonomy": "headless", + "recovery": "none", + "license_signal": "open-source", + "stars": 34845, + "tags": [ + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "openai-agents-python", + "catalog_ids": { + "github": "openai/openai-agents-python", + "best_of": "openai-agents-python" + }, + "described_at_url": "https://github.com/openai/openai-agents-python", + "description": "Handoffs, guardrails, and multi-LLM routing; minimal surface so you own the loop.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "mostly simple", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 30815, + "tags": [ + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Microsoft Agent Framework", + "catalog_ids": { + "github": "microsoft/agent-framework", + "best_of": "agent-framework" + }, + "described_at_url": "https://github.com/microsoft/agent-framework", + "description": "Microsoft's convergence of AutoGen and Semantic Kernel: build, orchestrate, and deploy agents and multi-agent workflows in Python and .NET, with graph-based workflows and checkpointing — the designated successor harness for both lines.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "slightly complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 14693, + "tags": [ + "multi-agent", + "workflow", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "omnigent", + "catalog_ids": { + "github": "omnigent-ai/omnigent", + "best_of": "omnigent" + }, + "described_at_url": "https://github.com/omnigent-ai/omnigent", + "description": "Open-source meta-**harness**: orchestrates Claude Code, Codex, Cursor, Pi, and custom agents behind one policy/sandboxing layer so teams swap harnesses without rewriting workflows.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "unknown", + "stars": 11492, + "tags": [ + "sandbox", + "ide", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "hive", + "catalog_ids": { + "github": "aden-hive/hive", + "best_of": "hive" + }, + "described_at_url": "https://github.com/aden-hive/hive", + "description": "Self-hosted multi-agent **harness** aimed at production workloads: human-in-the-loop checkpoints and a self-improving agent loop, distinct from single-session coding-agent shells.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "unknown", + "stars": 11167, + "tags": [ + "multi-agent", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Orkas", + "catalog_ids": { + "github": "Orkas-AI/Orkas", + "best_of": "orkas" + }, + "described_at_url": "https://github.com/Orkas-AI/Orkas", + "description": "Local-first desktop AI team. The **harness** is a Commander agent that turns one chat goal into a plan and runs specialist agents in parallel or in sequence, with tool approvals, session checkpoints, tool-round budgets and idle watchdogs for stalled runs, durable per-agent memory, and support for bu", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 9540, + "tags": [ + "memory", + "multi-agent", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "PraisonAI", + "catalog_ids": { + "github": "MervinPraison/PraisonAI", + "best_of": "praisonai" + }, + "described_at_url": "https://github.com/MervinPraison/PraisonAI", + "description": "Autonomous multi-agent teams with a single entry point; emphasis on minimal config.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "mostly simple", + "autonomy": "bounded", + "recovery": "none", + "license_signal": "open-source", + "stars": 9380, + "tags": [ + "multi-agent", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Open Multi-Agent", + "catalog_ids": { + "github": "open-multi-agent/open-multi-agent", + "best_of": "open-multi-agent" + }, + "described_at_url": "https://github.com/open-multi-agent/open-multi-agent", + "description": "Self-hosted TypeScript multi-agent runtime. The **harness** is a coordinator that plans a task DAG from one goal at runtime and a deterministic scheduler that runs specialized agents, with durable approvals that pause before a plan, task, or tool call, PostgreSQL-backed checkpoints for restart recov", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "slightly complex", + "autonomy": "checkpoint-gated", + "recovery": "durable", + "license_signal": "open-source", + "stars": 7071, + "tags": [ + "multi-agent", + "low-code", + "workflow", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Raven", + "catalog_ids": { + "github": "EverMind-AI/Raven", + "best_of": "raven" + }, + "described_at_url": "https://github.com/EverMind-AI/Raven", + "description": "EverMind's host agent, with its loop split into memory, planning, capability, and action modules. The **harness** plans complex tasks as DAGs and orchestrates built-in research, coding, design, and on-call agents plus third-party agents (Claude Code, Codex, OpenClaw, Hermes Agent) over ACP, CLI, or ", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "headless", + "recovery": "none", + "license_signal": "open-source", + "stars": 6291, + "tags": [ + "mcp", + "memory", + "multi-agent", + "cli", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "AG2", + "catalog_ids": { + "github": "ag2ai/ag2", + "best_of": "ag2" + }, + "described_at_url": "https://github.com/ag2ai/ag2", + "description": "AG2 (formerly AutoGen): the community-governed continuation of the original AutoGen project after Microsoft's fork diverged—conversable multi-agent groups, code execution, and human-in-the-loop under an open-source AgentOS banner. Graduated off the radar this cycle.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "unknown", + "stars": 5081, + "tags": [ + "multi-agent", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "HarnessRouter", + "catalog_ids": { + "github": "HarnessRouter/harnessrouter", + "best_of": "harnessrouter" + }, + "described_at_url": "https://github.com/HarnessRouter/harnessrouter", + "description": "Self-hostable Community Edition of a unified interface for complete agent harnesses. The **harness** contribution is the layer around them: each task runs a full harness (Codex, Claude Code, Hermes, Pi, DeepSeek Harness, and others) in its own on-demand sandbox, the harness is a request parameter be", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 4407, + "tags": [ + "memory", + "sandbox", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Agent Teams AI", + "catalog_ids": { + "github": "777genius/agent-teams-ai", + "best_of": "agent-teams-ai" + }, + "described_at_url": "https://github.com/777genius/agent-teams-ai", + "description": "Desktop app that runs a team of coding agents (Claude Code, Codex, OpenCode, Cursor, Copilot, and others) on a kanban board: agents take tasks, message each other, and review each other's work before it is accepted. The **harness** contribution is the team-coordination layer over existing agent CLIs", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 2529, + "tags": [ + "multi-agent", + "ide", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "CUGA", + "catalog_ids": { + "github": "cuga-project/cuga-agent", + "best_of": "cuga-agent" + }, + "described_at_url": "https://github.com/cuga-project/cuga-agent", + "description": "Open-source enterprise agent **harness**: a code-act loop in which the model writes Python that calls MCP, OpenAPI, and LangChain tools as functions inside a restricted sandbox, with results kept as variables, pre-execution verification, reflection, and tool shortlisting; CugaSupervisor coordinates ", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "mostly simple", + "autonomy": "bounded", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 1194, + "tags": [ + "mcp", + "multi-agent", + "sandbox", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Desplega Agent Swarm", + "catalog_ids": { + "github": "desplega-ai/agent-swarm", + "best_of": "agent-swarm" + }, + "described_at_url": "https://github.com/desplega-ai/agent-swarm", + "description": "Self-hosted multi-agent orchestration service: a lead agent delegates queued tasks to Claude Code, Codex, and other workers in isolated containers. The **harness** contribution is the lead-to-worker hierarchy, the task queue, shared memory, and review gates, with MCP tools and Slack and GitHub integ", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 1101, + "tags": [ + "mcp", + "memory", + "multi-agent", + "sandbox", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "fractal", + "catalog_ids": { + "github": "plasma-ai/fractal", + "best_of": "fractal" + }, + "described_at_url": "https://github.com/plasma-ai/fractal", + "description": "Hierarchical coding-agent **harness**: each autonomous loop works in its own git worktree and can delegate separable subtasks to child loops, so the execution tree grows recursively, with five coding-agent CLIs wired into per-node loops, shared SQLite run state, operator controls, and depth, cost, a", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "slightly complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 797, + "tags": [ + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Claudexor", + "catalog_ids": { + "github": "razzant/claudexor", + "best_of": "claudexor" + }, + "described_at_url": "https://github.com/razzant/claudexor", + "description": "Local-first control plane that routes one coding thread across Claude Code, Codex, Cursor, and OpenCode. The **harness** contribution is the layer around those agents: quota-aware rotation across isolated subscription profiles, bounded context handoffs between agents and accounts, best-of-N races, c", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "slightly complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 526, + "tags": [ + "multi-agent", + "sandbox", + "ide", + "typescript" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "AgentRL", + "catalog_ids": { + "github": "THUDM/AgentRL", + "best_of": "agentrl" + }, + "described_at_url": "https://github.com/THUDM/AgentRL", + "description": "Multitask, multiturn RL for LLM agents; Ray-based scaling, rollout/actor workers—for teams that want to train agents, not just run them.", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "headless", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 367, + "tags": [ + "training", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "GraphCode", + "catalog_ids": { + "github": "scgopi/GraphCode", + "best_of": "graphcode" + }, + "described_at_url": "https://github.com/scgopi/GraphCode", + "description": "macOS canvas that runs Claude Code, Codex CLI, Copilot CLI, and OpenCode sessions as nodes on a graph. The **harness** is the graph itself: each loop is typed by what ends it (a turn, a shell predicate or declared goal, a cadence, or a sub-graph), hand-off and spawn edges fire when a loop resolves, ", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "slightly complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "restricted (FSL-1.1-MIT)", + "stars": 159, + "tags": [ + "memory", + "workflow", + "cli" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "Agent Barn", + "catalog_ids": { + "github": "aai-labs/agent-barn", + "best_of": "agent-barn" + }, + "described_at_url": "https://github.com/aai-labs/agent-barn", + "description": "Control plane for teams of agents on your own Kubernetes cluster, deployed with Helm. The **harness** contribution is the layer around runtimes such as Hermes and OpenClaw: chat front ends (Slack, Teams, Telegram, Discord, email), tool wiring to Jira, GitHub, and Confluence, a model key per agent, a", + "best_of": { + "category_title": "Multi-agent and orchestration", + "tier": "complex", + "autonomy": "n/a", + "recovery": "n/a", + "license_signal": "open-source", + "stars": 112, + "tags": [ + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "status": "listed (not checked)" + }, + { + "label": "RuleGo", + "catalog_ids": { + "github": "rulego/rulego" + }, + "described_at_url": "https://github.com/rulego/rulego", + "description": "Lightweight embedded component orchestration (rule engine) for Go; rule chains as JSON DAGs.", + "best_of": null, + "licence": { + "spdx": "Apache-2.0", + "source": "GitHub API" + }, + "pin_candidate": { + "version": "v1.0.0", + "released": "2026-10-19", + "rule": "newest release at least two weeks old on 2026-11-22" + }, + "provides_interface": [ + { + "interface": "dag-orchestration", + "evidence": "rule chains as JSON DAGs; embedded in a Go program", + "source": "README" + } + ], + "telemetry_default": "none (library)", + "status": "shortlist", + "note": "rulego-server is a modified Apache-2.0 with extra conditions (its LICENSE): out; the core and components are libraries, so this means a small Go service of ours" + }, + { + "label": "RuleGo AI components", + "catalog_ids": { + "github": "rulego/rulego-components-ai" + }, + "described_at_url": "https://github.com/rulego/rulego-components-ai", + "description": "Declarative AI agent framework on RuleGo: ReAct agent node, MCP client and server, OpenAI-compatible, 10 AOP aspects incl. pre-LLM and pre-tool-call.", + "best_of": null, + "licence": { + "spdx": "Apache-2.0", + "source": "GitHub API" + }, + "pin_candidate": { + "version": "v1.0.0 (tag, no release object)", + "released": null, + "rule": "newest release at least two weeks old on 2026-11-22" + }, + "provides_interface": [ + { + "interface": "openai-compatible-endpoint", + "evidence": "\"OpenAI Compatible\"; per-session model switching", + "source": "README" + }, + { + "interface": "mcp-client-stdio", + "evidence": "\"MCP Bidirectional Protocol — Acts as both MCP client ... and MCP server\"", + "source": "README" + }, + { + "interface": "model-call-hook", + "evidence": "AOP aspects pre-LLM, post-LLM, pre-tool-call, post-tool-call", + "source": "README" + }, + { + "interface": "built-in-tools", + "evidence": "bash, read, write, edit", + "source": "README" + } + ], + "telemetry_default": "none (library)", + "status": "shortlist", + "note": "7 stars; tagged v1.0.0, tag date to be read; last commits 2026-11-06 to 11-11" + }, + { + "label": "aider", + "catalog_ids": { + "github": "aider-ai/aider", + "best_of": "aider" + }, + "described_at_url": "https://github.com/Aider-AI/aider", + "description": "Git-aware CLI pair programmer; edits in-repo, supports multiple models and MCP so agents see version control and tools.", + "best_of": { + "category_title": "Plugins, MCPs, CLI tools", + "tier": "slightly complex", + "autonomy": "checkpoint-gated", + "recovery": "resumable", + "license_signal": "open-source", + "stars": 50220, + "tags": [ + "mcp", + "cli", + "python" + ], + "source": "best-of-Agent-Harnesses (RyanAlberts, CC-BY-SA-4.0), harnesses.json read 2026-11-22" + }, + "licence": { + "spdx": "Apache-2.0", + "source": "GitHub API" + }, + "pin_candidate": { + "version": "v0.86.0", + "released": "2025-08-09" + }, + "status": "ruled-out", + "reason": "last release 2025-08-09; no MCP client documented" + }, + { + "label": "mini-swe-agent", + "catalog_ids": { + "github": "swe-agent/mini-swe-agent" + }, + "described_at_url": "https://github.com/swe-agent/mini-swe-agent", + "description": "", + "best_of": null, + "licence": { + "spdx": "MIT", + "source": "GitHub API" + }, + "pin_candidate": { + "version": "v2.4.6", + "released": "2026-07-23" + }, + "status": "ruled-out", + "reason": "no MCP; bash only, no tool calling (a prompt-size reference)" + }, + { + "label": "claude-code", + "catalog_ids": { + "github": "anthropics/claude-code" + }, + "described_at_url": "https://github.com/anthropics/claude-code", + "description": "", + "best_of": null, + "licence": { + "spdx": "none (proprietary)", + "source": "GitHub API" + }, + "pin_candidate": { + "version": null, + "released": null + }, + "status": "in-use-not-default", + "reason": "no open licence: stays the companion on the owner's login (S-136), as an agent instance, not a default part" + } + ] +} \ No newline at end of file diff --git a/scripts/trials/harness/net.sh b/scripts/trials/harness/net.sh new file mode 100755 index 0000000..07186da --- /dev/null +++ b/scripts/trials/harness/net.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# The trial's network (S-172): internal (no route out), the stack's gateway attached as `gateway`, and a recording +# proxy (`proxy`, S-162's proxy_rec.py) that logs and refuses anything sent to it. A harness on this network reaches +# the gateway and nothing else: a call that honours HTTP(S)_PROXY is logged; one that does not, fails. +# scripts/trials/harness/net.sh up|down +set -eu +here=$(cd "$(dirname "$0")" && pwd); root=$(cd "$here/../../.." && pwd) +out=$root/.state/trials/harness; mkdir -p "$out" +case "${1:-}" in + up) + podman network exists harness-trial || podman network create --internal harness-trial >/dev/null + podman network connect --alias gateway harness-trial substrate-gateway-1 2>/dev/null || true + podman rm -f harness-proxy >/dev/null 2>&1 || true + podman run -d --name harness-proxy --network harness-trial --network-alias proxy --cap-drop ALL \ + -v "$root/scripts/trials/offline-agent:/p:ro" -v "$out:/out" -e PROXY_LOG=/out/proxy_hits.log \ + --entrypoint python3 docker.io/library/python:3.13-alpine -c \ + "import sys,runpy; sys.argv=['p','8888']; import http.server as h; exec(open('/p/proxy_rec.py').read().replace('\"127.0.0.1\"','\"0.0.0.0\"'))" >/dev/null + echo "harness-trial up: gateway and proxy attached" ;; + down) + podman rm -f harness-proxy >/dev/null 2>&1 || true + podman network disconnect harness-trial substrate-gateway-1 2>/dev/null || true + podman network rm harness-trial >/dev/null 2>&1 || true + echo "harness-trial down" ;; + *) echo "usage: net.sh up|down" >&2; exit 2 ;; +esac diff --git a/scripts/trials/harness/stub_mcp.py b/scripts/trials/harness/stub_mcp.py new file mode 100644 index 0000000..072375a --- /dev/null +++ b/scripts/trials/harness/stub_mcp.py @@ -0,0 +1,45 @@ +"""A stub MCP server over stdio, standard library only (any image with python3 runs it): one tool, `add`, and a log of +every call in STUB_MCP_LOG. MCP's stdio transport is JSON-RPC 2.0, one message per line.""" +import json +import os +import sys + +LOG = os.environ.get("STUB_MCP_LOG", "/tmp/stub_mcp.log") +TOOLS = [{"name": "add", "description": "Add two numbers and return the sum", + "inputSchema": {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}, "required": ["a", "b"]}}] + + +def reply(i, result=None, error=None): + msg = {"jsonrpc": "2.0", "id": i} + msg.update({"error": error} if error else {"result": result}) + sys.stdout.write(json.dumps(msg) + "\n") + sys.stdout.flush() + + +for line in sys.stdin: + try: + m = json.loads(line) + except ValueError: + continue + method, i = m.get("method"), m.get("id") + if i is None: # a notification (e.g. notifications/initialized) + continue + if method == "initialize": + reply(i, {"protocolVersion": (m.get("params") or {}).get("protocolVersion", "2025-06-18"), + "capabilities": {"tools": {}}, "serverInfo": {"name": "stub", "version": "0.1"}}) + elif method == "tools/list": + reply(i, {"tools": TOOLS}) + elif method == "tools/call": + p = m.get("params") or {} + args = p.get("arguments") or {} + with open(LOG, "a") as f: + f.write(json.dumps({"tool": p.get("name"), "arguments": args}) + "\n") + if p.get("name") != "add": + reply(i, error={"code": -32602, "message": "no such tool"}) + else: + total = (args.get("a") or 0) + (args.get("b") or 0) + reply(i, {"content": [{"type": "text", "text": str(total)}], "isError": False}) + elif method == "ping": + reply(i, {}) + else: + reply(i, error={"code": -32601, "message": f"method not found: {method}"}) diff --git a/scripts/trials/openenv/Containerfile b/scripts/trials/openenv/Containerfile new file mode 100644 index 0000000..773a671 --- /dev/null +++ b/scripts/trials/openenv/Containerfile @@ -0,0 +1,6 @@ +# The OpenEnv spike (S-184, plan step 1): openenv 0.12.0 beside Claude Code and psycopg. Trial only, never published. +FROM localhost/substrate-companion:local +USER root +RUN pip install --no-cache-dir openenv==0.12.0 +USER companion +CMD ["sleep", "infinity"] diff --git a/scripts/trials/openenv/run.sh b/scripts/trials/openenv/run.sh new file mode 100755 index 0000000..df0fde1 --- /dev/null +++ b/scripts/trials/openenv/run.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# The OpenEnv spike (S-184, plan step 1): openenv 0.12.0 beside Claude Code, on the stack's Postgres (throwaway +# databases openenv_trial*). scripts/trials/openenv/run.sh [all|facts|p1|p3|p47]; results in .state/trials/openenv/. +set -eu +cd "$(dirname "$0")/../../.." + +out=.state/trials/openenv; mkdir -p "$out" +podman image exists substrate-trial-openenv:local || podman build -t substrate-trial-openenv:local scripts/trials/openenv +POSTGRES_PASSWORD=$(sed -n "s/^POSTGRES_PASSWORD=//p" .env | tail -1); export POSTGRES_PASSWORD # by name below, never on a command line +podman run --rm --network substrate_default -e POSTGRES_PASSWORD \ + -v "$PWD/scripts/trials/openenv/spike.py:/opt/spike.py:ro,Z" \ + substrate-trial-openenv:local python3 -I /opt/spike.py "${1:-all}" | tee -a "$out/results.jsonl" diff --git a/scripts/trials/openenv/spike.py b/scripts/trials/openenv/spike.py new file mode 100644 index 0000000..98734ff --- /dev/null +++ b/scripts/trials/openenv/spike.py @@ -0,0 +1,451 @@ +"""The OpenEnv spike (S-184, plan step 1): openenv 0.12.0, one Postgres-backed environment, the seven points. + + python3 -I spike.py all | p1 | p2 | p3 | p47 (in the trial image; scripts/trials/openenv/run.sh) + +Each point prints one JSON result line; run.sh keeps them in .state/trials/openenv/results.jsonl. +Trial only: throwaway databases openenv_trial* on the stack's Postgres, dropped at the end. +""" +from __future__ import annotations + +import asyncio +import json +import os +import shutil +import statistics +import subprocess +import sys +import tempfile +import threading +import time +import uuid +from typing import Any, AsyncIterator, Optional + +import psycopg +import uvicorn +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse, StreamingResponse +from fastmcp import FastMCP + +from openenv.core.env_server.http_server import create_app +from openenv.core.env_server.interfaces import Environment # noqa: F401 (the base the classes below extend) +from openenv.core.env_server.mcp_environment import MCPEnvironment +from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation +from openenv.core.env_server.types import Observation, State +from openenv.core.harness import (AgenticHarnessAdapter, HarnessAction, HarnessConfig, HarnessEnvironment, + HarnessEvent, HarnessEventType) +from openenv.core.mcp_client import MCPToolClient +from openenv.core.rubrics import Rubric + +LIVE, TMPL = "openenv_trial", "openenv_trial_tmpl" +HOST = os.environ.get("PGHOST", "db") + + +def dsn(db: str = "postgres") -> str: + return f"postgresql://postgres:{os.environ['POSTGRES_PASSWORD']}@{HOST}:5432/{db}" + + +def sql(db: str, q: str, args: tuple = (), fetch: bool = False): + with psycopg.connect(dsn(db), autocommit=True) as c: + cur = c.execute(q, args) + return cur.fetchall() if fetch else None + + +def result(point: int, ok: bool, line: str, **data): + print(json.dumps({"point": point, "ok": ok, "result": line, **data}), flush=True) + + +SCHEMA = """ +create table if not exists note (id bigserial primary key, session text, episode text, body text, + at timestamptz default clock_timestamp()); +create table if not exists proposal (id bigserial primary key, session text, action text, status text default 'waiting'); +create table if not exists model_call (id bigserial primary key, episode text, path text, kind text, + has_tools bool, at timestamptz default clock_timestamp()); +create table if not exists outcome (episode text primary key, score float, at timestamptz default clock_timestamp()); +create or replace function note_event() returns trigger language plpgsql as $$ +begin perform pg_notify('note', json_build_object('id', new.id, 'session', new.session, 'body', new.body, + 'at', extract(epoch from new.at))::text); return new; end $$; +drop trigger if exists note_event on note; +create trigger note_event after insert on note for each row execute function note_event(); +""" + + +def setup(): + for db in (LIVE, TMPL): + if not sql("postgres", "select 1 from pg_database where datname=%s", (db,), fetch=True): + sql("postgres", f'create database "{db}"') + sql(db, SCHEMA) + # the template carries some data, so the clone copies something (10k notes, ~1 MB) + if sql(TMPL, "select count(*) from note", fetch=True)[0][0] == 0: + sql(TMPL, "insert into note(session, body) select 'seed', md5(g::text) from generate_series(1, 10000) g") + sql("postgres", f'alter database "{TMPL}" with is_template true') + + +def teardown(): + rows = sql("postgres", "select datname from pg_database where datname like 'openenv_ep_%%'", fetch=True) + for (db,) in rows: + sql("postgres", f'drop database "{db}" with (force)') + + +# ---- the environment: state in Postgres, so every session is a view of one live environment ------------------- + +class NotesEnv(MCPEnvironment): + """Tools over Postgres. Production: every session reads and writes the live database. Simulation: reset() + clones the template database and the episode works on its copy.""" + SUPPORTS_CONCURRENT_SESSIONS = True + + def __init__(self, db: str = LIVE): + mcp = FastMCP("notes") + self.db, self.session = db, uuid.uuid4().hex[:8] + self._state = State(episode_id=None, step_count=0) + env = self + + @mcp.tool + def note_add(body: str) -> str: + """Add a note to the shared notebook.""" + (nid,), = sql(env.db, "insert into note(session, episode, body) values (%s, %s, %s) returning id", + (env.session, env._state.episode_id, body), fetch=True) + return f"noted #{nid}" + + @mcp.tool + def notes_list(limit: int = 20) -> list[str]: + """The newest notes, from every session.""" + return [f"{s}: {b}" for s, b in sql(env.db, "select session, body from note where session <> 'seed' " + "order by id desc limit %s", (limit,), fetch=True)] + + @mcp.tool + def propose(action: str) -> dict: + """Ask the owner to approve an action; returns at once with the proposal's id (the gate, S-143).""" + (pid,), = sql(env.db, "insert into proposal(session, action) values (%s, %s) returning id", + (env.session, action), fetch=True) + return {"status": "waiting_for_approval", "proposal_id": pid} + + super().__init__(mcp) + + def reset(self, seed=None, episode_id=None, **kw) -> Observation: + ep = episode_id or uuid.uuid4().hex + name = f"openenv_ep_{ep[:12]}" + t0 = time.perf_counter() + sql("postgres", f'create database "{name}" template "{TMPL}" strategy {kw.get("strategy", "file_copy")}') + ms = (time.perf_counter() - t0) * 1000 + self.db, self._state = name, State(episode_id=ep, step_count=0) + return Observation(done=False, reward=0.0, metadata={"episode_id": ep, "db": name, "clone_ms": ms}) + + def _step_impl(self, action, timeout_s=None, **kw) -> Observation: + return Observation(done=False, reward=0.0, metadata={"error": "only MCP tool calls"}) + + @property + def state(self) -> State: + return self._state + + +def serve(app, port: int) -> uvicorn.Server: + srv = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning")) + threading.Thread(target=srv.run, daemon=True).start() + while not srv.started: + time.sleep(0.05) + return srv + + +# ---- points 1 and 2: many sessions on one live environment, events to a subscriber --------------------------- + +async def p1_p2(): + app = create_app(NotesEnv, CallToolAction, CallToolObservation, max_concurrent_envs=8, mode="production") + routes = sorted({getattr(r, "path", "") for r in app.routes}) + srv = serve(app, 8765) + got: list[tuple[float, dict]] = [] + ready = threading.Event() + + def listen(): + with psycopg.connect(dsn(LIVE), autocommit=True) as c: + c.execute("listen note") + ready.set() + for n in c.notifies(timeout=20, stop_after=6): + got.append((time.time(), json.loads(n.payload))) + t = threading.Thread(target=listen, daemon=True) + t.start() + ready.wait(5) + sql(LIVE, "truncate note, proposal") + try: + clients = [MCPToolClient("http://127.0.0.1:8765", mode="production") for _ in range(3)] + for c in clients: + await c.connect() + for i, c in enumerate(clients): + await c.call_tool("note_add", body=f"from agent {i}") + await c.call_tool("note_add", body=f"again from agent {i}") + seen = [await c.call_tool("notes_list") for c in clients] + gate = await clients[0].call_tool("propose", action="send the weekly email") + for c in clients: + await c.close() + finally: + srv.should_exit = True + t.join(25) + def as_list(x): + x = getattr(x, "data", None) or getattr(x, "structured_content", None) or x + if isinstance(x, dict) and "result" in x: + x = x["result"] + return x if isinstance(x, list) else [str(x)] + lists = [as_list(s) for s in seen] + sessions = {r[0] for r in sql(LIVE, "select distinct session from note", fetch=True)} + shared = all(len(l) == 6 for l in lists) and len(sessions) == 3 + result(1, shared, f"3 MCP sessions on one production server ({len(sessions)} server-side env instances) each " + f"saw all {len(lists[0])} notes written by all three: state lives in Postgres, not the instance; " + f"OpenEnv's production routes: {[r for r in routes if r]}", + seen=lists, propose=str(getattr(gate, 'data', gate))) + lat = [(ts - p["at"]) * 1000 for ts, p in got] + result(2, len(got) == 6, f"{len(got)}/6 inserts reached a LISTEN subscriber, median " + f"{statistics.median(lat):.1f} ms after commit (a trigger's pg_notify); OpenEnv itself pushes nothing " + f"in production mode (request/response only), so events come from Postgres (NOTIFY here, pgmq as " + f"environment/ does)" if got else "no events arrived", + latency_ms=[round(x, 2) for x in lat]) + + +# ---- point 3: reset clones a template database ------------------------------------------------------------- + +def p3(): + env = NotesEnv() + out = {} + for strategy in ("file_copy", "wal_log"): + ms = [env.reset(strategy=strategy).metadata["clone_ms"] for _ in range(10)] + out[strategy] = {"median_ms": round(statistics.median(ms), 1), "max_ms": round(max(ms), 1)} + env.reset() + n = sql(env.db, "select count(*) from note", fetch=True)[0][0] + size = sql("postgres", "select pg_size_pretty(pg_database_size(%s))", (TMPL,), fetch=True)[0][0] + teardown() + best = min(v["median_ms"] for v in out.values()) + result(3, best < 1000, f"reset() cloned a {size} template database (10k rows; the copy had {n}) in a median " + f"{out['file_copy']['median_ms']} ms with FILE_COPY, {out['wal_log']['median_ms']} ms with WAL_LOG " + f"(10 each, Postgres 17); one database per episode, dropped after", timings=out) + + +# ---- points 4 to 7: Claude Code through the harness adapter, against a model proxy ----------------------------- + +def proxy_app(): + """A stand-in for the ladder's proxy (S-178, plan step 3): records each model call with the episode id from its + header, and answers as a skill would (no model): a tool_use block for the env's tool, then final text.""" + app = FastAPI() + + def answer(body: dict) -> tuple[list[dict], str]: + tools = [t["name"] for t in body.get("tools", [])] + last = body["messages"][-1] + after_tool = isinstance(last.get("content"), list) and any(b.get("type") == "tool_result" + for b in last["content"]) + target = next((t for t in tools if t.endswith("note_add")), None) + if target and not after_tool: + return [{"type": "tool_use", "id": "toolu_" + uuid.uuid4().hex[:20], "name": target, + "input": {"body": "written by a skill through Claude Code"}}], "tool_use" + return [{"type": "text", "text": "Done: the note is in." if after_tool else "ok"}], "end_turn" + + def sse(msg: dict): + def ev(name, data): + return f"event: {name}\ndata: {json.dumps({'type': name, **data})}\n\n" + head = {**msg, "content": [], "stop_reason": None} + yield ev("message_start", {"message": head}) + for i, b in enumerate(msg["content"]): + if b["type"] == "text": + yield ev("content_block_start", {"index": i, "content_block": {"type": "text", "text": ""}}) + yield ev("content_block_delta", {"index": i, "delta": {"type": "text_delta", "text": b["text"]}}) + else: + yield ev("content_block_start", {"index": i, "content_block": {**b, "input": {}}}) + yield ev("content_block_delta", {"index": i, "delta": {"type": "input_json_delta", + "partial_json": json.dumps(b["input"])}}) + yield ev("content_block_stop", {"index": i}) + yield ev("message_delta", {"delta": {"stop_reason": msg["stop_reason"], "stop_sequence": None}, + "usage": {"output_tokens": 5}}) + yield ev("message_stop", {}) + + @app.post("/v1/messages/count_tokens") + async def count(req: Request): + return {"input_tokens": 10} + + @app.post("/v1/messages") + async def messages(req: Request): + body = await req.json() + content, stop = answer(body) + ep = req.headers.get("x-episode-id") + sql(LIVE, "insert into model_call(episode, path, kind, has_tools) values (%s, %s, %s, %s)", + (ep, req.url.path, content[0]["type"], bool(body.get("tools")))) + msg = {"id": "msg_" + uuid.uuid4().hex[:20], "type": "message", "role": "assistant", + "model": body.get("model", "trial"), "content": content, "stop_reason": stop, "stop_sequence": None, + "usage": {"input_tokens": 10, "output_tokens": 5}} + if body.get("stream"): + return StreamingResponse(sse(msg), media_type="text/event-stream") + return JSONResponse(msg) + + @app.api_route("/{path:path}", methods=["GET", "POST", "HEAD"]) + async def other(path: str, req: Request): + sql(LIVE, "insert into model_call(episode, path, kind, has_tools) values (%s, %s, 'other', false)", + (req.headers.get("x-episode-id"), "/" + path)) + return JSONResponse({"error": "not in the trial"}, status_code=404) + return app + + +class ClaudeCodeAdapter(AgenticHarnessAdapter): + """RFC 005's adapter for Claude Code (none ships with openenv 0.12.0): one `claude -p` per turn, resumed by + session id; its own tools off (`--tools ""`), only the environment's tools over the bridge (`--mcp-config`, + `--strict-mcp-config`); model calls to ANTHROPIC_BASE_URL with the episode id in a header.""" + BUILTIN_TOOL_NAMES = frozenset({"Bash", "Read", "Edit", "Write", "Glob", "Grep", "WebFetch", "WebSearch", "Task"}) + + def __init__(self, config: HarnessConfig, base_url: str): + super().__init__(config) + self.base_url, self.episode_id, self.session = base_url, None, None + self.home = self.mcp_file = None + + async def inject_tools(self, tools, bridge_url=None): + self.home = tempfile.mkdtemp(prefix="cc-") + self.mcp_file = os.path.join(self.home, "mcp.json") + with open(self.mcp_file, "w") as f: + json.dump({"mcpServers": {"env": {"type": "http", "url": bridge_url}}}, f) + + async def start(self, working_directory): + self.session = str(uuid.uuid4()) + self.turns = 0 + + async def stop(self): + if self.home: + shutil.rmtree(self.home, ignore_errors=True) + self.home = None + + async def is_alive(self): + return self.home is not None + + async def send_message_streaming(self, message: str) -> AsyncIterator[HarnessEvent]: + env = {**{k: v for k, v in os.environ.items() if k not in ("POSTGRES_PASSWORD",)}, + "HOME": self.home, "ANTHROPIC_BASE_URL": self.base_url, "ANTHROPIC_API_KEY": "trial", + "ANTHROPIC_CUSTOM_HEADERS": f"X-Episode-Id: {self.episode_id}", "DISABLE_AUTOUPDATER": "1", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"} + cmd = ["claude", "-p", message, "--bare", "--output-format", "stream-json", "--verbose", "--tools", "", + "--mcp-config", self.mcp_file, "--strict-mcp-config", "--allowedTools", "mcp__env__*", + "--model", self.config.model or "claude-haiku-5-5", "--max-turns", "4"] + cmd += ["--resume", self.session] if self.turns else ["--session-id", self.session] + self.turns += 1 + proc = await asyncio.create_subprocess_exec(*cmd, env=env, cwd=self.home, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + final, err = "", "" + async for raw in proc.stdout: + try: + ev = json.loads(raw) + except ValueError: + continue + if ev.get("type") == "assistant": + for b in ev["message"]["content"]: + if b["type"] == "tool_use": + yield HarnessEvent(type=HarnessEventType.TOOL_CALL, data={"name": b["name"], "input": b["input"]}) + elif b["type"] == "text": + yield HarnessEvent(type=HarnessEventType.TEXT_OUTPUT, data={"text": b["text"]}) + elif ev.get("type") == "user": + for b in ev["message"]["content"]: + if isinstance(b, dict) and b.get("type") == "tool_result": + yield HarnessEvent(type=HarnessEventType.TOOL_RESULT, data={"content": b.get("content")}) + elif ev.get("type") == "result": + final = ev.get("result", "") or "" + err = "" if not ev.get("is_error") else str(ev.get("subtype")) + await proc.wait() + if proc.returncode and not final: + err = err or (await proc.stderr.read()).decode()[-400:] + if err: + yield HarnessEvent(type=HarnessEventType.ERROR, data={"error": err}) + yield HarnessEvent(type=HarnessEventType.TURN_COMPLETE, data={"response": final, "done": True}) + + +class NoteWritten(Rubric): + """1.0 when the episode's note is in the database.""" + def __init__(self, env): + super().__init__() + self.env = env + + def forward(self, action, observation) -> float: + n = sql(LIVE, "select count(*) from note where episode = %s", (self.env.state.episode_id,), fetch=True)[0][0] + return 1.0 if n else 0.0 + + +class ClaudeCodeNotesEnv(HarnessEnvironment): + """The harness environment: Claude Code is the agent, the notes tools are its only tools.""" + def __init__(self, base_url: str): + mcp = FastMCP("notes") + env = self + + @mcp.tool + def note_add(body: str) -> str: + """Add a note to the shared notebook.""" + (nid,), = sql(LIVE, "insert into note(session, episode, body) values ('claude-code', %s, %s) returning id", + (env.state.episode_id, body), fetch=True) + return f"noted #{nid}" + + super().__init__(ClaudeCodeAdapter(HarnessConfig(name="claude-code", command=["claude"], + working_directory="/tmp"), base_url), mcp=mcp) + self.rubric = NoteWritten(self) + + async def reset_async(self, seed=None, episode_id=None, **kw): + self.adapter.episode_id = episode_id = episode_id or uuid.uuid4().hex + return await super().reset_async(seed=seed, episode_id=episode_id, **kw) + + +async def p47(): + sql(LIVE, "truncate model_call, outcome") + srv = serve(proxy_app(), 8766) + + def attach(rubric, action, observation, score): + # point 7: the rubric's score becomes the outcome of every model call of the episode, afterwards + sql(LIVE, "insert into outcome(episode, score) values (%s, %s) on conflict (episode) do update set " + "score = excluded.score", (rubric.env.state.episode_id, score)) + try: + env = ClaudeCodeNotesEnv("http://127.0.0.1:8766") + env.rubric.register_forward_hook(attach) + obs = await env.reset_async() + ep = obs.metadata["episode_id"] + step = await env.step_async(HarnessAction(message="Write a note saying hello, then tell me you did.")) + await env.close_async() if hasattr(env, "close_async") else env.close() + finally: + srv.should_exit = True + md = step.metadata or {} + events = md.get("turn_events") or [] + kinds = [e.get("type") if isinstance(e, dict) else str(e) for e in events] + calls = sql(LIVE, "select path, kind, has_tools, episode from model_call order by id", fetch=True) + notes = sql(LIVE, "select body from note where episode = %s", (ep,), fetch=True) + tool_calls = [k for k in kinds if "tool_call" in k] + response = md.get("response") or getattr(step, "response", None) or "" + result(4, bool(notes), f"Claude Code 2.1.311 ran as an OpenEnv HarnessEnvironment turn through a 90-line " + f"AgenticHarnessAdapter (openenv ships none for Claude Code), its own tools off, and called the env's " + f"tool over OpenEnv's loopback MCP bridge: notes written {len(notes)}; events {kinds}", + injected=obs.metadata.get("injected_tools"), stderr_or_error=[e for e in events if 'error' in str(e)][:2]) + msgs = [c for c in calls if c[0] == "/v1/messages"] + tagged = [c for c in msgs if c[3] == ep] + result(5, bool(msgs) and len(tagged) == len(msgs), f"ANTHROPIC_BASE_URL sent all {len(msgs)} /v1/messages " + f"calls to the proxy; {len(tagged)} carried the episode id in X-Episode-Id (ANTHROPIC_CUSTOM_HEADERS); " + f"other paths: {sorted({c[0] for c in calls if c[0] != '/v1/messages'})}", + calls=[list(c[:3]) for c in calls]) + kinds_sent = [c[1] for c in msgs] + result(6, "tool_use" in kinds_sent and bool(notes) and "note is in" in str(response) + str(md), + f"the proxy answered with no model: a tool_use block (streamed) that Claude Code executed against the env " + f"(note written), then final text that ended the turn: response {response!r}", sent=kinds_sent, + step_reward=step.reward) + rows = sql(LIVE, "select count(*), count(o.score), min(o.score) from model_call m left join outcome o " + "using (episode) where m.episode = %s", (ep,), fetch=True)[0] + result(7, rows[0] > 0 and rows[0] == rows[1], f"the rubric (NoteWritten, score {rows[2]}) ran at step's end; " + f"a forward hook wrote it as the episode's outcome; {rows[1]}/{rows[0]} of the episode's model calls " + f"join to it by episode id (as env.outcome does, S-183)", episode=ep) + + +def facts(): + import importlib.metadata as md + import mcp.types as t + print(json.dumps({"point": "mcp", "openenv": md.version("openenv"), "mcp": md.version("mcp"), + "fastmcp": md.version("fastmcp"), "mcp_latest_protocol": t.LATEST_PROTOCOL_VERSION, + "task_status_input_required": hasattr(t, "TASK_STATUS_INPUT_REQUIRED"), + "mrtr_resultType": "resultType" in open(t.__file__).read()}), flush=True) + + +if __name__ == "__main__": + what = sys.argv[1] if len(sys.argv) > 1 else "all" + setup() + try: + if what in ("all", "facts"): + facts() + if what in ("all", "p1", "p2"): + asyncio.run(p1_p2()) + if what in ("all", "p3"): + p3() + if what in ("all", "p47"): + asyncio.run(p47()) + finally: + teardown() diff --git a/scripts/trials/voice-route/cases.json b/scripts/trials/voice-route/cases.json new file mode 100644 index 0000000..dee5704 --- /dev/null +++ b/scripts/trials/voice-route/cases.json @@ -0,0 +1,50 @@ +[ + { + "text": "Good morning! How did you sleep?", + "route": "talk" + }, + { + "text": "What's a good name for a cat?", + "route": "talk" + }, + { + "text": "Name three planets, quickly.", + "route": "talk" + }, + { + "text": "Tell me a short joke.", + "route": "talk" + }, + { + "text": "How do you say thank you in French?", + "route": "talk" + }, + { + "text": "I'm feeling a bit tired today.", + "route": "talk" + }, + { + "text": "Check how much free disk space my computer has.", + "route": "work" + }, + { + "text": "Find the latest news about the Mars mission.", + "route": "work" + }, + { + "text": "Read my notes file and summarise it.", + "route": "work" + }, + { + "text": "Write a plan for moving my photos to the new drive.", + "route": "work" + }, + { + "text": "Save a note that I need to buy milk.", + "route": "work" + }, + { + "text": "What's in my downloads folder?", + "route": "work" + } +] \ No newline at end of file diff --git a/scripts/trials/voice-route/trial.py b/scripts/trials/voice-route/trial.py new file mode 100644 index 0000000..8b8f20b --- /dev/null +++ b/scripts/trials/voice-route/trial.py @@ -0,0 +1,31 @@ +"""The voice router's trial (S-170, S-171): the fast model's first tool on the held-out utterances in cases.json (never +used to write the prompt or the seed), twice, plus five requests it might wrongly say it cannot do. The first tool +counts as talk when it is talk or a quick fact on the way to talking (lookup, calculate), and as work when it does +something (delegate, save_note, read_notes, remind, search). Run in the voice head's container: + + podman exec -i -e CASES_JSON="$(cat scripts/trials/voice-route/cases.json)" substrate-voice-1 python3 - < scripts/trials/voice-route/trial.py + +2026-11-22, LFM3 1.7B Q6_K on llama.cpp b12627. Talk, delegate and save_note only (S-170): held-out 12/12 twice. +With the quick tools (S-171): held-out 11/12 twice (median 0.38 s, 0.60 s; "Name three planets" searched first); +the five extra cases 5/5 twice (disk space and "Is the stack running?" delegated, notes questions read_notes). +""" +import json, os, sys, time, urllib.request +sys.path.insert(0, "/app") +from voice import route +GW, KEY = "http://gateway:8080", os.environ["VOICE_KEY"] +cases = [(c["text"], c["route"]) for c in json.loads(os.environ["CASES_JSON"])] +extra = [("How many files are in your workspace notes folder?", "work"), ("Is the stack running?", "work"), ("What did I ask you to remember?", "work"), ("Check how much free disk space my computer has.", "work"), ("Hi! What's a fun fact about honeybees?", "talk")] +for name, cs in (("held-out", cases), ("can't-cases", extra)): + for run in (1, 2): + ok, ts, bad = 0, [], [] + for u, want in cs: + body = route.tools_body("fast/fast", [], u, "Sunday 22 November 2026, 12:00 (PST)") + r = urllib.request.Request(f"{GW}/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json", "x-bf-vk": KEY}) + t = time.perf_counter(); m = json.load(urllib.request.urlopen(r, timeout=60))["choices"][0]["message"]; ts.append(time.perf_counter() - t) + tool, arg = route.tools_decision(m) + # the first tool: talking, or a quick fact on the way to talking, is talk; anything that does something is work + got = "talk" if tool in ("talk", "lookup", "calculate") else "work" if tool in ("delegate", "save_note", "read_notes", "remind", "search") else "none" + ok += got == want + if got != want: bad.append(f"{u!r} -> {tool}: {arg[:50]!r}") + elif tool not in ("talk", "delegate"): bad.append(f"(ok) {u!r} -> {tool}") + ts.sort(); print(f"{name} run {run}: {ok}/{len(cs)}, median {ts[len(ts)//2]:.2f}s", *bad, sep="\n ") diff --git a/voice/route.py b/voice/route.py new file mode 100644 index 0000000..7f43044 --- /dev/null +++ b/voice/route.py @@ -0,0 +1,232 @@ +"""The voice head's router (S-170): does what the owner said need work, or can it be answered by talking? + +Two ways, chosen by VOICE_ROUTER: `tools` (the default, at the end of this file) lets the fast model decide by the tool +it calls each turn; `embed` (the Router class) decides by a vote over example embeddings, a first pass for later. + +"talk" goes to the fast model, which answers at once; "work" goes to the worker's queue (the slow local model, with +tools), and its answer is read out when it comes. The 1.7B fast model could not make this call itself (S-169: it +handed over everything, or with a constrained answer missed a quarter of the jobs); a nearest-example vote over +embeddings made it on the same utterances, in about 65 ms on the CPU. Examples are the seed below plus every +`voice.route.example` signal ({"text": ..., "route": "talk" | "work"}): a correction is one more example. + +Standard library only; the embedder is passed in (the voice head's goes through the gateway). +""" +from __future__ import annotations + +import json +import math +import re +from typing import Callable + +ROUTES = ("talk", "work") +# A prefix in the embedding model's instruction format (Qwen3-Embedding: "Instruct: ...\nQuery: "). +INSTRUCT = ("Instruct: Classify whether this spoken request needs tools (computer, files, saving, web) or can be " + "answered by talking\nQuery: ") +SEED = [ + ("Hi there, what's up?", "talk"), ("How are you feeling today?", "talk"), ("That's funny, thanks!", "talk"), + ("I had a long day at work.", "talk"), ("Can you cheer me up?", "talk"), ("Good night!", "talk"), + ("What's the capital of Spain?", "talk"), ("How many legs does a spider have?", "talk"), + ("What does photosynthesis mean?", "talk"), ("Give me a tip for sleeping better.", "talk"), + ("How should I start learning the guitar?", "talk"), ("Say something nice.", "talk"), + ("What's the difference between a frog and a toad?", "talk"), ("Do you like music?", "talk"), + ("Open my calendar and see what's on Friday.", "work"), ("Remember that my sister's birthday is in June.", "work"), + ("Search for cheap flights to Lisbon.", "work"), ("Draft an email to my landlord about the heating.", "work"), + ("Look through my project folder and tell me what's unfinished.", "work"), ("Delete the old logs on my machine.", "work"), + ("Is my backup still running?", "work"), ("Make a to-do list for the weekend and save it.", "work"), + ("What's the weather forecast for tomorrow?", "work"), ("Run the tests and tell me what failed.", "work"), + ("How much memory is the computer using?", "work"), ("Write me a one-page report on solar panels.", "work"), + ("Add eggs to my shopping list.", "work"), ("Which files did I change today?", "work"), +] + +Embed = Callable[[list[str]], list[list[float]]] + + +def _unit(v: list[float]) -> list[float]: + n = math.sqrt(sum(x * x for x in v)) or 1.0 + return [x / n for x in v] + + +class Router: + """k nearest examples by cosine similarity; the majority route wins (k odd, so no ties).""" + + def __init__(self, embed: Embed, examples: list[tuple[str, str]] | None = None, k: int = 3): + self.embed, self.k = embed, k + self.examples: list[tuple[str, str]] = [] + self.vectors: list[list[float]] = [] + self.set_examples(examples if examples is not None else SEED) + + def set_examples(self, examples: list[tuple[str, str]]) -> None: + examples = [(t.strip(), r) for t, r in examples if r in ROUTES and t and t.strip()] + if not examples: + raise ValueError("a router needs examples") + vectors = [_unit(v) for v in self.embed([INSTRUCT + t for t, _ in examples])] + self.examples, self.vectors = examples, vectors + + def route(self, text: str) -> tuple[str, dict]: + """The route, and what decided it: the nearest examples with their similarity.""" + v = _unit(self.embed([INSTRUCT + text])[0]) + sims = sorted(((sum(a * b for a, b in zip(v, u)), i) for i, u in enumerate(self.vectors)), reverse=True) + near = [(round(s, 3), *self.examples[i]) for s, i in sims[:self.k]] + work = sum(1 for _, _, r in near if r == "work") + route = "work" if work * 2 > len(near) else "talk" + return route, {"near": [{"similarity": s, "text": t, "route": r} for s, t, r in near]} + + +# ---- the fast model decides, by the tool it calls (S-170, the owner's idea; S-171 adds quick tools): it is trained to +# call tools, so every step it must call one. talk ends the turn (spoken as it streams); delegate ends it too (the +# worker takes multi-step work); the quick tools (voice/tools.py) run in the voice head and their result comes back for +# the next step, at most QUICK_STEPS of them a turn, then only talk or delegate are offered. Measured on the trial's 12 +# held-out utterances with talk, delegate and save_note: 12/12 twice, median 0.35 s, with thinking off, +# tool_choice required, a stop at (with thinking off it sometimes writes plain words, then loops on that +# marker) and plain words taken as talk. Without save_note it said "Saved note: ..." for a note it had not saved. +QUICK_STEPS = 3 +TOOLS_SYSTEM = """You are the owner's companion, speaking with them out loud. It is {now}. Every step, call exactly one tool. +talk: say your answer, in one to three short spoken sentences (no lists, markdown, emoji or links). This ends your turn. +Quick tools, which you use yourself and then talk about the result: +- save_note: keep a short note, only when the owner asks you to keep, note, write down or save something. +- read_notes: read the owner's notes (what they asked you to remember), optionally about a topic. +- remind: set a reminder; give the time as YYYY-MM-DDTHH:MM in their local time, or as "in N minutes". +- calculate: work out arithmetic exactly. +- lookup: a fact from Wikipedia about a person, place, thing or idea. +- search: search the web for current things (news, prices, opening hours, weather, recent events). +delegate: hand the request to the assistant with more tools when it takes several steps, changes things, or needs a long +written plan or document. Anything about the computer (disk space, files and folders other than notes, programs, +settings, what is running) is always delegate: it is the computer you run on, so do not ask which one. Ends your turn. +Answer small talk, feelings, jokes, translations and simple advice yourself with talk. Never say you did something +unless a tool did it, and never say you cannot do something or have no tool for it: use a quick tool, or delegate. +Do not repeat the question back. What you hear is a speech-to-text transcript and may have small mistakes; if it +makes no sense, ask once.""" + + +def _fn(name: str, description: str, props: dict, required: list[str]) -> dict: + return {"type": "function", "function": {"name": name, "description": description, + "parameters": {"type": "object", "properties": props, "required": required}}} + + +_S = {"type": "string"} +TALK = _fn("talk", "Say this to the owner out loud; ends the turn", {"text": {"type": "string", "description": "spoken words only"}}, ["text"]) +DELEGATE = _fn("delegate", "Hand multi-step work to the assistant with more tools; ends the turn", + {"task": {"type": "string", "description": "the request, complete and self-contained"}}, ["task"]) +QUICK = [ + _fn("save_note", "Save a short note for the owner", {"text": _S}, ["text"]), + _fn("read_notes", "Read the owner's notes, optionally only those about a topic", {"topic": _S}, []), + _fn("remind", "Set a reminder", {"text": _S, "when": {"type": "string", "description": "YYYY-MM-DDTHH:MM local time, or 'in N minutes'"}}, ["text", "when"]), + _fn("calculate", "Work out an arithmetic expression", {"expression": _S}, ["expression"]), + _fn("lookup", "Look up a fact on Wikipedia", {"topic": _S}, ["topic"]), + _fn("search", "Search the web", {"query": _S}, ["query"]), +] +TOOLS = [TALK, DELEGATE] + QUICK +QUICK_NAMES = {t["function"]["name"] for t in QUICK} +ENDS = {"talk", "delegate"} + + +def tools_body(model: str, history: list[dict], utterance: str | None, now: str = "", steps: list[dict] | None = None, + final: bool = False, stream: bool = False) -> dict: + """The request for one step: the history, the utterance, the steps so far this turn (assistant tool calls and + their results); final offers only talk and delegate.""" + msgs = [{"role": "system", "content": TOOLS_SYSTEM.format(now=now or "unknown")}] + history + if utterance is not None: + msgs.append({"role": "user", "content": utterance}) + return {"model": model, "messages": msgs + (steps or []), "tools": [TALK, DELEGATE] if final else TOOLS, + "tool_choice": "required", "temperature": 0.2, "max_tokens": 300, "reasoning_effort": "none", + "stop": [""], "stream": stream} + + +def tools_decision(message: dict) -> tuple[str, str]: + """(tool, its main text) from a whole reply: talk or delegate, or a quick tool with its arguments as JSON. Plain words + with no tool call are talk; an unknown tool, bad arguments or nothing at all are ("", "").""" + calls = message.get("tool_calls") or [] + if not calls: + text = (message.get("content") or "").strip() + return ("talk", text) if text else ("", "") + f = calls[0].get("function") or {} + try: + args = json.loads(f.get("arguments") or "{}") + except ValueError: + return "", "" + name = f.get("name") + if not isinstance(args, dict) or name not in ENDS | QUICK_NAMES: + return "", "" + if name in QUICK_NAMES: + return name, json.dumps(args) + text = args.get("task" if name == "delegate" else "text") + return (name, text.strip()) if isinstance(text, str) and text.strip() else ("", "") + + +class TalkText: + """The value of "text" in a talk call's arguments, read as the arguments stream in: feed() returns what is new. + JSON string escapes are decoded; a \\u escape split across chunks waits for its four digits.""" + + def __init__(self): + self.buf, self.pos, self.inside, self.done = "", 0, False, False + + def feed(self, chunk: str) -> str: + self.buf += chunk + out = [] + if not self.inside and not self.done: + m = re.search(r'"text"\s*:\s*"', self.buf) + if not m: + return "" + self.inside, self.pos = True, m.end() + while self.inside and self.pos < len(self.buf): + c = self.buf[self.pos] + if c == '"': + self.inside, self.done = False, True + self.pos += 1 + break + if c == "\\": + if self.pos + 1 >= len(self.buf): + break + e = self.buf[self.pos + 1] + if e == "u": + if self.pos + 6 > len(self.buf): + break + try: + out.append(chr(int(self.buf[self.pos + 2:self.pos + 6], 16))) + except ValueError: + pass + self.pos += 6 + continue + out.append({"n": "\n", "t": "\t", "r": "", "b": "", "f": ""}.get(e, e)) + self.pos += 2 + continue + out.append(c) + self.pos += 1 + return "".join(out) + + +def stream_events(lines): + """OpenAI chat-completion stream lines -> ("content", text) and ("tool", index, id, name, arguments-delta) events.""" + for line in lines: + line = line.decode("utf-8", "replace").strip() if isinstance(line, bytes) else line.strip() + if not line.startswith("data:"): + continue + data = line[5:].strip() + if data == "[DONE]": + return + try: + delta = json.loads(data)["choices"][0].get("delta") or {} + except (ValueError, KeyError, IndexError): + continue + if delta.get("content"): + yield ("content", delta["content"]) + for tc in delta.get("tool_calls") or []: + f = tc.get("function") or {} + yield ("tool", tc.get("index", 0), tc.get("id"), f.get("name"), f.get("arguments") or "") + + +_EMOJI = re.compile("[\U0001F300-\U0001FAFF\u2600-\u27BF\uFE0F\u200B-\u200D\u2060]") + + +def speakable(text: str) -> str: + """Text fit for speech: markdown emphasis, headings, code marks, list marks and emoji removed (the model sometimes + writes them in a talk call anyway).""" + t = _EMOJI.sub("", text or "") + t = re.sub(r"(?m)^\s*(?:[-*•]|\d+[.)])\s+", "", t) + t = re.sub(r"[*_`#]+", "", t) + return re.sub(r"\s+", " ", t).strip() + + +def note_name(text: str) -> str: + from voice import tools + return tools.note_name(text) diff --git a/voice/server.py b/voice/server.py index 3597432..cc7e3e4 100644 --- a/voice/server.py +++ b/voice/server.py @@ -20,6 +20,7 @@ from __future__ import annotations import asyncio +import datetime as dt import json import mimetypes import os @@ -36,14 +37,24 @@ from websockets.datastructures import Headers from websockets.http11 import Response -from voice import reply +from voice import reply, route, tools ROOT = Path(__file__).resolve().parent STATIC = ROOT / "static" MODELS = Path(os.environ.get("VOICE_MODELS") or "/models") GATEWAY = os.environ.get("GATEWAY_URL", "http://gateway:8080") -LLM = os.environ.get("LLM_NAME") or "local/gemma" +LLM = os.environ.get("LLM_NAME") or "local/slow" KEY = os.environ.get("VOICE_KEY", "") +# the router (S-170): tools (the default): LLM calls talk, delegate or save_note each turn; embed: an embedding vote +# decides talk or work first; off: LLM's reply component decides with its HANDOFF line (to the companion), as before +ROUTER = (os.environ.get("VOICE_ROUTER") or "tools").strip() +NOTED = "Noted." +NOTES_ROOT = os.environ.get("VOICE_NOTES_ROOT") or "/workspace" # the worker's workspace: notes/.txt (S-171) +SEARCH_URL = os.environ.get("SEARCH_URL", "") # the local SearXNG (compose service search) +EMBED_MODEL = os.environ.get("EMBED_MODEL") or "ollama/qwen3-embedding:0.6b" +ON_IT = "On it. I'll tell you when it's done." +WORKER_SAYS = ("Say this result to the owner out loud in one to three short spoken sentences: plain words, no lists, " + "markdown, file paths read character by character, or code. Keep what matters; drop the rest.") THREADS = int(os.environ.get("VOICE_THREADS") or 4) VOICE = os.environ.get("VOICE_STYLE") or "af_heart" TTS_URL = os.environ.get("TTS_URL", "").rstrip("/") @@ -193,6 +204,49 @@ def reply_component(self) -> tuple[int | None, dict]: self._card_at = now return self._card + def route_examples(self) -> tuple[int, list[tuple[str, str]]]: + """The owner's corrections (voice.route.example signals) after the seed: (the last one's id, the examples).""" + try: + rows = self.conn().execute("select id, body->>'text', body->>'route' from env.signal where key = 'voice.route.example' " + "order by id").fetchall() + return (rows[-1][0] if rows else 0), [(t, r) for _, t, r in rows if t and r in route.ROUTES] + except psycopg.Error as e: + log(f"record: {e}") + self.c = None + return -1, [] + + def worker_done_after(self, last: int) -> list[tuple[int, str, bool]]: + """The worker's finished tasks that the voice head asked for: reply_to voice, or voice:quiet when it failed + (a saved note is confirmed at once with "Noted"; only a failure is read out).""" + try: + return self.conn().execute("select id, body->>'text', coalesce((body->>'ok')::boolean, false) from env.signal " + "where key = 'worker.task.done' and id > %s and (body->>'reply_to' = 'voice' or " + "(body->>'reply_to' = 'voice:quiet' and not coalesce((body->>'ok')::boolean, false))) " + "order by id", (last,)).fetchall() + except psycopg.Error as e: + log(f"record: {e}") + self.c = None + return [] + + def last_worker_done(self) -> int: + try: + return self.conn().execute("select coalesce(max(id), 0) from env.signal where key = 'worker.task.done'").fetchone()[0] + except psycopg.Error: + self.c = None + return 0 + + def due_reminders(self) -> list[tuple[int, str]]: + """Reminders whose time has come and that have not been said (voice.reminder.said names them).""" + try: + return self.conn().execute( + "select r.id, r.body->>'text' from env.signal r where r.key = 'voice.reminder' " + "and (r.body->>'due')::timestamptz <= now() and not exists (select 1 from env.signal s " + "where s.key = 'voice.reminder.said' and (s.body->>'reminder')::bigint = r.id) order by r.id").fetchall() + except psycopg.Error as e: + log(f"record: {e}") + self.c = None + return [] + def last_reply(self) -> int: try: return self.conn().execute("select coalesce(max(id), 0) from env.action where actuator = 'companion.reply'").fetchone()[0] @@ -249,6 +303,11 @@ async def respond(self, seg: np.ndarray): return await self.state("listening") await self.send({"type": "heard", "text": text}) heard = self.rec.publish("companion.voice.heard", {"text": text, "audio_s": round(len(seg) / 16000, 2), "stt_ms": stt_ms}, "owner (voice)") + if ROUTER == "tools": + return await self.tools_turn(text, heard, stt_ms, t0) + decided, why = await asyncio.to_thread(ROUTE.decide, text) + if decided == "work": + return await self.hand_to_worker(text, heard, stt_ms, why, t0) comp_id, card = await asyncio.to_thread(self.rec.reply_component) prior = list(self.history) self.history.append({"role": "user", "content": text}) @@ -300,8 +359,12 @@ def pump(): "interrupted": True, "stt_ms": stt_ms, "first_audio_ms": first_ms}, "voice head") raise spoken = " ".join(said) + dropped = None + if decided == "talk" and handoff is not None: # the router said talk: the model's hand-over is not sent + dropped, handoff = (handoff.strip() or None), None self.history.append({"role": "assistant", "content": spoken + (f"\nHANDOFF: {handoff.strip()}" if handoff else "")}) self.rec.publish("companion.voice.said", {"text": spoken, "by": LLM, "heard": heard, "component": comp_id, + "route": decided, "routed_by": why, "handoff_dropped": dropped, "handoff": (handoff or "").strip() or None, "stt_ms": stt_ms, "first_audio_ms": first_ms, "turn_ms": round((time.perf_counter() - t0) * 1000)}, "voice head") @@ -311,6 +374,166 @@ def pump(): await self.send({"type": "say", "text": f"handed to the companion: {handoff.strip()}", "by": "voice head"}) await self.state("listening") + async def tools_turn(self, text: str, heard, stt_ms: int, t0: float): + """One turn decided by the tools the voice model calls (S-170, S-171). Each step streams: a talk call's text is + spoken sentence by sentence as it arrives; a quick tool runs here and its result goes back for the next step (at + most route.QUICK_STEPS, then only talk and delegate are offered); delegate sends the task to the worker.""" + now = dt.datetime.now().astimezone() + steps: list[dict] = [] + said: list = [] + used: list[dict] = [] + first_ms = None + tool, arg = "", "" + for n in range(route.QUICK_STEPS + 1): + body = route.tools_body(LLM, self.history[-20:], text, f"{now:%A %-d %B %Y, %H:%M} ({now.tzname()})", steps, + final=n == route.QUICK_STEPS, stream=True) + try: + tool, arg, call_id, spoke = await self.stream_step(body, said) + except Exception as e: # noqa: BLE001 - reported, and the turn ends + await self.send({"type": "error", "text": f"the voice model: {e}"}) + break + if spoke and first_ms is None: + first_ms = round((time.perf_counter() - t0) * 1000) + if tool in route.ENDS or not tool: + break + result = await asyncio.to_thread(self.quick, tool, arg, now) + used.append({"tool": tool, "args": arg, "result": result[:300]}) + steps += [{"role": "assistant", "content": None, "tool_calls": [{"id": call_id, "type": "function", + "function": {"name": tool, "arguments": arg}}]}, + {"role": "tool", "tool_call_id": call_id, "content": result}] + if tool == "delegate": + self.rec.publish("worker.owner.message", {"text": arg, "said": text, "reply_to": "voice"}, "owner (voice)") + await self.say(ON_IT, said) + elif not said: + await self.say("Sorry, could you say that again?", said) + if first_ms is None: + first_ms = round((time.perf_counter() - t0) * 1000) + spoken = " ".join(said) + self.history.append({"role": "user", "content": text}) + # only what was said: tool results written into the history were copied into later replies, "(calculate: ...)" + self.history.append({"role": "assistant", "content": spoken}) + self.rec.publish("companion.voice.said", {"text": spoken, "by": LLM, "heard": heard, "route": tool or None, "routed_by": "tools", + "quick_tools": used, "task": arg if tool == "delegate" else None, "stt_ms": stt_ms, + "first_audio_ms": first_ms, "turn_ms": round((time.perf_counter() - t0) * 1000)}, + "voice head") + await self.state("listening") + + async def stream_step(self, body: dict, said: list) -> tuple[str, str, str, bool]: + """One streamed step: (tool, its text or JSON arguments, the call's id, whether anything was spoken). A talk + call's text (or plain words with no call) is spoken as each sentence completes.""" + req = urllib.request.Request(f"{GATEWAY}/v1/chat/completions", json.dumps(body).encode(), + {"Content-Type": "application/json", "x-bf-vk": KEY, "x-wb-call": f"voice-{time.time_ns()}"}) + q: asyncio.Queue = asyncio.Queue() + loop = asyncio.get_running_loop() + + def pump(): + try: + with urllib.request.urlopen(req, timeout=60) as r: + for ev in route.stream_events(r): + loop.call_soon_threadsafe(q.put_nowait, ev) + except Exception as e: # noqa: BLE001 - raised in the turn + loop.call_soon_threadsafe(q.put_nowait, ("error", e)) + loop.call_soon_threadsafe(q.put_nowait, None) + loop.run_in_executor(None, pump) + name, call_id, args, content, buf, spoke = None, "", "", "", "", False + talk = route.TalkText() + while (ev := await q.get()) is not None: + if ev[0] == "error": + raise ev[1] + new = "" + if ev[0] == "content" and name is None: + content += ev[1] + new = ev[1] + elif ev[0] == "tool" and ev[1] == 0: + name = name or ev[3] + call_id = call_id or ev[2] or f"call-{time.time_ns()}" + args += ev[4] + if name == "talk": + new = talk.feed(ev[4]) + if new: + buf += new + while m := SENTENCE.match(buf): + sentence, buf = route.speakable(m.group(1)), buf[m.end():] + if sentence: + await self.say(sentence, said) + spoke = True + if name in (None, "talk") and route.speakable(buf): + await self.say(route.speakable(buf), said) + spoke = True + if name is None: + return ("talk", content.strip(), "", spoke) if content.strip() else ("", "", "", spoke) + tool, arg = route.tools_decision({"tool_calls": [{"function": {"name": name, "arguments": args}}]}) + return tool, arg, call_id, spoke + + def quick(self, tool: str, arg: str, now: dt.datetime) -> str: + """A quick tool, run here (voice/tools.py); its result goes back to the model.""" + a = json.loads(arg or "{}") + try: + if tool == "save_note": + return tools.save_note(NOTES_ROOT, a.get("text", "")) + if tool == "read_notes": + return tools.read_notes(NOTES_ROOT, a.get("topic", "")) + if tool == "remind": + result, r = tools.remind(a.get("text", ""), a.get("when", ""), now) + if r: + self.rec.publish("voice.reminder", r, "owner (voice)") + return result + if tool == "calculate": + return tools.calculate(a.get("expression", "")) + if tool == "lookup": + return tools.lookup(a.get("topic", "")) + if tool == "search": + return tools.search(a.get("query", ""), SEARCH_URL) + except OSError as e: + return f"error: {e}" + return f"error: no tool {tool}" + + async def speak_reminder(self, text: str): + while self.hearing or (self.turn and not self.turn.done()): + await asyncio.sleep(0.3) + line = f"A reminder: {text}" + await self.send({"type": "say", "text": line, "by": "reminder"}) + pcm = await asyncio.to_thread(self.m.speak, line) + await self.send({"type": "audio", "rate": 24000}, pcm) + self.history.append({"role": "assistant", "content": line}) + + async def hand_to_worker(self, text: str, heard, stt_ms: int, why: dict, t0: float): + """Work: say so at once, and put the request on the worker's queue; its answer is read out when it comes.""" + said: list = [] + self.rec.publish("worker.owner.message", {"text": text, "reply_to": "voice"}, "owner (voice)") + await self.say(ON_IT, said) + first_ms = round((time.perf_counter() - t0) * 1000) + self.history.append({"role": "user", "content": text}) + self.history.append({"role": "assistant", "content": ON_IT + " (handed to the worker)"}) + self.rec.publish("companion.voice.said", {"text": ON_IT, "by": "voice head", "heard": heard, "route": "work", + "routed_by": why, "to": "worker", "stt_ms": stt_ms, "first_audio_ms": first_ms}, + "voice head") + await self.state("listening") + + async def speak_worker(self, text: str, ok: bool): + """The worker's answer, condensed by the voice model into a few spoken sentences and read out in a quiet moment.""" + while self.hearing or (self.turn and not self.turn.done()): + await asyncio.sleep(0.3) + if not (text or "").strip(): + text, ok = "The task finished with no answer.", False + card = {"params": {"system": WORKER_SAYS, "temperature": 0.3, "max_tokens": 200, "reasoning_effort": "none", + "history_turns": 0}} + try: + spoken = "".join(await asyncio.to_thread(lambda: list(reply.stream(card, [], text, GATEWAY, KEY, LLM)))).strip() + spoken = reply.split(spoken)[0] or spoken + except Exception as e: # noqa: BLE001 - the answer is read as it is + log(f"condensing the worker's answer: {e}") + spoken = " ".join(sentences(text)[:3]) + spoken = re.sub(r"[`*_#]+", "", spoken).strip() # markdown the model kept would be read out + if not ok: + spoken = "The task did not finish. " + spoken + self.history.append({"role": "assistant", "content": f"(the worker's answer) {spoken}"}) + await self.send({"type": "say", "text": spoken, "by": "worker"}) + for sentence in sentences(spoken) or [spoken]: + pcm = await asyncio.to_thread(self.m.speak, sentence) + await self.send({"type": "audio", "rate": 24000}, pcm) + self.rec.publish("companion.voice.said", {"text": spoken, "by": "worker", "condensed_from": text[:2000]}, "voice head") + async def say(self, sentence: str, said: list): said.append(sentence) await self.state("speaking") @@ -350,6 +573,73 @@ def once(): await asyncio.sleep(15) +class Route: + """The router as the voice head runs it: built once its embeddings answer, rebuilt when the owner adds an example. + decide() returns (None, {}) when routing is off or not ready, and the model's own HANDOFF line decides, as before.""" + + def __init__(self): + self.router, self.seen = None, None + + def embed(self, texts: list[str]) -> list[list[float]]: + body = json.dumps({"model": EMBED_MODEL, "input": texts}).encode() + req = urllib.request.Request(f"{GATEWAY}/v1/embeddings", body, {"Content-Type": "application/json", "x-bf-vk": KEY}) + with urllib.request.urlopen(req, timeout=30) as r: + return [d["embedding"] for d in sorted(json.load(r)["data"], key=lambda d: d["index"])] + + def refresh(self, record: Record) -> None: + last, extra = record.route_examples() + if last < 0 or (self.router is not None and last == self.seen): + return + self.router = route.Router(self.embed, route.SEED + extra) + self.seen = last + log(f"router: {len(route.SEED)} seed and {len(extra)} owner examples") + + def decide(self, text: str) -> tuple[str | None, dict]: + if ROUTER != "embed" or self.router is None: + return None, {} + try: + t = time.perf_counter() + r, why = self.router.route(text) + return r, {**why, "ms": round((time.perf_counter() - t) * 1000)} + except Exception as e: # noqa: BLE001 - the model decides, as before + log(f"router: {e}") + return None, {"error": str(e)[:200]} + + +ROUTE = Route() + + +async def keep_router(record: Record): + while ROUTER == "embed": + try: + await asyncio.to_thread(ROUTE.refresh, record) + except Exception as e: # noqa: BLE001 - e.g. the embedding model not up yet + log(f"router not ready: {e}") + await asyncio.sleep(30 if ROUTE.router else 5) + + +async def worker_replies(record: Record): + last = await asyncio.to_thread(record.last_worker_done) + while True: + await asyncio.sleep(1) + for sid, text, ok in await asyncio.to_thread(record.worker_done_after, last): + last = sid + for s in list(SESSIONS): + asyncio.create_task(s.speak_worker(text or "", ok)) + + +async def reminders(record: Record): + """Say each reminder when it falls due, to whoever is listening; one with no page open waits for one.""" + while True: + await asyncio.sleep(10) + if not SESSIONS: + continue + for rid, text in await asyncio.to_thread(record.due_reminders): + for s in list(SESSIONS): + asyncio.create_task(s.speak_reminder(text or "")) + record.publish("voice.reminder.said", {"reminder": rid, "text": text}, "voice head") + + async def companion_replies(record: Record): last = await asyncio.to_thread(record.last_reply) while True: @@ -405,6 +695,9 @@ def process(conn, request): return None asyncio.create_task(companion_replies(record)) + asyncio.create_task(worker_replies(record)) + asyncio.create_task(reminders(record)) + asyncio.create_task(keep_router(record)) asyncio.create_task(warm()) host, port = os.environ.get("VOICE_HOST", "127.0.0.1"), int(os.environ.get("VOICE_PORT") or 8110) async with serve(handler, host, port, process_request=process, max_size=2**20): diff --git a/voice/tools.py b/voice/tools.py new file mode 100644 index 0000000..9eab23b --- /dev/null +++ b/voice/tools.py @@ -0,0 +1,151 @@ +"""The fast layer's quick tools (S-171): what the voice model does itself, in one step, without the worker. + +Each returns a short text for the model to read (the tool result), never raises for a bad argument (it says what was +wrong instead), and is quick: a file, a sum, one HTTP call with a short timeout. Multi-step work is the worker's +(`delegate`). Notes live in the worker's workspace (notes/.txt, as the example plan writes them), so both +read the same ones. Reminders are records (the voice head keeps them in the environment and says them when due). +""" +from __future__ import annotations + +import ast +import datetime as dt +import json +import operator +import re +import urllib.parse +import urllib.request +from pathlib import Path + +UA = "substrate-voice/0.1 (local assistant)" # Wikimedia asks for a descriptive User-Agent; nothing about the owner +MAX_RESULT = 1200 + + +def note_name(text: str) -> str: + """A file name for a note: its first few words, lower case, hyphenated (the example plan's [\\w-]+).""" + words = re.findall(r"[a-z0-9]+", text.lower())[:5] + return "-".join(words) or "note" + + +def save_note(root: str, text: str) -> str: + text = (text or "").strip() + if not text: + return "error: the note is empty" + d = Path(root) / "notes" + d.mkdir(parents=True, exist_ok=True) + base, n = note_name(text), 1 + f = d / f"{base}.txt" + while f.exists(): + n += 1 + f = d / f"{base}-{n}.txt" + f.write_text(text + "\n", encoding="utf-8") + return f"saved as notes/{f.name}" + + +def read_notes(root: str, query: str = "") -> str: + """The notes, newest first; with a query, only those containing one of its words.""" + d = Path(root) / "notes" + files = sorted(d.glob("*.txt"), key=lambda p: p.stat().st_mtime, reverse=True) if d.is_dir() else [] + words = [w for w in re.findall(r"[a-z0-9]+", (query or "").lower()) if len(w) > 2] + out = [] + for f in files: + body = f.read_text(encoding="utf-8", errors="replace").strip() + if words and not any(w in (f.stem + " " + body).lower() for w in words): + continue + out.append(f"{f.stem}: {body[:200]}") + if not out: + return "no notes" + (f" about {query}" if words else "") + return "\n".join(out)[:MAX_RESULT] + + +def parse_when(when: str, now: dt.datetime) -> dt.datetime | None: + """An ISO 8601 date-time (the model is given the current time), or 'in N minutes|hours|days'.""" + when = (when or "").strip() + m = re.fullmatch(r"in (\d+) (minute|hour|day)s?", when.lower()) + if m: + return now + dt.timedelta(**{m.group(2) + "s": int(m.group(1))}) + try: + t = dt.datetime.fromisoformat(when.replace("Z", "+00:00")) + except ValueError: + return None + return t if t.tzinfo else t.replace(tzinfo=now.tzinfo) + + +def remind(text: str, when: str, now: dt.datetime) -> tuple[str, dict | None]: + """(the result for the model, the reminder to keep or None).""" + text = (text or "").strip() + t = parse_when(when, now) + if not text: + return "error: the reminder has no text", None + if t is None: + return f"error: could not read the time {when!r}; give it as YYYY-MM-DDTHH:MM or 'in N minutes'", None + if t <= now: + return f"error: {t:%A %H:%M} has passed", None + return f"reminder set for {t:%A %-d %B at %H:%M}", {"text": text, "due": t.isoformat()} + + +_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, + ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod, ast.Pow: operator.pow, ast.USub: operator.neg, ast.UAdd: operator.pos} + + +def calculate(expression: str) -> str: + """Arithmetic only: numbers, + - * / // % ** and brackets (no names, no calls).""" + def ev(n): + if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)) and not isinstance(n.value, bool): + return n.value + if isinstance(n, ast.BinOp) and type(n.op) in _OPS: + a, b = ev(n.left), ev(n.right) + if isinstance(n.op, ast.Pow) and abs(b) > 100: + raise ValueError("exponent too large") + return _OPS[type(n.op)](a, b) + if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS: + return _OPS[type(n.op)](ev(n.operand)) + raise ValueError("only numbers and + - * / // % ** ( )") + try: + v = ev(ast.parse((expression or "").replace("^", "**").replace("×", "*").replace("÷", "/"), mode="eval").body) + except (SyntaxError, ValueError, ZeroDivisionError, OverflowError) as e: + return f"error: {e}" + if isinstance(v, float): + v = round(v, 10) + v = int(v) if v.is_integer() else v + return f"{expression} = {v}" + + +def _get(url: str, timeout: float = 6) -> dict: + req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"}) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.load(r) + + +def lookup(topic: str, get=_get) -> str: + """Wikipedia's summary of the best-matching article (English), with its title.""" + topic = (topic or "").strip() + if not topic: + return "error: nothing to look up" + try: + hits = get("https://en.wikipedia.org/w/rest.php/v1/search/page?" + urllib.parse.urlencode({"q": topic, "limit": 1})).get("pages") or [] + if not hits: + return f"Wikipedia has no article for {topic!r}" + s = get("https://en.wikipedia.org/api/rest_v1/page/summary/" + urllib.parse.quote(hits[0]["key"], safe="")) + except (OSError, ValueError, KeyError) as e: + return f"error: Wikipedia did not answer ({type(e).__name__})" + return f"Wikipedia, {s.get('title', hits[0].get('title'))}: {(s.get('extract') or '').strip()}"[:MAX_RESULT] + + +def search(query: str, base: str, get=_get) -> str: + """The top results from the local SearXNG (title, a snippet, the site), for the model to answer from.""" + query = (query or "").strip() + if not query: + return "error: nothing to search for" + if not base: + return "error: no search engine is set up (SEARCH_URL)" + try: + res = get(f"{base.rstrip('/')}/search?" + urllib.parse.urlencode({"q": query, "format": "json"}), timeout=8).get("results") or [] + except (OSError, ValueError) as e: + return f"error: the search did not answer ({type(e).__name__})" + if not res: + return f"no results for {query!r}" + out = [] + for r in res[:4]: + site = urllib.parse.urlparse(r.get("url") or "").netloc + out.append(f"- {(r.get('title') or '').strip()} ({site}): {(r.get('content') or '').strip()[:220]}") + return "\n".join(out)[:MAX_RESULT]