diff --git a/.env.example b/.env.example index ba54481..5c8bcb8 100644 --- a/.env.example +++ b/.env.example @@ -52,10 +52,11 @@ DESKTOP_PORT=8080 KERNEL_URL= # the kernel's secrets, generated once (deploy/secrets.txt) KK_AUTHENTICATOR_PASSWORD= -# the MCP router's and its connectors' logins to the kernel's database (S-205) +# the MCP router's, its connectors', the desktop's and the channel's logins to the kernel's database (S-205, S-206, S-220) MCP_ROUTER_DB_PASSWORD= MCP_CONNECTOR_DB_PASSWORD= MCP_DESKTOP_DB_PASSWORD= +MCP_CHANNEL_DB_PASSWORD= KK_JWT_SECRET= # OpenRouter models a caller may use (comma-separated names or regex:...); empty: free ones only GATEWAY_OPENROUTER_MODELS= diff --git a/CLAUDE.md b/CLAUDE.md index 33d9dac..50df1d6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,19 +16,20 @@ The projects (S-209, S-212; `docs/framework.md`, `docs/repos.md`): **Morphogen** (the default distribution), **MetaSoar** (the research). A part of Substrate is a kernel module only when it needs the kernel; otherwise it is an Agent Skill, an MCP server, a compose service or an outside service (S-213). Every dependency is a contract, never another project's code. 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, before the parts move** -(`docs/parts.md`). The old assistant was removed on 2026-11-23 (S-194); git keeps it. +`slow`, `cloud`), never by model. **The table below is what is in the tree today; the environment, the channel and the router are in their types +(S-219 to S-221), the rest moves as `docs/parts.md` says.** The old assistant was removed on 2026-11-23 (S-194); git keeps it. | 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 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) | -| 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 kernel's database `kernel` (S-202, the kernel's D-126: one database) | 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 real-time environment | `environment/`, a kernel module (S-219: `module.yaml`, `migration.sql`, installed by `scripts/kernel.sh init`; schema `env` in `environment/sql/`, migrated by `environment/db.py`; its service `environment/review.py`, compose `environment`) on pgmq, in the kernel's database `kernel` (S-202, the kernel's D-126: one database) | signals logged whole and fanned out as topics, a queue per actuator behind its gate (`free`, `propose`, `deny`); a proposed action waits in the kernel's review lane and is decided in the desktop's Review (S-219) | +| The channel | `environment/channel.py`, an MCP server (stdio) a harness starts, as its own login `mcp_channel` (S-220) | an environment queue pushed into a Claude Code session, archived only on `ack` (S-143); acting through the gates | | 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`; 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 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) | | The desktop | compose service `caddy` (`deploy/caddy/Caddyfile`, `deploy/caddy/apps.json`) on 127.0.0.1:8080 (`DESKTOP_PORT`), in front of the kernel's `kk serve`; its framed apps on 8081 (the gateway's dashboard) and 8082 (the map pages) | the kernel's UI shell as a desktop (the kernel's D-127): a launcher and windows for search, review, change sets, the graph, the view modules and framed apps, each app on an origin of its own with its headers rewritten in the proxy; MCP over HTTP at `/mcp`; a person signs in with `scripts/kernel.sh person NAME` (S-199, S-200) | -| The MCP router | `mcp-router/` (Go), compose services `mcp-router` (its endpoint and page, 127.0.0.1:8083 through Caddy) and one connector per server (`mcp-kernel`); its rules in `environment/sql/010_mcp.sql` | one MCP endpoint for agents and the desktop in front of every connected MCP server; each server and tool registered in the environment, each tool an actuator behind its gate, each call an action recorded and, when it changes the world, waiting for a person on the router's page (S-203, S-205) | +| The MCP router | `mcp-router/` (Go), compose services `mcp-router` (its endpoint and page, 127.0.0.1:8083 through Caddy) and one connector per server (`mcp-kernel`); its registry and rules in the environment module's schema (`environment/sql/010_mcp.sql` to `013`) | one MCP endpoint for agents and the desktop in front of every connected MCP server; each server and tool registered in the environment, each tool an actuator behind its gate, each call an action recorded and, when it changes the world, waiting for a person in the desktop's Review (S-203, S-205, S-219) | | The desktop and the assistant | `desktop/` (`server.py`; the Assistant view module, mounted into the kernel's container), compose services `desktop` and its connector `mcp-desktop`; `environment/sql/011_desktop.sql`; `scripts/assistant.sh` | the conversation between a person and the agents as signals: the person talks in the desktop's Assistant window, an agent (a Claude Code session started by `scripts/assistant.sh`) hears it on the channel and answers, shows and asks through the router (S-206) | | Images | `.github/workflows/images.yml`, `image_ref` in `scripts/lib.sh` | `ghcr.io/openreplicant/substrate-{db,tools}` and the kernel's image are pulled (tags `SUBSTRATE_IMAGE_TAG`, `KERNEL_IMAGE_TAG`); compose keeps `build:` as the fallback (S-167) | | Glue | `scripts/`, `deploy/` | brings the parts up and connects them | @@ -76,12 +77,12 @@ scripts/up.sh # the stack (db, gateway, ollama, ui), the tools cont scripts/check.sh # is everything up and wired scripts/test.sh [FILE...] # the test suites, in the tools container (the kernel's in its image, the router's Go tests in Go's) scripts/build.sh [db|tools|kernel] # none: pull published images, build what did not pull; SUBSTRATE_BUILD=1 builds all -scripts/logs.sh SERVICE # db, gateway, ollama, kernel, ui, caddy, mcp-router, mcp-kernel, llm, llm-fast +scripts/logs.sh SERVICE # db, gateway, ollama, kernel, environment, ui, caddy, mcp-router, mcp-kernel, llm, llm-fast scripts/tools.sh start|stop|status -scripts/kernel.sh init|catalog|login NAME|mcp NAME|person NAME # the Knowledge Kernel: its schema, the catalog into it, an agent's login, its MCP server, a person's sign-in +scripts/kernel.sh init|catalog|login NAME|mcp NAME|person NAME # the Knowledge Kernel: its schema and Substrate's modules, the catalog into it, an agent's login, its MCP server, a person's sign-in scripts/assistant.sh # the assistant: a Claude Code session you talk to in the desktop's Assistant window (S-206) 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 kernel's database and the environment's schema in it (environment/sql/) -bin/in-tools python3 scripts/env.py waiting|decide|publish|actuators|gate|queues # the environment, as a person +bin/in-tools python3 scripts/env.py waiting|publish|actuators|gate|queues # the environment, as a person (proposals are decided in the desktop's Review, S-219) ``` diff --git a/DECISIONS.md b/DECISIONS.md index 6461803..31b22ca 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -226,3 +226,6 @@ Status: **decided** (owner agreed), **adopted** (recommended and taken; confirm | S-216 | **Substrate on the kit: its rules in the catalog, Morphogen's plugin repinned, its own `map`, `catalog` and `research` skills removed** (2026-11-25; after Morphogen #102 and #103 merged; the owner: "what's next?"; plan "The re-cut" steps 1 and 2). (a) `morphogen.yaml` is gone (Morphogen #103 reads every rule from the catalog): a root `catalog-info.yaml` is a Location naming `catalog/catalog-info.yaml`, and the settings it held (`sandbox: podman`, the sandbox image) are on the System entity under `spec.morphogen`. Morphogen at `63648ca` reads all of Substrate's catalog with no errors (`structure check`: 17 interfaces untested, 6 unused, warnings only), and its `status` says the next step is this catalog on `main`. (b) **The plugin is pinned to `63648ca`** (`.claude/settings.json`, and `repos.yaml`'s `checked`), Morphogen's `main` after #103. (c) **Substrate uses Morphogen's skills like any user:** `.claude/skills/{map,catalog,research}` are removed; rule 3 names `morphogen:research`. Picks are still recorded in `DECISIONS.md` (rule 1). `setup` and `upstream` stay. (d) The operator's `morphogen.local.yaml` still names the retired cell `voice-route`; it is uncommitted and the operator's to tidy. | done | | S-217 | **The demo engagement is done with the kit alone; the plugin is pinned to Morphogen `d945a9c` (0.9.0)** (2026-11-24; the owner: "merged 104 ...continue"; plan "The re-cut" steps 1 and 3). (a) Morphogen #104 adds `demos/fernhill`: a made-up 11-person kitchen firm's material (documents, a job log of 121 jobs, an interview), the first run's map (Backstage entities, 40 evidence quotes, all found on their lines), its quote calculator as a judged cell (held-out cost error 12.4% to 3.4% after `tune`; pass, 7 runs, p = 0.008, Podman), four options for job scheduling quoted from the vendors' pages, and a report of four implementation projects. No kernel and no stack ran. (b) **Step 3's done-when is met:** `run.sh` ran Claude Code on sonnet with only the plugin and the material, and `check.py`'s eight checks passed with no help (its report in `demos/fernhill/runs/`). (c) **The pin moves to `d945a9c`** (`.claude/settings.json`, `repos.yaml`). Morphogen #102 and #103 changed the plugin under version 0.8.0, so `claude plugin update` kept the code from before them, and S-216's pin never reached the install; #104 bumps it to 0.9.0. A plugin repin is checked by the install's `gitCommitSha` in `~/.claude/plugins/installed_plugins.json`, not by the settings file. (d) Four kit findings are listed in the demo's README for issues in Morphogen. (e) The business session (S-188 c) can start from the report. | done | | S-218 | **The stack on kernel `e4ed8e2`; an MCP tool's gate follows its annotations until a person sets it; the desktop's host port is a setting** (2026-11-24; the owner, on port 8080 taken: "use any other available port, i'm working with 8080 right now"; on the gates: "Free, and change the rule"). (a) **The kernel pin moves to `e4ed8e2`** (main after #140, with #138 / its D-128: every MCP tool says whether it writes; `repos.yaml`); the published image's revision is the same commit; `scripts/check.sh` passes and every suite passes on it (catalog 9, environment 41, gateway 15, kernel 27, UI 36, the router's Go tests). (b) **The gate rule** (`environment/sql/012_mcp_gates.sql`, superseding the "a connector registering again never changes a gate" of `010_mcp.sql` and S-205): the kernel's tools were registered before #138, so its 14 read-only tools kept `propose` and every read waited for a person. Now each registration sets again a gate whose `set_by` is the registering connector (no person has set it since): from `env.mcp_policy` first, else readOnlyHint true is `free` and anything else `propose`, in both directions. A gate a person set is kept (`recall`, set by `person_owner`). On this machine the 14 are `free` by the rule (set_by `connector:kernel`, no decision made in the owner's name); the 5 writers stay `propose`. Seven new checks in `scripts/tests/test_environment.py`; three of them fail without 012. (c) **`DESKTOP_PORT`** (default 8080) is the desktop's port on the host: compose maps it to Caddy's 8080, and the Caddyfile's and the router's `frame-ancestors`, `check.sh`, `kernel.sh person` and `assistant.sh` name it; the framed apps stay on 8081 to 8083 (S-200). This machine uses 8180. The `setup` skill names a taken port as a known cause. | done | +| S-219 | **The environment is a kernel module: a proposed action waits in the kernel's review lane, and the decision made there is the action's** (2026-11-27; `docs/parts.md` "Order" step 2, first part; S-212, S-213 (a), S-214: a part is a kernel module when it needs the kernel's database, a role and the review lane). (a) **Through the kernel's module contract** (its `kernel/schemas/module.schema.json`, `modules/_template`, `kk module install`, read at kernel `e4ed8e2`): `environment/module.yaml` (`urn:kk:module:environment`, kind `control`, slots `trigger` and `actuator`, requires `review-lane`, role `kkm_environment`, runtime a python-service) and `environment/migration.sql` (the role, its agent row, the role granted to the kernel's login, as `actuator-compose` does). `scripts/kernel.sh init` runs `kk module install` on it after `kk init`, so the kernel checks the manifest and its licence and applies the migration once. The environment's own schema `env` stays migrated by `environment/db.py` (numbered files, each once): the kernel's contract applies a module's migration once and has no upgrade step, and `env` has seven files already; `013_review_lane.sql` gives the module's role `env.review_waiting()` and `env.decide` and nothing else in `env`. (b) **Its service** (`environment/review.py`; compose `environment`, in the kernel's image with `../environment` mounted, so it uses the kernel's `kk.lib` as every kernel module does: the kernel's login `kk_authenticator`, switched to `kkm_environment`): each waiting action becomes one change set in the review lane, keyed `environment:action:`, in scope `urn:kk:scope:default`: `urn:kk:environment:action:` a `sosa:Actuation`, `sosa:madeByActuator` its actuator, `as:actor` the caller's kernel agent when it is one, an `rdfs:label` (an MCP tool by the name its caller used, the caller, the action's id) and `dcterms:description` its input in full; standard terms from the kernel's packs, no new vocabulary. The kernel validates it and holds it for a reviewer, so the person decides it in the desktop's Review with everything else. Approved, the kernel applies it (the approved request is kept as claims, five per action) and the service calls `env.decide(approve, the reviewer, the note)`: queued for its actuator; rejected, refused with the reviewer's note. The kernel refuses a change set's approval by its submitter (the module) and the environment a proposal's by its caller, so a person who approves a request they made has it refused, with the reason. It wakes on `env_action` and `kernel_change_set` and looks every 5 s (`KK_SWEEP_SECONDS`), because a rejection sends no notification. (c) **One place to decide:** the router decides nothing any more (its `/api/decide` and the page's Approve and Reject buttons are gone; its Waiting list says to decide in Review; `env.decide` is revoked from `env_router`), and `scripts/env.py decide` is gone. (d) **Checked:** `scripts/tests/test_review.py`, 19/19 in a throwaway kernel (the install and its repeat; one change set per waiting action, held for review, saying what, by whom, with the input; approval, rejection with a note, self-approval refused; the router may not decide; the module may decide and may not act or set a gate); every suite passes (environment 44, review 19, kernel 27, UI 36, gateway 15, catalog 9, the router's Go tests). End to end on a throwaway stack (compose project `recut`, its own ports and volumes): an agent's `kernel_remember` through the router waited, appeared in the kernel's `review_queue` for `person_owner`, was approved with the kernel's own `review` tool and carried out by the kernel's connector; a second was rejected and the router's `router_outcome` said refused, by `person_owner`, "not now". (e) **Found, for the kernel:** `kk module install` gives a python-service module's role a login with a new random password on every run, even when the module is installed (unused here: the service switches from the kernel's login); there is no upgrade path for a module's migration; a rejection sends no `kernel_change_set` notification. Each is a small kernel pull request when wanted, none needed now. (f) **Privacy:** an approved request's input is now a claim in the default scope, which every agent with default clearance can read; before, it was only in `env.action`. Whether proposals go to a scope of their own is the owner's call (`docs/privacy.md`). | adopted | +| S-220 | **The channel and the MCP router are MCP servers on the environment module; the channel connects as its own login** (2026-11-27; `docs/parts.md` "Order" step 2, second part). (a) **The channel** (`environment/channel.py`, stdio, started by the harness) was already an MCP server reading the environment's queues, but it connected as Postgres's superuser. It now connects with `DATABASE_URL`, its own login `mcp_channel` (role `env_agent`: publish, act through the gates, read and acknowledge the queues it subscribed; it cannot decide, set a gate or read another's queue), password `MCP_CHANNEL_DB_PASSWORD` (`deploy/secrets.txt`, made by `scripts/settings.sh`, the login by `scripts/db.py init`). `scripts/assistant.sh` writes it into the channel's MCP entry (`.state/assistant/mcp.json`, mode 600, beside the token it already held); `013_review_lane.sql` gives the login the assistant's queues made before. Without `DATABASE_URL` it still falls back to `ENV_URL`, `STORE_URL`, then the superuser, for a person at the command line. It stays in the `environment` package: it is a few lines over the module's functions, not a part with code of its own. (b) **The router** (`mcp-router/`, Go) is already a compose-service MCP server whose registry (`env.mcp_server`, `env.mcp_tool`, `env.mcp_policy`) and gates are the environment module's schema; it now decides nothing (S-219 c). S-205 (g)'s question, whether it moves into the kernel's core, stays open. (c) **The catalog:** `component:environment` is now a service with its compose service, `component:channel` is new. (d) **Checked:** four new checks in `scripts/tests/test_environment.py` (the channel's session runs on an `env_agent` login; that login may not decide, set a gate or read a queue it did not subscribe), and the channel started from `assistant.sh`'s dry-run settings on the throwaway stack initialised as `mcp_channel` and acted through the gates. | adopted | +| S-221 | **The assistant's conversation is already a view in the kernel's desktop; nothing more is built for it until a use case asks, and `ui/` stays** (2026-11-27; `docs/parts.md` "Order" step 2, third part: "built as far as a use case needs"). The Assistant view (`desktop/view-assistant/`, a view module in the kernel's contract, mounted into the kernel's container, S-206) and its messages as signals in `env` (`011_desktop.sql`) are the target shape already; its server `desktop/server.py` is an MCP server through the router, as S-213 (a) wants. What it lacks (a chat library picked with the `research` skill, S-208) waits for the next use of the assistant. `ui/` is not retired: the kernel's Map view draws one map, and Substrate's many maps (S-207: a map as an item, one marked self) are not in the kernel yet. | adopted | diff --git a/README.md b/README.md index 8561b21..09eb18c 100644 --- a/README.md +++ b/README.md @@ -25,9 +25,10 @@ implementation project runs end to end on a demo small business without new core and picks an opportunity, the harness carries it out under the kernel's gates, a person approves what matters, and Morphogen judges the result (S-211). -**Where it stands (2026-11-24):** the stack below runs on one machine, and a person has talked to the assistant in -the kernel's desktop (S-208). The re-cut is decided and the parts are not moved yet. The work goes to Morphogen -(the kit) and the kernel first. +**Where it stands (2026-11-27):** the stack below runs on one machine, and a person has talked to the assistant in +the kernel's desktop (S-208). Morphogen is the kit (the re-cut's first step, S-216, S-217). The environment is now a +kernel module whose proposals a person decides in the kernel's review lane, and the channel and the router are MCP +servers on it (S-219 to S-221); the default distribution and the test of the bet come next (`docs/parts.md`). ## What runs @@ -37,8 +38,8 @@ Podman compose, published on 127.0.0.1 only. | Part | Where | What it does | | --- | --- | --- | | The store | the Knowledge Kernel (`scripts/kernel.sh`), Postgres (`deploy/postgres`) | Wikibase's data model with pinned evidence: things, statements, and the exact span of the source each statement rests on. A changed source flags what cites it, with no model call. Maps of parts, roles and interfaces, and catalogs of candidates with measurements and trade-off notes | -| 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 environment | `environment/`, schema `env`, a kernel module (service `environment`) | Signals logged whole and fanned out as pgmq topics; one queue per actuator behind a gate (`free`, `propose`, `deny`); a proposal waits in the kernel's review lane and a person decides it in the desktop's Review, with everything else the kernel holds for review; every action recorded (S-219) | +| The channel | `environment/channel.py`, an MCP server | Pushes an environment's signals into a live Claude Code session, as a login of its own; a signal not acknowledged comes back (S-220) | | 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; a meter counts a judged run's calls (S-193) | | 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 optimiser | Morphogen's Claude Code plugin; its rules in the catalog (`catalog-info.yaml` at the root, S-216) | Cells from Substrate's catalog (`catalog/`); a change is judged on cases it cannot read, its model calls counted at the gateway (S-193) | diff --git a/catalog/catalog-info.yaml b/catalog/catalog-info.yaml index 1dbf4bf..0729691 100644 --- a/catalog/catalog-info.yaml +++ b/catalog/catalog-info.yaml @@ -24,6 +24,7 @@ spec: - ./component-caddy.yaml - ./component-desktop.yaml - ./component-environment.yaml + - ./component-channel.yaml - ./component-gateway.yaml - ./component-kernel-catalog.yaml - ./component-kernel-init.yaml diff --git a/catalog/component-channel.yaml b/catalog/component-channel.yaml new file mode 100644 index 0000000..faf783b --- /dev/null +++ b/catalog/component-channel.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: channel + title: The channel into a harness + description: An MCP server (stdio) a harness session starts; it pushes a subscribed queue of the environment module as channel events, archived only on ack, and acts through the gates, as its own login (mcp_channel, role env_agent). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/source: environment/channel.py + substrate.dev/decision: S-143, S-144, S-220 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + dependsOn: + - resource:db + - component:environment diff --git a/catalog/component-environment.yaml b/catalog/component-environment.yaml index 8990824..0bed2c6 100644 --- a/catalog/component-environment.yaml +++ b/catalog/component-environment.yaml @@ -3,16 +3,19 @@ apiVersion: backstage.io/v1alpha1 kind: Component metadata: name: environment - title: The real-time environment - description: Signals, subscribers, actuators behind gates and the record of actions on pgmq (schema env, environment/sql/); the channel into Claude Code (environment/channel.py). + title: The live environment (a kernel module) + description: Signals, subscribers, actuators behind gates and the record of actions on pgmq (schema env, environment/sql/); a kernel module (environment/module.yaml) whose service puts each proposed action in the kernel's review lane and records the person's decision there. annotations: substrate.dev/licence: Apache-2.0 substrate.dev/source: environment/ - substrate.dev/decision: S-143, S-144, S-194 + substrate.dev/image: ghcr.io/openreplicant/kernel + substrate.dev/compose-service: environment + substrate.dev/decision: S-143, S-144, S-194, S-219 spec: - type: library + type: service lifecycle: experimental owner: owner system: substrate dependsOn: - resource:db + - component:kernel diff --git a/deploy/compose.yaml b/deploy/compose.yaml index 0ee747b..e03854b 100644 --- a/deploy/compose.yaml +++ b/deploy/compose.yaml @@ -104,6 +104,27 @@ services: environment: KK_ADMIN_URL: postgresql://postgres:${POSTGRES_PASSWORD:?set in .env}@db:5432/kernel KK_AUTHENTICATOR_PASSWORD: ${KK_AUTHENTICATOR_PASSWORD:?set in .env} + # Substrate's kernel modules, for `kk module install` (scripts/kernel.sh init; S-219) + volumes: + - ../environment:/substrate/environment:ro + depends_on: + db: {condition: service_healthy} + + # The environment as a kernel module (S-219; environment/module.yaml): a proposed action waits in the kernel's review + # lane, a person decides it in the desktop's Review, and this service records that decision on the action. In the + # kernel's image, with kk.lib, as every kernel module: the kernel's login, switched to the module's role. + environment: + <<: *locked + image: ghcr.io/openreplicant/kernel:${KERNEL_IMAGE_TAG:-main} + command: ["python3", "-m", "environment.review"] + tmpfs: [/tmp] + environment: + DATABASE_URL: postgresql://kk_authenticator:${KK_AUTHENTICATOR_PASSWORD:?set in .env}@db:5432/kernel + KK_ROLE: kkm_environment + PYTHONPATH: /substrate + PYTHONDONTWRITEBYTECODE: "1" + volumes: + - ../environment:/substrate/environment:ro depends_on: db: {condition: service_healthy} diff --git a/deploy/secrets.txt b/deploy/secrets.txt index 7d610e2..1a68a09 100644 --- a/deploy/secrets.txt +++ b/deploy/secrets.txt @@ -13,4 +13,5 @@ KK_AUTHENTICATOR_PASSWORD token:24 the Knowledge Kernel's one login for MCP_ROUTER_DB_PASSWORD token:24 the MCP router's login to the kernel's database (mcp_router, role env_router: lists and calls tools, records decisions; S-205) MCP_CONNECTOR_DB_PASSWORD token:24 the MCP connectors' login (mcp_connector, role env_connector: registers servers, applies calls; S-205) MCP_DESKTOP_DB_PASSWORD token:24 the desktop server's login (mcp_desktop, role env_desktop: the conversation's signals and feed; S-206) +MCP_CHANNEL_DB_PASSWORD token:24 the channel's login (mcp_channel, role env_agent: its own queues, acting through the gates; S-220) 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/parts.md b/docs/parts.md index 717d755..0e79012 100644 --- a/docs/parts.md +++ b/docs/parts.md @@ -6,19 +6,20 @@ person who wants only the kernel never installs them. Our agents and experiments distribution. **A part is a kernel module only when it needs the kernel** (its own role, its data in the kernel's database, the review lane; S-213), written to the kernel's module contract (S-203) and shipped from this repository. Otherwise it is the standard type it already is: an Agent Skill, an MCP server, a compose service, a harness plugin, or an external -service in the default collection. Nothing has been rebuilt yet. +service in the default collection. The environment, the channel and the router are in their types since 2026-11-27 +(S-219 to S-221). ## Substrate's optional parts (shipped from here, not with the kernel's core) -| Part | Where it is now | What it becomes | +| Part | Where it is | What it is | | --- | --- | --- | -| The live environment: signals, a queue per actuator, gates, the record | `environment/sql/`, `environment/db.py` | a kernel module (it needs the kernel's database and review lane): its gates send `propose` to the review lane, so a person approves in one place | -| The channel into a harness session | `environment/channel.py` | an MCP server a harness connects to, reading the environment module's queues | -| The MCP router: one endpoint, each tool an action behind its gate | `mcp-router/` (Go), `environment/sql/010_mcp.sql` | an MCP server run as a compose service, its registry in the environment module's schema | +| The live environment: signals, a queue per actuator, gates, the record | `environment/` (`module.yaml`, `migration.sql`, the schema in `sql/` by `db.py`, the service `review.py`, compose `environment`) | **done (S-219):** a kernel module, installed by `kk module install` (`scripts/kernel.sh init`); a proposed action waits in the kernel's review lane, so a person approves in one place, the desktop's Review, and the module records that decision on the action | +| The channel into a harness session | `environment/channel.py` | **done (S-220):** an MCP server (stdio) a harness starts, reading the environment module's queues as its own login (`mcp_channel`, role `env_agent`) | +| The MCP router: one endpoint, each tool an action behind its gate | `mcp-router/` (Go), compose `mcp-router` and a connector per server; its registry `environment/sql/010_mcp.sql` to `013` | **done (S-220):** an MCP server run as a compose service, its registry and gates in the environment module's schema; it decides nothing (S-219) | | The desktop: windows, the launcher, framed apps | the kernel's shell (`modules/ui`, the kernel's D-127); `deploy/caddy/` | stays the kernel's, in its repository, growing there by its pull requests as use cases need (S-214); Substrate's views install onto it | -| The assistant's conversation | `desktop/`, `environment/sql/011_desktop.sql` | a view module from this repository, installed into the kernel's desktop; its messages kept in the environment module | +| The assistant's conversation | `desktop/` (the view `view-assistant`, mounted into the kernel's container; its server an MCP server through the router), `environment/sql/011_desktop.sql` | **in its type already (S-221):** a view module from this repository in the kernel's desktop, its messages signals in the environment module; built further when a use case asks | | Substrate's read model and encoder | the kernel's `view-substrate`, `encoder-substrate` | brought here as Substrate's modules, or retired once maps are items (S-207) | -| The old store UI | `ui/` | retired: the kernel's views and the map viewer (S-207) do its job | +| The old store UI | `ui/` | retired once the kernel's views and the map viewer (S-207) do its job; kept until then (S-221) | ## The default distribution @@ -44,8 +45,9 @@ or a module on top of the default one. ## Order 1. Morphogen's kit (`docs/morphogen-kit.md`), by pull request there. -2. Substrate's parts in their types, in this repository: the environment as a kernel module, the channel and the +2. **Done 2026-11-27 (S-219 to S-221) but for what waits on use cases:** Substrate's parts in their types, in this repository: the environment as a kernel module, the channel and the router as MCP servers on it; the assistant's conversation as a view installed into the kernel's desktop, built as far as a use case needs. + Left: Substrate's read model and encoder (the kernel's `view-substrate`, `encoder-substrate`) and `ui/`, both waiting on S-207 (maps as items). 3. The default distribution: the compose file installs the kernel's core and Substrate's modules, the harness is configured to use them, `scripts/check.sh` checks the wiring. 4. The test of the bet (S-211 c): one implementation project on a demo SMB, end to end. diff --git a/environment/__init__.py b/environment/__init__.py index 0d72c9a..a4a55c5 100644 --- a/environment/__init__.py +++ b/environment/__init__.py @@ -1,6 +1,6 @@ -"""The real-time environment (plan step 3c): signals, subscribers, actuators and gates on pgmq, in the -substrate database (schema `env`, environment/sql/005_environment.sql). This module is the Python side of those functions; the -channel into Claude Code is environment.channel. +"""The real-time environment (plan step 3c; a kernel module since S-219, environment/module.yaml): signals, subscribers, +actuators and gates on pgmq, in the kernel's database (schema `env`, environment/sql/). This module is the Python side +of those functions; the channel into Claude Code is environment.channel, the review lane's service environment.review. """ from __future__ import annotations diff --git a/environment/channel.py b/environment/channel.py index 044da8e..7949bc6 100644 --- a/environment/channel.py +++ b/environment/channel.py @@ -10,7 +10,10 @@ one left unacknowledged becomes visible again and is delivered again, with its delivery count. Tools: ack (archive handled messages), act (call an actuator through its gate), escalate (to the level above). -The database is ENV_URL or STORE_URL, else the kernel's database from .env (S-202). MCP 2025-11-25 (and 2025-06-18 if asked): newline-delimited +It is an MCP server on the environment module (S-220): it connects with DATABASE_URL, the channel's own login +(mcp_channel, role env_agent: it publishes, acts through the gates and reads only the queues it subscribed; it cannot +decide a proposal or change a gate). Without it, ENV_URL or STORE_URL, else the kernel's database from .env as a +superuser, for a person at the command line (S-202). MCP 2025-11-25 (and 2025-06-18 if asked): newline-delimited JSON-RPC on stdin and stdout, logs on stderr. """ from __future__ import annotations @@ -24,7 +27,12 @@ import psycopg from environment import Env -from environment.db import database_url +from environment.db import database_url as admin_or_env_url + + +def database_url() -> str: + """The channel's own login (DATABASE_URL) when it is given one, else the environment's address (environment.db).""" + return os.environ.get("DATABASE_URL") or admin_or_env_url() VERSIONS = ("2025-11-25", "2025-06-18") # MCP protocol versions it speaks, newest first @@ -39,7 +47,8 @@ def obj(props: dict, required: list[str]) -> dict: "not delivered again. An unacknowledged message comes back after the visibility timeout.", "inputSchema": obj({"msg_ids": {**A, "items": I}}, ["msg_ids"])}, {"name": "act", "description": "Call an actuator (.) with an input object, through its gate: free is queued " - "at once, propose waits for a person (the outcome arrives as an .review.decided event), deny is refused.", + "at once, propose waits for a person's decision in the desktop's Review (the outcome arrives as an " + ".review.decided event), deny is refused.", "inputSchema": obj({"actuator": S, "input": {"type": "object"}}, ["actuator", "input"])}, {"name": "escalate", "description": "Hand something you cannot or should not handle to the level above (.escalate), " "saying what and why.", "inputSchema": obj({"env": S, "text": S}, ["env", "text"])}, diff --git a/environment/migration.sql b/environment/migration.sql new file mode 100644 index 0000000..5939f51 --- /dev/null +++ b/environment/migration.sql @@ -0,0 +1,19 @@ +-- Module install: environment (Substrate, S-219), the kernel's side. Applied once by `kk module install` as a superuser +-- (the kernel's modules/_template/migration.sql). The environment's own schema `env` is migrated by environment/db.py +-- (environment/sql/, numbered, each applied once); 013 there grants this role what it needs in `env`. +-- Clearance comes from the default scope grants to kk_agent (the kernel's 002_bootstrap.sql): the module submits each +-- waiting action as a change set in the review lane of urn:kk:scope:default. + +do $$ begin + if not exists (select 1 from pg_roles where rolname = 'kkm_environment') then + create role kkm_environment nologin; + end if; +end $$; +grant kk_agent to kkm_environment; +grant kkm_environment to kk_authenticator; -- the module's service connects as the kernel's login and switches to it + +set role kk_owner; +insert into kernel.agent(iri, db_role, kind, label) +values ('urn:kk:agent:environment', 'kkm_environment', 'software', 'Environment: actions behind gates') +on conflict (iri) do nothing; +reset role; diff --git a/environment/module.yaml b/environment/module.yaml new file mode 100644 index 0000000..c3ab421 --- /dev/null +++ b/environment/module.yaml @@ -0,0 +1,51 @@ +# Module manifest — schema: kernel/schemas/module.schema.json (the kernel's). Substrate's environment as a kernel module +# (S-219; S-213: a part is a kernel module when it needs the kernel: its own role, its data in the kernel's database, +# the review lane). Installed by `scripts/kernel.sh init` (`kk module install`), its service is compose's `environment`. +id: urn:kk:module:environment +name: 'Environment: signals, actuators behind gates, the record' +version: 0.1.0 +description: 'The live environment (schema env, environment/sql/, on pgmq): signals logged whole and fanned out as + topics, one queue per actuator behind its gate (free, propose, deny), every call an action recorded whole. A proposed + action waits in the kernel''s review lane: the module submits it as a change set (a sosa:Actuation with its actuator, + its caller and its input), a person approves or rejects it in the desktop''s Review, and the module records that + decision on the action, which is then queued or refused. The channel and the MCP router are MCP servers on it.' +license: Apache-2.0 +kind: control +slots: +- trigger +- actuator +protected: true +agent: + iri: urn:kk:agent:environment + db_role: kkm_environment + member_of: + - kk_agent +clearance: + write: + - urn:kk:scope:default +runtime: + type: python-service + entrypoint: python3 -m environment.review + env: + DATABASE_URL: the kernel's login (kk_authenticator), which switches to kkm_environment + KK_ROLE: kkm_environment + KK_SWEEP_SECONDS: how often it looks at the review lane without a notification (default 5) +requires: +- slot: review-lane +accepts: +- 'env.action (a proposed action: its actuator, input and caller)' +- 'change_set (its own, decided in the review lane)' +produces: +- add_claim +- 'http://www.w3.org/ns/sosa/Actuation (rdf:type; sosa:madeByActuator the actuator, as:actor the caller, rdfs:label, dcterms:description the input)' +- 'env.decide (the reviewer''s decision on the action)' +triggers: +- type: notify + spec: env_action +- type: notify + spec: kernel_change_set +- type: schedule + spec: every KK_SWEEP_SECONDS (a review decision sends no notification) +mcp: + expose: [] +migration: migration.sql diff --git a/environment/review.py b/environment/review.py new file mode 100644 index 0000000..f2ca118 --- /dev/null +++ b/environment/review.py @@ -0,0 +1,132 @@ +"""The environment's review lane (S-219): a proposed action waits in the kernel's review lane, so a person approves +in one place, the desktop's Review. + + python3 -m environment.review [--once] # the kernel module's service (compose `environment`), in the kernel's image + +For each action waiting for a person (env.review_waiting), it submits one change set in the review lane, keyed +`environment:action:`: a sosa:Actuation with its actuator (sosa:madeByActuator), its caller (as:actor, when the +caller is a kernel agent), a label, and its input in full (dcterms:description). The kernel validates it and holds it +for a reviewer. Once a person has approved it (the kernel applies it, so the approved request is kept as claims) or +rejected it, the module records that person's decision on the action with env.decide: approved, it is queued for its +actuator; rejected, it never is. The kernel refuses a change set's approval by its submitter (this module); the +environment refuses a proposal's approval by its caller, so a person who approved their own request has it refused here, +with the reason. + +It wakes on `env_action` (a new proposal) and `kernel_change_set` (an applied approval), and looks again every +KK_SWEEP_SECONDS (default 5), since a rejection sends no notification. It runs as kkm_environment: DATABASE_URL is the +kernel's login (kk_authenticator), KK_ROLE the module's role (the kernel's kk.lib, as every kernel module). +""" +from __future__ import annotations + +import argparse +import json +import os +import signal +import sys + +from kk.lib import connect, listen, run, submit + +MODULE = "urn:kk:module:environment" +AGENT = "urn:kk:agent:environment" +SCOPE = "urn:kk:scope:default" +ROLE = "kkm_environment" +RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" +LABEL = "http://www.w3.org/2000/01/rdf-schema#label" +DESCRIPTION = "http://purl.org/dc/terms/description" +SOSA = "http://www.w3.org/ns/sosa/" +ACTOR = "https://www.w3.org/ns/activitystreams#actor" + + +def key(action: int) -> str: + return f"environment:action:{action}" + + +def iri(action: int) -> str: + return f"urn:kk:environment:action:{action}" + + +def what(a: dict) -> str: + """The action in a few words: an MCP tool by its exposed name, else the actuator.""" + inp = a["input"] if isinstance(a["input"], dict) else {} + if a["actuator"].startswith("mcp.") and inp.get("server") and inp.get("tool"): + return f"{inp['server']}_{inp['tool']}" + return a["actuator"] + + +def ops(a: dict, actor: str | None) -> list[dict]: + """The change set's claims about one waiting action: what the reviewer reads in Review.""" + s, ref = iri(a["id"]), [{"source_uri": iri(a["id"])}] + shown = a["input"].get("arguments", a["input"]) if isinstance(a["input"], dict) else a["input"] + + def claim(p, o): + return {"op": "add_claim", "subject": s, "predicate": p, "object": o, "evidence_type": "deterministic", + "references": ref} + out = [claim(RDF_TYPE, {"entity": SOSA + "Actuation"}), + claim(LABEL, {"value": {"@value": f"{what(a)}, asked by {a['caller']} (action {a['id']})"}}), + claim(SOSA + "madeByActuator", {"entity": f"urn:kk:environment:actuator:{a['actuator']}"}), + claim(DESCRIPTION, {"value": {"@value": json.dumps(shown, ensure_ascii=False, sort_keys=True)}})] + if actor: + out.append(claim(ACTOR, {"entity": actor})) + return out + + +def one_pass(conn) -> dict: + """Submit what waits and is not in the review lane yet; record what a person decided there. Returns what it did.""" + did = {"submitted": [], "approved": [], "rejected": [], "refused": [], "waiting": [], "stuck": []} + with conn.cursor() as cur: + cur.execute("select id, actuator, description, input, caller, login, at from env.review_waiting()") + cols = [d.name for d in cur.description] + waiting = [dict(zip(cols, r)) for r in cur.fetchall()] + if not waiting: + return did + cur.execute("select idempotency_key, status, decided_by, coalesce(review_note, '') from api.change_sets " + "where idempotency_key = any(%s) and attributed_to = %s", ([key(a["id"]) for a in waiting], AGENT)) + sets = {k: (st, by, note) for k, st, by, note in cur.fetchall()} + cur.execute("select db_role::text, iri from kernel.agent where db_role::text = any(%s)", + (sorted({a["caller"] for a in waiting}),)) + agents = dict(cur.fetchall()) + for a in waiting: + st, by, note = sets.get(key(a["id"]), (None, None, "")) + if st is None: + with run(cur, MODULE, {"action": a["id"], "actuator": a["actuator"]}) as (run_id, outputs): + got = submit(cur, {"idempotency_key": key(a["id"]), "attributed_to": AGENT, "target_scope": SCOPE, + "lane": "review", "ops": ops(a, agents.get(a["caller"]))}, run_id) + outputs.update(change_set=got["id"]) + did["submitted"].append(a["id"]) + elif st in ("approved", "applied", "rejected"): + approve = st != "rejected" + if approve and by == a["caller"]: + cur.execute("select env.decide(%s, false, %s, %s)", (a["id"], ROLE, + f"approved in the review lane by {by}, who asked for it; a proposal needs another person")) + did["refused"].append(a["id"]) + continue + cur.execute("select env.decide(%s, %s, %s, %s)", (a["id"], approve, by, note or None)) + did["approved" if approve else "rejected"].append(a["id"]) + elif st in ("invalid", "conflict"): + did["stuck"].append(a["id"]) # the kernel would not hold it for review; logged, left waiting + else: + did["waiting"].append(a["id"]) + return did + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description="Proposed actions into the kernel's review lane, and its decisions back.") + ap.add_argument("--once", action="store_true", help="one pass, print what it did and exit") + a = ap.parse_args(argv) + conn = connect(os.environ.get("KK_ROLE", ROLE)) + if a.once: + print(json.dumps(one_pass(conn))) + return 0 + signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) # PID 1 in its container: stop at once when compose stops it + conn.execute("listen env_action") # a new proposal wakes it as well as an applied change set + + def step(c): + did = one_pass(c) + if any(v for k, v in did.items() if k != "waiting"): + print(json.dumps(did), flush=True) + listen(conn, step, sweep=float(os.environ.get("KK_SWEEP_SECONDS") or 5)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/environment/sql/013_review_lane.sql b/environment/sql/013_review_lane.sql new file mode 100644 index 0000000..0bef170 --- /dev/null +++ b/environment/sql/013_review_lane.sql @@ -0,0 +1,37 @@ +-- The environment as a kernel module (S-219): a proposal waits in the kernel's review lane, so a person approves in one +-- place, the desktop's Review. The module's process (environment/review.py, role kkm_environment) submits each waiting +-- action as a change set in the review lane and, once a person has approved or rejected it there, records that person's +-- decision here with env.decide. The kernel's side of the install (the role's agent row, its clearance) is +-- environment/migration.sql, which `kk module install` applies; this file is the environment's side, safe in either order. +-- +-- env.review_waiting() the actions waiting for a person, with what the review lane shows of each +-- env.decide now called only by the module (and a superuser): the router no longer decides (S-219) +-- +-- The channel (environment/channel.py) gets a login of its own (S-220): mcp_channel, role env_agent, so a harness's +-- channel acts through the gates and reads only the queues it subscribed, never as a superuser. + +do $$ begin + if not exists (select 1 from pg_roles where rolname = 'kkm_environment') then + create role kkm_environment nologin; + end if; +end $$; + +create function env.review_waiting(p_limit int default 200) +returns table (id bigint, actuator text, description text, input jsonb, caller text, login text, at timestamptz) +language sql stable security definer set search_path = pg_catalog, public as $$ + select a.id, a.actuator, u.description, a.input, a.caller, a.login, a.at + from env.action a join env.actuator u on u.name = a.actuator + where a.status = 'proposed' + order by a.id limit least(greatest(p_limit, 1), 1000) +$$; + +revoke all on function env.review_waiting(int) from public; +revoke execute on function env.decide(bigint, boolean, text, text) from env_router; +grant usage on schema env to kkm_environment; +grant execute on function env.review_waiting(int), env.decide(bigint, boolean, text, text) to kkm_environment; + +-- Queues the assistant's channel made while it connected as a superuser (S-206) become the channel login's, so it can +-- subscribe to them again under its own login. +insert into env.reader (queue, login) +select queue_name, 'mcp_channel' from pgmq.meta where queue_name like 'assistant\_%' +on conflict do nothing; diff --git a/mcp-router/README.md b/mcp-router/README.md index 4c7c920..a2ab7de 100644 --- a/mcp-router/README.md +++ b/mcp-router/README.md @@ -1,8 +1,9 @@ # mcp-router Substrate's MCP router (S-203: modules run on their own and meet over MCP; S-205: the router's rules live in Postgres, -its edge and connectors are processes outside it). One static binary, two modes. The rules (gates, the record, who -decides) are the `env.mcp_*` functions in `environment/sql/010_mcp.sql`; the binary holds none of them. +its edge and connectors are processes outside it). One static binary, two modes. The rules (gates, the record) and the registry +are the `env.mcp_*` functions and tables of the environment module's schema (`environment/sql/010_mcp.sql` to `013`); the binary +holds none of them. ## `mcp-router serve`: the edge @@ -10,8 +11,10 @@ decides) are the `env.mcp_*` functions in `environment/sql/010_mcp.sql`; the bin at that moment, for the caller in its token). Tools are named `_`, plus `router_outcome {action}`. A call goes through `env.mcp_call`; the router waits (LISTEN `env_action`, one listener for all waits) up to `WAIT_SECONDS` for it to end, else answers that it waits for approval. -- `/api/login`, `/api/tools`, `/api/calls`, `/api/decide`: the JSON API of the desktop page. Sign-in opens a Postgres - connection as `person_` with the password and, if it works, mints an 8-hour token. Only `person_` roles decide. +- `/api/login`, `/api/tools`, `/api/calls`: the JSON API of the desktop page. Sign-in opens a Postgres connection as + `person_` with the password and, if it works, mints an 8-hour token. The router decides nothing: a call that + waits is decided by a person in the kernel's review lane (the desktop's Review), where the environment module puts + it and from which it records the decision (S-219); the page shows what waits. - `/`: the page (embedded; no inline script or style, no CDN). `/healthz`: `ok`. - Every request to `/mcp` and `/api` (but login) needs `Authorization: Bearer ` made as the Knowledge Kernel makes them (`repos/kernel/kk/cli.py mint`): claims `role`, `iat`, `exp`. diff --git a/mcp-router/api.go b/mcp-router/api.go index f56f5ba..ff379d2 100644 --- a/mcp-router/api.go +++ b/mcp-router/api.go @@ -33,7 +33,8 @@ func (s *Server) apiRoutes(mux *http.ServeMux) { mux.HandleFunc("POST /api/login", s.login) mux.Handle("GET /api/tools", s.auth(http.HandlerFunc(s.apiTools))) mux.Handle("GET /api/calls", s.auth(http.HandlerFunc(s.apiCalls))) - mux.Handle("POST /api/decide", s.auth(http.HandlerFunc(s.apiDecide))) + // No decide: a waiting call is decided by a person in the kernel's review lane (the desktop's Review), and the + // environment module records that decision on the action (S-219). The router only shows what waits. } func writeJSON(w http.ResponseWriter, code int, v any) { @@ -87,25 +88,3 @@ func (s *Server) apiCalls(w http.ResponseWriter, r *http.Request) { } writeJSON(w, 200, b) } - -func (s *Server) apiDecide(w http.ResponseWriter, r *http.Request) { - role, _ := r.Context().Value(roleKey{}).(string) - if !isPerson(role) { - writeJSON(w, 403, map[string]string{"error": "only a person decides"}) - return - } - var in struct { - Action int64 `json:"action"` - Approve bool `json:"approve"` - Reason string `json:"reason"` - } - if json.NewDecoder(http.MaxBytesReader(w, r.Body, 16384)).Decode(&in) != nil || in.Action <= 0 { - writeJSON(w, 400, map[string]string{"error": "bad request"}) - return - } - if err := s.store.Decide(r.Context(), in.Action, in.Approve, role, in.Reason); err != nil { - writeJSON(w, 400, map[string]string{"error": pgMessage(err)}) - return - } - writeJSON(w, 200, map[string]any{"ok": true}) -} diff --git a/mcp-router/results.go b/mcp-router/results.go index 0ee926f..91ab5fa 100644 --- a/mcp-router/results.go +++ b/mcp-router/results.go @@ -81,5 +81,5 @@ func mapOutcome(o Outcome) (res *mcp.CallToolResult, done bool) { } func waitingResult(id int64, status string) *mcp.CallToolResult { - return textResult(true, "action %d is %s: it waits for a person's approval (or its server); ask router_outcome with action %d", id, status, id) + return textResult(true, "action %d is %s: it waits for a person's approval in the desktop's Review (or its server); ask router_outcome with action %d", id, status, id) } diff --git a/mcp-router/router_test.go b/mcp-router/router_test.go index c335e86..77baefa 100644 --- a/mcp-router/router_test.go +++ b/mcp-router/router_test.go @@ -152,9 +152,6 @@ func (f *fakeStore) Outcome(_ context.Context, id int64) (*Outcome, error) { } func (f *fakeStore) ToolsJSON(context.Context) ([]byte, error) { return []byte(`[]`), nil } func (f *fakeStore) CallsJSON(context.Context, int) ([]byte, error) { return []byte(`[]`), nil } -func (f *fakeStore) Decide(_ context.Context, id int64, approve bool, person, reason string) error { - return nil -} func (f *fakeStore) finish(id int64, status string, result string) { f.mu.Lock() o := f.outcomes[id] @@ -276,7 +273,7 @@ func TestAPIAndHeaders(t *testing.T) { t.Errorf("%s: %d", p, r.StatusCode) } } - // an agent role may read but not decide + // an agent role may read; no one decides here (the kernel's review lane does, S-219) agent := mintToken("agent_a", secret, time.Minute, time.Now()) if r := get("/api/calls?limit=5", agent); r.StatusCode != 200 { t.Errorf("calls: %d", r.StatusCode) @@ -292,12 +289,9 @@ func TestAPIAndHeaders(t *testing.T) { } return r } - if r := post("/api/decide", `{"action":1,"approve":true}`, agent); r.StatusCode != 403 { - t.Errorf("agent decide: %d", r.StatusCode) - } person := mintToken("person_ann", secret, time.Minute, time.Now()) - if r := post("/api/decide", `{"action":1,"approve":true}`, person); r.StatusCode != 200 { - t.Errorf("person decide: %d", r.StatusCode) + if r := post("/api/decide", `{"action":1,"approve":true}`, person); r.StatusCode != 404 && r.StatusCode != 405 { + t.Errorf("person decide on the router: %d, want none (decided in the kernel's review lane)", r.StatusCode) } // login r = post("/api/login", `{"name":"ann","password":"pw"}`, "") diff --git a/mcp-router/store.go b/mcp-router/store.go index 0c14b73..e42d9f3 100644 --- a/mcp-router/store.go +++ b/mcp-router/store.go @@ -24,7 +24,6 @@ type Store interface { Outcome(ctx context.Context, id int64) (*Outcome, error) ToolsJSON(ctx context.Context) ([]byte, error) CallsJSON(ctx context.Context, limit int) ([]byte, error) - Decide(ctx context.Context, id int64, approve bool, person, reason string) error } type pgStore struct{ pool *pgxpool.Pool } @@ -87,8 +86,3 @@ func (s pgStore) ToolsJSON(ctx context.Context) ([]byte, error) { func (s pgStore) CallsJSON(ctx context.Context, limit int) ([]byte, error) { return s.json(ctx, `select coalesce(jsonb_agg(c order by c.id desc), '[]'::jsonb) from env.mcp_calls($1) c`, limit) } - -func (s pgStore) Decide(ctx context.Context, id int64, approve bool, person, reason string) error { - _, err := s.pool.Exec(ctx, `select env.decide($1, $2, $3, nullif($4, ''))`, id, approve, person, reason) - return err -} diff --git a/mcp-router/web/app.js b/mcp-router/web/app.js index 00ce5f2..b180795 100644 --- a/mcp-router/web/app.js +++ b/mcp-router/web/app.js @@ -61,28 +61,17 @@ }); $('signout').addEventListener('click', signOut); - function decide(id, approve, reason, box) { - api('/api/decide', { method: 'POST', body: JSON.stringify({ action: id, approve: approve, reason: reason }) }) - .then(refresh) - .catch(function (e) { box.textContent = e.message; }); - } - function renderWaiting(calls) { var box = $('waiting'), w = calls.filter(function (c) { return c.status === 'proposed'; }); $('waiting-count').textContent = w.length ? '(' + w.length + ')' : ''; box.replaceChildren(); if (!w.length) { box.appendChild(el('p', { class: 'muted', text: 'Nothing waits for a decision.' })); return; } + // decided in the desktop's Review (the kernel's review lane, S-219), not here + box.appendChild(el('p', { class: 'muted', text: 'Approve or reject these in the desktop\'s Review window.' })); w.forEach(function (c) { - var reason = el('input', { class: 'reason', placeholder: 'reason', 'aria-label': 'reason for call ' + c.id }); - var err = el('span', { class: 'error' }); - var yes = el('button', { type: 'button', class: 'primary', text: 'Approve' }); - var no = el('button', { type: 'button', text: 'Reject' }); - yes.addEventListener('click', function () { decide(c.id, true, reason.value, err); }); - no.addEventListener('click', function () { decide(c.id, false, reason.value, err); }); box.appendChild(el('div', { class: 'card' }, [ el('div', { class: 'row' }, [el('strong', { text: '#' + c.id + ' ' + c.tool }), el('span', { class: 'muted', text: 'by ' + c.caller + ', ' + when(c.at) })]), - el('pre', { text: JSON.stringify(c.arguments, null, 2) }), - el('div', { class: 'row' }, [reason, yes, no, err]) + el('pre', { text: JSON.stringify(c.arguments, null, 2) }) ])); }); } diff --git a/scripts/assistant.sh b/scripts/assistant.sh index e19111f..7f07828 100755 --- a/scripts/assistant.sh +++ b/scripts/assistant.sh @@ -2,7 +2,9 @@ # The assistant (S-206; the product cut's step 2): a Claude Code session in this terminal that you talk to in the desktop. # It reaches every connected MCP server through the router as its own kernel agent (agent_assistant), so each tool call # is recorded and gated (S-205), and it hears what you say in the desktop's Assistant window through the environment's -# channel (desktop.*.message). Its token (1 day) and MCP settings are written to .state/assistant/ (mode 600), never shown. +# channel (desktop.*.message), which connects as its own login (mcp_channel, S-220). Its token (1 day) and MCP settings, with +# the channel's login, are written to .state/assistant/ (mode 600), never shown. What it asks that changes something waits +# for a person in the desktop's Review (the kernel's review lane, S-219). # # scripts/assistant.sh [NAME] # the stack must be up (scripts/up.sh); then open Assistant in the desktop as NAME # # (default owner): it hears only that person, so a trial's test person is not answered @@ -12,6 +14,9 @@ who=person_$(printf '%s' "${1:-owner}" | tr '-' '_') dir="$ROOT/.state/assistant" mkdir -p "$dir"; chmod 700 "$dir"; umask 077 KK_JWT_SECRET=$(env_value KK_JWT_SECRET); export KK_JWT_SECRET +# the channel's own login (S-220), for its MCP entry; read from the environment below, never printed +CHANNEL_PW=$(env_value MCP_CHANNEL_DB_PASSWORD); CHANNEL_PORT=$(env_value DB_PORT); export CHANNEL_PW CHANNEL_PORT +[ -n "$CHANNEL_PW" ] || { echo "MCP_CHANNEL_DB_PASSWORD is empty: scripts/up.sh makes it and the channel's login (S-220)" >&2; exit 1; } compose run --rm --no-deps -T kernel-init kk agent add assistant --no-login >/dev/null token=$(compose run --rm --no-deps -T -e KK_JWT_SECRET kernel-init kk token agent_assistant --days 1 2>/dev/null | tail -1) [ -n "$token" ] || { echo "could not mint the assistant's token (scripts/logs.sh kernel)" >&2; exit 1; } @@ -22,7 +27,9 @@ cfg = {"mcpServers": { "headers": {"Authorization": "Bearer " + os.environ["TOKEN"]}}, "desktop": {"command": os.path.join(os.environ["ROOT"], "bin/in-tools"), "args": ["python3", "-m", "environment.channel", "assistant_" + os.environ["WHO"], - "desktop." + os.environ["WHO"] + ".message"]}, + "desktop." + os.environ["WHO"] + ".message"], + "env": {"DATABASE_URL": "postgresql://mcp_channel:%s@127.0.0.1:%s/kernel" + % (os.environ["CHANNEL_PW"], os.environ.get("CHANNEL_PORT") or "5432")}}, }} fd = os.open(sys.argv[1], os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w") as f: @@ -37,8 +44,9 @@ You are the assistant in Substrate's desktop (S-206). A person talks to you in t app (id app:maps, app:gateway, app:mcp), view (id view:view-map, view:view-bpm, view:view-modules, search, graph, review) or claim (a claim id). Ask with desktop_ask when you need their decision; their answer comes as a message. - Every other tool (kernel_*, and any server connected later) also goes through the router. A tool that changes - something waits for a person's approval on the MCP router page (Apps, MCP router): tell them what you asked for and - why, and check later with router_outcome. Never claim a change was made until its outcome says applied. + something waits for a person's approval in the desktop's Review window (show it with desktop_show, kind view, id + review): tell them what you asked for and why, and check later with router_outcome. Never claim a change was made + until its outcome says applied. - After handling a channel event, call the channel's ack with its msg_id. Keep replies short and plain. - The person reads the desktop's chat, not this terminal: write nothing here beyond a few words at most, and say everything they should read with desktop_say. Do not narrate your steps in the terminal. diff --git a/scripts/check.sh b/scripts/check.sh index 26bfc16..403b219 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -9,14 +9,14 @@ fails=0 ok() { printf ' ok %s\n' "$*"; } bad() { printf ' FAIL %s\n' "$*"; fails=$((fails + 1)); } note() { printf ' note %s\n' "$*"; } -CORE="db gateway ollama kernel ui caddy mcp-router mcp-kernel desktop mcp-desktop" +CORE="db gateway ollama kernel environment ui caddy mcp-router mcp-kernel desktop mcp-desktop" say "Services ($RUNTIME on $ENGINE)" running=$(rt_status 2>/dev/null | awk 'NR > 1 {print $1}' | tr '\n' ' ') for s in $CORE; do case "$running" in *"-$s-"*) ;; *) bad "service $s is not running (scripts/logs.sh $s)" ;; esac done -extra=$(printf '%s\n' $running | grep -v -e '-db-' -e '-gateway-' -e '-ollama-' -e '-kernel-' -e '-ui-' -e '-caddy-' -e '-mcp-' -e '-desktop-' -e '-llm-' || true) +extra=$(printf '%s\n' $running | grep -v -e '-db-' -e '-gateway-' -e '-ollama-' -e '-kernel-' -e '-environment-' -e '-ui-' -e '-caddy-' -e '-mcp-' -e '-desktop-' -e '-llm-' || true) [ -z "$extra" ] && ok "only the core runs ($CORE)" || note "also running, outside the core: $(echo $extra)" if "$ROOT/bin/in-tools" python3 -c ' import sys; sys.path.insert(0, "scripts") @@ -53,8 +53,10 @@ import sys; sys.path[:0] = ["scripts", "."] from db import connect, DB; from gateway import settings with connect(settings(), DB) as c: s, q, a, w = c.execute("select (select count(*) from env.signal), (select count(*) from pgmq.meta), (select count(*) from env.actuator), (select count(*) from env.action where status = $$proposed$$)").fetchone() - print(f"{s} signals, {q} queues, {a} actuators, {w} proposals waiting")' 2>&1); then - ok "environment $out (bin/in-tools python3 scripts/env.py waiting)" + m = c.execute("select to_regclass($$kernel.agent$$) is not null and exists (select 1 from kernel.agent where iri = $$urn:kk:agent:environment$$)").fetchone()[0] + if not m: raise SystemExit("not installed as a kernel module (scripts/kernel.sh init)") + print(f"{s} signals, {q} queues, {a} actuators, {w} proposals waiting in the review lane")' 2>&1); then + ok "environment $out (a kernel module, S-219: decided in the desktop's Review)" 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 diff --git a/scripts/db.py b/scripts/db.py index 0b695c3..1d2b80e 100644 --- a/scripts/db.py +++ b/scripts/db.py @@ -65,10 +65,11 @@ def init(env: dict[str, str]) -> None: logins(env) -# The environment's logins (S-205): each a login role granted one of the roles environment/sql/010_mcp.sql makes, its +# The environment's logins (S-205, S-220): each a login role granted one of the roles environment/sql/ makes, its # password from .env. Made if missing, its password set each time (so a changed .env takes effect). LOGINS = (("mcp_router", "env_router", "MCP_ROUTER_DB_PASSWORD"), ("mcp_connector", "env_connector", "MCP_CONNECTOR_DB_PASSWORD"), - ("mcp_desktop", "env_desktop", "MCP_DESKTOP_DB_PASSWORD")) + ("mcp_desktop", "env_desktop", "MCP_DESKTOP_DB_PASSWORD"), + ("mcp_channel", "env_agent", "MCP_CHANNEL_DB_PASSWORD")) # the channel into a harness (S-220) def logins(env: dict[str, str]) -> None: diff --git a/scripts/env.py b/scripts/env.py index 9d01c6f..c54b9f0 100644 --- a/scripts/env.py +++ b/scripts/env.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 -"""The real-time environment from the command line (plan step 3c): what a person does until the UI has a review lane. +"""The real-time environment from the command line (plan step 3c). A proposal is decided in the desktop's Review (the +kernel's review lane, S-219), not here: the environment module records that decision on the action. bin/in-tools python3 scripts/env.py waiting # proposals waiting for a person - bin/in-tools python3 scripts/env.py decide ACTION yes|no [REASON] --as NAME bin/in-tools python3 scripts/env.py publish KEY JSON --as SOURCE # e.g. owner.inbox.message '{"text":"hi"}' bin/in-tools python3 scripts/env.py actuators # each actuator, its gate and queue bin/in-tools python3 scripts/env.py gate NAME free|propose|deny --as NAME @@ -34,8 +34,6 @@ def main(argv: list[str]) -> None: if cmd == "waiting": for w in e.waiting(): print(f"{w['id']} {w['actuator']} {json.dumps(w['input'])} by {w['caller']} at {w['at']:%Y-%m-%d %H:%M}") - elif cmd == "decide" and len(args) >= 2 and who: - print(e.decide(int(args[0]), args[1] in ("yes", "y", "approve"), who, " ".join(args[2:]) or None)) elif cmd == "publish" and len(args) == 2 and who: print(f"signal {e.publish(args[0], json.loads(args[1]), who)}") elif cmd == "actuators": diff --git a/scripts/gateway.py b/scripts/gateway.py index fab8944..53bc1f4 100644 --- a/scripts/gateway.py +++ b/scripts/gateway.py @@ -34,7 +34,7 @@ "GATEWAY_REQUESTS_PER_HOUR", "GATEWAY_DB_PASSWORD", "GATEWAY_METER_PASSWORD", "GATEWAY_KEY_SECRET", "GATEWAY_PORT", "ANTHROPIC_MODELS", "COMPANION_MODELS", "LLM_MODEL", "LLM_FAST_MODEL", "KERNEL_URL", "KK_AUTHENTICATOR_PASSWORD", "MCP_ROUTER_DB_PASSWORD", - "MCP_CONNECTOR_DB_PASSWORD", "MCP_DESKTOP_DB_PASSWORD") + "MCP_CONNECTOR_DB_PASSWORD", "MCP_DESKTOP_DB_PASSWORD", "MCP_CHANNEL_DB_PASSWORD") def settings() -> dict[str, str]: diff --git a/scripts/kernel.sh b/scripts/kernel.sh index 13a51aa..e7c31a4 100755 --- a/scripts/kernel.sh +++ b/scripts/kernel.sh @@ -2,7 +2,8 @@ # The Knowledge Kernel (S-153, S-154): its schema, Substrate's catalog in it, an agent's login, and the MCP server Claude Code starts. The kernel runs in its own image (published, or scripts/build.sh kernel) # in the stack's Postgres, database `kernel` (scripts/db.py init makes it); nothing is installed on the host. # -# scripts/kernel.sh init # install the kernel's schema and default modules (safe to run again) +# scripts/kernel.sh init # install the kernel's schema and default modules, then Substrate's kernel modules +# # (environment/, by kk module install, S-219); safe to run again # 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 @@ -22,6 +23,11 @@ image() { image_ref kernel; } case "${1:-}" in init) compose run --rm --no-deps kernel-init + # Substrate's kernel modules, through the kernel's module contract (S-219): the manifest checked, its migration applied + # once; the module's service (compose `environment`) acts as the kernel's login switched to its role, so the login + # kk module install writes for it is not used (written to the container's /tmp and gone with it) + compose run --rm --no-deps -T kernel-init kk module install /substrate/environment --out /tmp/modules | grep '^{' | tail -1 | + python3 -c 'import json, sys; r = json.load(sys.stdin); print(" module %s %s: migration %s" % (r["module"], r["version"], r["migration"]))' ;; catalog) compose run --rm --no-deps kernel-catalog diff --git a/scripts/test.sh b/scripts/test.sh index 337dbeb..b374a09 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -4,7 +4,7 @@ # scripts/test.sh # all of them # scripts/test.sh FILE... # some: scripts/tests/test_gateway.py, ..., or mcp-router (its Go tests) # -# The tests that start a throwaway Knowledge Kernel (KERNEL_TESTS: the kernel's and the UI's, S-154) run in the kernel's +# The tests that start a throwaway Knowledge Kernel (KERNEL_TESTS: the kernel's, the UI's and the review lane's, S-154, S-219) run in the kernel's # image instead (published, or scripts/build.sh kernel), on the host network, with this checkout mounted read-only: `kk`, its modules # and the MCP server are there, and the tools container has none of them. set -eu @@ -12,7 +12,7 @@ set -eu url="postgresql://postgres:$(env_value POSTGRES_PASSWORD)@127.0.0.1:$(env_value DB_PORT)/postgres" [ $# -gt 0 ] || set -- "$ROOT"/scripts/tests/test_*.py "$ROOT"/mcp-router -KERNEL_TESTS="scripts/tests/test_kernel.py scripts/tests/test_ui.py" +KERNEL_TESTS="scripts/tests/test_kernel.py scripts/tests/test_ui.py scripts/tests/test_review.py" kimage=$(image_ref kernel) # the kernel's login role is shared by the cluster: its fixture keeps the stack's password (passed by name, not value) KK_AUTHENTICATOR_PASSWORD=$(env_value KK_AUTHENTICATOR_PASSWORD); export KK_AUTHENTICATOR_PASSWORD diff --git a/scripts/tests/test_environment.py b/scripts/tests/test_environment.py index b503a86..f8e4d82 100644 --- a/scripts/tests/test_environment.py +++ b/scripts/tests/test_environment.py @@ -9,8 +9,9 @@ - apply its schema once (environment/sql/, environment/db.py), and again without change - give an MCP tool its gate from its annotations when registered, follow them while no person has set the gate (both directions, a deployment's policy first), and keep a gate a person set -- as the channel (stdio MCP): declare claude/channel, push a subscribed signal as notifications/claude/channel, - push it again while unacknowledged, stop once ack is called, and act through the gates +- as the channel (stdio MCP), on a login of its own (role env_agent, S-220): declare claude/channel, push a subscribed + signal as notifications/claude/channel, push it again while unacknowledged, stop once ack is called, and act through + the gates; never decide a proposal, change a gate or read another's queue scripts/test.sh scripts/tests/test_environment.py """ @@ -164,7 +165,7 @@ class Proc: def __init__(self, url, vt): self.p = subprocess.Popen([sys.executable, "-m", "environment.channel", "chan", "home.owner.*"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=ROOT, - env={**os.environ, "STORE_URL": url, "CHANNEL_VT": str(vt), "CHANNEL_POLL": "0.2"}) + env={**os.environ, "DATABASE_URL": url, "CHANNEL_VT": str(vt), "CHANNEL_POLL": "0.2"}) self.q = queue.Queue() threading.Thread(target=lambda: [self.q.put(json.loads(l)) for l in self.p.stdout], daemon=True).start() @@ -191,6 +192,24 @@ def call(self, mid, name, args): def channel(e: Env, url: str): + # the channel's own login, as scripts/db.py makes mcp_channel: role env_agent (roles are the cluster's: dropped after) + login, pw = f"chan_test_{os.getpid()}", os.urandom(12).hex() + e.c.execute(f"create role {login} login password '{pw}' in role env_agent") + own = url.replace(url.split("//", 1)[1].split("@", 1)[0], f"{login}:{pw}", 1) + try: + with psycopg.connect(own, autocommit=True) as c2: + mine = Env(c2) + a, _ = e.act("home.budget", {"cap_usd": 2}, "claude-code") + check("channel login: may not decide a proposal", refused(lambda: mine.decide(a, True, "owner"), "permission denied")) + check("channel login: nor change a gate", refused(lambda: mine.actuator("home.budget", "free", "x"), "permission denied")) + check("channel login: nor read a queue it did not subscribe", refused(lambda: mine.read("review", 0), "may not read")) + channel_session(e, own) + finally: + e.c.execute(f"drop owned by {login}") + e.c.execute(f"drop role {login}") + + +def channel_session(e: Env, url: str): ch = Proc(url, vt=2) try: ch.send({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { diff --git a/scripts/tests/test_review.py b/scripts/tests/test_review.py new file mode 100644 index 0000000..6d4dc3e --- /dev/null +++ b/scripts/tests/test_review.py @@ -0,0 +1,160 @@ +"""The environment as a kernel module (S-219): a proposed action waits in the kernel's review lane and a person's +decision there is the action's. In a throwaway kernel with the environment's schema beside it (ADMIN_URL from +scripts/test.sh; it runs in the kernel's image). It should: +- install through the kernel's module contract (`kk module install environment`): its manifest checked, its role and + agent made, and installing again changing nothing +- submit each waiting action once, as a change set in the review lane that the kernel holds for a reviewer, saying + what is asked, by whom, of which actuator, with its input in full; an MCP tool by the name its caller used +- record a person's approval there on the action (queued for its actuator, decided by that person), and keep the + approved request as claims +- record a rejection (refused, with the reviewer's note), and refuse a proposal its own caller approved +- leave the decision to the module: the MCP router may no longer decide; the module may decide, and do nothing else + in the environment + + scripts/test.sh scripts/tests/test_review.py +""" +import json +import os +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +import psycopg + +ROOT = Path(__file__).resolve().parents[2] +sys.path[:0] = [str(Path(__file__).resolve().parent), str(ROOT)] +import kernelfx # noqa: E402 + +checks = [] + + +def check(name, ok, detail=""): + checks.append(bool(ok)) + print(("ok " if ok else "FAIL"), name, "" if ok else detail) + + +def main(): + k = None + try: + k = kernelfx.Kernel(os.environ["ADMIN_URL"]) + run(k) + except Exception as e: # a missing kernel is a failure, named + checks.append(False) + print("FAIL the review lane:", type(e).__name__, e) + finally: + if k: + k.close() + print(f"{sum(checks)}/{len(checks)} checks passed") + sys.exit(0 if all(checks) else 1) + + +def kk(k, *args): + out = subprocess.run([sys.executable, "-m", "kk", *args], env=k.env, capture_output=True, text=True) + if out.returncode: + raise RuntimeError(f"kk {' '.join(args)}: {out.stderr.strip()[-400:]}") + return json.loads(out.stdout.strip().splitlines()[-1]) + + +def status(admin, cs_key, want, seconds=30): + with psycopg.connect(admin, autocommit=True) as c: + for _ in range(seconds * 4): + r = c.execute("select status from kernel.change_set where idempotency_key = %s", (cs_key,)).fetchone() + if r and r[0] in want: + return r[0] + time.sleep(0.25) + return r and r[0] + + +def run(k): + from environment import Env + from environment import db as envdb + from environment.review import one_pass + from kk.lib import connect + + with psycopg.connect(k.admin, autocommit=True) as c: + envdb.migrate(c) + with tempfile.TemporaryDirectory() as out: + first = kk(k, "module", "install", str(ROOT / "environment"), "--out", out) + again = kk(k, "module", "install", str(ROOT / "environment"), "--out", out) + check("installs through the kernel's module contract", first.get("module") == "urn:kk:module:environment" + and first.get("migration") == "applied", first) + check("and installing again applies nothing", again.get("migration", "").startswith("skipped"), again) + kk(k, "agent", "add", "assistant", "--no-login") + kk(k, "person", "add", "tester", "--no-login") + + admin = psycopg.connect(k.admin, autocommit=True) + e = Env(admin) + with admin.transaction(): + agent = admin.execute("select iri, db_role from kernel.agent where iri = 'urn:kk:agent:environment'").fetchone() + check("its agent and role are the kernel's", agent == ("urn:kk:agent:environment", "kkm_environment"), agent) + priv = admin.execute("select has_function_privilege('env_router', 'env.decide(bigint,boolean,text,text)', 'execute'), " + "has_function_privilege('kkm_environment', 'env.decide(bigint,boolean,text,text)', 'execute'), " + "has_function_privilege('kkm_environment', 'env.act(text,jsonb,text)', 'execute'), " + "has_function_privilege('kkm_environment', 'env.actuator(text,text,text,text)', 'execute')").fetchone() + check("the router may no longer decide; the module may, and may not act or set a gate", priv == (False, True, False, False), priv) + + q = e.actuator("shop.refund", "propose", "person_owner", "Refund an order") + a1, st1 = e.act("shop.refund", {"order": 1042, "amount_eur": 30}, "agent_assistant") + a2, _ = e.act("shop.refund", {"order": 77, "amount_eur": 9000}, "agent_assistant") + a3, _ = e.act("shop.refund", {"order": 5, "amount_eur": 1}, "person_tester") + admin.execute("select * from env.mcp_register('crm', 'http', '{}', '{}', %s::jsonb, 'connector:crm')", + (json.dumps([{"name": "update_contact", "annotations": {}}]),)) + a4, st4 = admin.execute("select * from env.mcp_call('crm_update_contact', %s, 'agent_assistant')", + (json.dumps({"id": 3, "email": "a@example.org"}),)).fetchone() + check("four actions wait for a person", (st1, st4) == ("proposed", "proposed"), (st1, st4)) + + mod = connect("kkm_environment", url=k.url) + did = one_pass(mod) + check("one pass submits each waiting action to the review lane", sorted(did["submitted"]) == sorted([a1, a2, a3, a4]), did) + held = status(k.admin, f"environment:action:{a1}", {"awaiting_review"}) + check("the kernel holds it for a reviewer", held == "awaiting_review", held) + for a in (a2, a3, a4): + status(k.admin, f"environment:action:{a}", {"awaiting_review"}) + check("a second pass submits nothing again", one_pass(mod)["submitted"] == []) + + with admin.transaction(): + admin.execute("set local role person_owner") + queue = {r[0]: r[1] for r in admin.execute( + "select c.idempotency_key, q.ops from api.review_queue q join kernel.change_set c on c.id = q.id")} + ops = queue.get(f"environment:action:{a1}") or [] + said = {o["predicate"].rsplit("/", 1)[-1].rsplit("#", 1)[-1]: o["object"] for o in ops} + check("Review shows the request: an actuation, by its actuator", said.get("type", {}).get("entity") == "http://www.w3.org/ns/sosa/Actuation" + and said.get("madeByActuator", {}).get("entity") == "urn:kk:environment:actuator:shop.refund", said) + check("who asked, as the kernel's agent", said.get("actor", {}).get("entity") == "urn:kk:agent:assistant", said) + check("and its input in full", json.loads(said.get("description", {}).get("value", {}).get("@value", "null")) + == {"order": 1042, "amount_eur": 30}, said) + lab4 = next((o["object"]["value"]["@value"] for o in queue.get(f"environment:action:{a4}") or [] + if o["predicate"].endswith("label")), "") + check("an MCP tool is named as its caller called it", lab4.startswith("crm_update_contact, asked by agent_assistant"), lab4) + + def review(action, approve, who, note=None): + with admin.transaction(): + cs = admin.execute("select id from kernel.change_set where idempotency_key = %s", (f"environment:action:{action}",)).fetchone()[0] + admin.execute(f"set local role {who}") + return admin.execute("select api.review(%s, %s, %s)", (cs, approve, note)).fetchone()[0] + + check("a person approves it in the review lane: the kernel applies it", review(a1, True, "person_owner") == "applied") + review(a2, False, "person_owner", "too much; call the customer") + review(a3, True, "person_tester") + did = one_pass(mod) + check("the module records each decision", (did["approved"], did["rejected"], did["refused"]) == ([a1], [a2], [a3]), did) + row = admin.execute("select status, decided_by from env.action where id = %s", (a1,)).fetchone() + msgs = e.read(q, 0) + check("approved: queued for its actuator, decided by that person", row == ("queued", "person_owner") + and [m["action"] for m in msgs] == [a1], (row, msgs)) + kept = admin.execute("select count(*) from kernel.claim where subject = %s", (f"urn:kk:environment:action:{a1}",)).fetchone()[0] + check("and the approved request is kept as claims", kept == 5, kept) + row = admin.execute("select status, decided_by, reason from env.action where id = %s", (a2,)).fetchone() + check("rejected: refused, with the reviewer's note", row == ("refused", "person_owner", "too much; call the customer"), row) + row = admin.execute("select status, reason from env.action where id = %s", (a3,)).fetchone() + check("approved by its own caller: refused, saying why", row[0] == "refused" and "who asked for it" in (row[1] or ""), row) + check("the MCP call still waits, nothing else changed", one_pass(mod)["waiting"] == [a4] + and e.status(a4) == "proposed") + mod.close() + admin.close() + + +if __name__ == "__main__": + main()