diff --git a/CLAUDE.md b/CLAUDE.md index e883c7a..d2389d8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,10 +25,11 @@ removed on 2026-11-23 (S-194): the assistant starts again from scratch, not port | 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, 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) | | 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 | -`deploy/caddy` (in front of the UI) and `deploy/ontop` (SPARQL) are kept and not started yet. +`deploy/ontop` (SPARQL) is kept and not started yet. ## Rules @@ -71,9 +72,9 @@ 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 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, llm, llm-fast +scripts/logs.sh SERVICE # db, gateway, ollama, kernel, ui, caddy, llm, llm-fast scripts/tools.sh start|stop|status -scripts/kernel.sh init|catalog|login NAME|mcp NAME # the Knowledge Kernel: its schema, the catalog into it, an agent's login and its MCP server +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/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 31ed813..1f30c55 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -204,3 +204,7 @@ Status: **decided** (owner agreed), **adopted** (recommended and taken; confirm | S-194 | **The assistant starts again from scratch; nothing of it is ported** (2026-11-23; the owner, after using the voice interface: "please stop the voice head and its secondary model... its pretty fucked up. we'll need to completely restart on what we've just put together"; then "rt_down then... i'm not impressed with how the assistant works and we'll want to start from scratch rather than porting it"). Supersedes plan step 3's porting of the assistant's parts (S-185, S-186: the companion, the voice head and avatar, the worker, blocks and the skill gate, the ladder's code) into `distributions/assistant/`. (a) **The stack is down** (`scripts/down.sh`, data kept); the voice head and the fast model were stopped first. (b) **Nothing is ported:** `distributions/assistant/` will be designed anew, on the settled shape (OpenEnv environments, the kernel, Morphogen as its judge), when the owner says what it should do; until then the old parts stay in the tree, unused, and are removed in one commit once the owner agrees (git keeps them). (c) **What stands:** Substrate's own parts (the stack, the gateway and its meter, the kernel, the catalog, the skills, OpenEnv per S-192, Morphogen per S-193); the ladder's design (S-178 to S-183) and the OpenEnv findings are inputs to the new assistant, not commitments. The first Morphogen cell, `voice-route`, measured the old voice head: it stays as the worked example of the judge until a cell on a part that stays replaces it. | decided | | S-195 | **The old assistant's code is removed; the old store's export step goes with it** (2026-11-23; the owner: "yes, remove the old assistant code"; follows S-194). On branch `claude/retire-assistant`. (a) **Removed:** `voice/`, `blocks/`, `judge/`, `deploy/companion`, `deploy/worker`, `deploy/searxng`, `environment/{companion,worker,author,judge,experience}.py`, `environment/sql/007_components.sql` and `008_experience.sql`, `scripts/companion.sh`, the trials `decider`, `voice-gpu`, `voice-head`, `voice-route`, `offline-agent`, their test suites (`test_blocks`, `test_companion`, `test_components`, `test_experience`, `test_voice_route`, `test_worker`, and `stub_memory_mcp.py`); compose services `environment`, `companion`, `judge`, `tts`, `voice`, `search`, `worker` and their volumes; the images `companion` and `worker` (workflow and `scripts/build.sh`); the gateway's callers `companion:*`, `voice:head`, `judge:voice`, `worker:loop` (left: `store:embed`, `morphogen:judge`); the database logins in `scripts/db.py`; 21 catalog entries; the UI's `#/companion` and `#/worker` pages and every write it had (it is now read-only, on the kernel only); their settings in `.env.example` and `deploy/secrets.txt` (`COMPANION_MODELS` becomes `ANTHROPIC_MODELS`, the old name still read). The first Morphogen cell `voice-route` (S-193) went with the voice head; its verdict stays in the evidence log. (b) **Data:** the `env` and `pgmq` schemas were dumped first (`.state/backups/substrate-env-pgmq-20261123-125241.sql`: 438 signals, 60 actions, 3 components, 2 verdicts, no experience); migration `009_retire_assistant.sql` drops 007's and 008's tables and functions, the old actuators and their queues, readers and bindings, and the logins `companion`, `worker`, `judge` and role `env_judge`; dry-run in a rolled-back transaction, then applied. The environment itself stays (005, 006: signals, subscribers, actuators behind gates, the channel); `test_environment` now uses the namespace `home`. (c) **Kept:** both local models (`llm`, `llm-fast`, the stack's `slow` and `fast` roles), the Anthropic provider in the gateway (no caller reaches it now), the channel. (d) **Found on the way:** `scripts/up.sh` still ran `scripts/kernel.sh export`, the one-off export of the `store` schema dropped in S-191, so `up.sh` failed from then on; the step, the `export` verb, the `kernel-export` service and its catalog entry are removed. `scripts/check.sh` and all five remaining suites pass (catalog 9, environment 36, gateway 15, kernel 27, UI 36). | done | | S-196 | **envkit is retired; uv is allowed on the host; the machine and the repository tidied** (2026-11-23; the owner: "why keep envkit if we're using openenv? cleanup companion-home, remove unused images, clean .env, clean git. rule 6 is your call"). (a) **envkit removed** (`envkit/`, its `CLAUDE.md` row): OpenEnv is the environment standard (S-184, S-192), and MetaSoar's `main` does not import it (only its unmerged `claude/envkit` branch does); git keeps it. (b) **Rule 6 amended:** the host may also have **uv**, because Claude Code plugins run their MCP servers with it (Morphogen's `plugin.json` runs `uv run ... morphogen-mcp`) and containerising that would mean our own plugin configuration outside Morphogen's contract; `scripts/bootstrap.sh` shows it. (c) **The OpenEnv trial's image** stands alone (Python 3.13.17, psycopg 3.3.6, openenv 0.12.0, Claude Code 2.1.311 by the same pinned checksum), no longer built on the retired companion image. (d) **This machine:** volume `substrate_companion-home` deleted (it held the companion's Claude login); 37 image tags removed, images 40.05 GB to 12.75 GB, keeping the stack's (Bifrost v2.3.2, Ollama 0.40.12, llama.cpp b12627, kernel, substrate-db, substrate-tools), their bases, Caddy and Ontop (kept parts), the OpenEnv trial and MetaSoar's two; `.env` backed up (`.state/backups/env-before-s196-*`, mode 600), then 30 old assistant settings and their comments removed, `COMPANION_MODELS` renamed `ANTHROPIC_MODELS`, `COMPOSE_PROFILES=llm`. The volumes `voice-models`, `worker-workspace` and `search-cache` and about 55 anonymous ones remain until the owner says. (e) **Git:** merged branches deleted (their only commits beyond `main` are merge commits with no file difference); `seed`, `direction/experiment-first` and `game-catalogs` (unique work, no merged pull request) kept as tags `archive/*` before their branches went; PR #23 retargeted to `main` (PR #22 was merged before the S-193 and S-194 commits were pushed, so #23 carries them). | done | +| S-197 | **The pins moved to what runs; Morphogen's clone in `repos/`; the dropped `store` schema has no readers left** (2026-11-23; the handoff's loose ends 1 to 3; the owner: "work the handoff's loose ends in order"). (a) **Kernel:** PR #136 (D-125, D-126 onto `main`) merged as `e176b03`; its published image `ghcr.io/openreplicant/kernel:main` carries that revision (label `org.opencontainers.image.revision`), `scripts/up.sh` applied its schema 003 to 006, and `check.sh` and all five suites pass on it, so `repos.yaml`'s kernel `checked` is `e176b03`; `repos/kernel` moved from `claude/one-database` to `main`. (b) **Morphogen's one location is `repos/morphogen`** (S-11, the `upstream` skill): cloned there from GitHub at `9769a0b`, the commit the plugin is pinned to in `.claude/settings.json` (S-193), and `repos.yaml`'s `checked` is that commit; the two pins move together. `~/Projects/Morphogen` is the owner's own checkout, no longer named by Substrate. (c) **No old schema in the tests:** `test_kernel` and `test_ui` build their fixtures in memory (`scripts/tests/seed.py`, the plain rows the kernel's encoder-substrate takes) and submit them into the throwaway kernel through the encoder's own `export`, in its role (`kernelfx.Kernel.seed`); `scripts/tests/oldschema/` (the old schema's SQL and writer) is removed, and no throwaway `store` database is made; same checks, same counts (27, 36). The encoder stays because the kernel's `substrate` MCP profile writes claims in its shapes. (d) **Trials:** `embedding-model` removed (parked, S-142; it read `store.page`; git keeps it); `map-diagram/cases.py` reads Substrate's map through the UI's API (`/api/map/Q10`) and is kept, because `ui/static/vendor/VENDOR.md` cites its `fetch.py`. Left for step 4: `environment/db.py`'s carry-over of `public.store_migration` records. Empty leftover folders `blocks/`, `store/`, `voice/` (only `__pycache__`) deleted. | done | +| S-198 | **The optimiser is a slot with two fillers: Morphogen for files and settings, OpenEnv's rubrics for behaviour** (2026-11-23; the owner: "sounds like morphogen isn't the only optimization method in the system now that we integrated openenv", then "yes, record it"). Amends S-185's slot table (`docs/framework.md`, "Slots" and "Optimise"). (a) **Morphogen** (its cell contract, S-193) changes what a cell's `change` names, files and settings, and its judge scores a candidate by the cell's tests and measure. (b) **An OpenEnv environment** (S-184, S-192) scores a model's or a policy's episodes by its rubrics; a trainer (reinforcement learning, distillation) learns from those scores, and the result (weights, a compiled skill, a router) is judged on held-out episodes before it is used. S-192's point 7 (a rubric's score attached to every model call of its episode) is what makes this possible. (c) **One rule over both:** whatever is changed cannot edit what judges it (a cell's tests and scorer, an environment's rubric and held-out episodes), and a winner is a proposal the person approves. (d) **The `optimize` skill** (plan step 5) picks which one for a target: a change to text or configuration goes to Morphogen; a change to how a model behaves on a task family goes to an environment and a trainer. Nothing is built by this row; the trainer is picked with the `research` skill when a step needs one (plan step 9, M-17, is the first candidate). | decided | +| S-199 | **The front door: Caddy in front of the kernel's UI shell, the first step to one pluggable desktop** (2026-11-23; the owner: "i want to see a web UI... maybe all we need is a UI for kernel that's pluggable (i had a fascination with desktop WM styling, which requires iframes with proper security headers)", then "yes... start step 1"). (a) **One UI, the kernel's** (recommended and taken): the kernel's shell (`modules/ui`, the kernel's D-44: an MCP client with the person's own token; search, review, change sets, the graph; view modules that register themselves) grows into the desktop, in the kernel's repository by pull request; Substrate's `ui/` folds into it later as a view module or a framed app. (b) **This step:** the `kernel` service now runs `kk serve --host 0.0.0.0 --port 8000 --only mcp,validator` (it ran only the validator), and a new compose service `caddy` (`docker.io/library/caddy:2.11.7-alpine`, the version the kernel's own deploy pins; `deploy/caddy/Caddyfile` replaces v1's Workbench file) serves it on `127.0.0.1:${DESKTOP_PORT:-8080}`: `/` goes to `/ui/`, `/mcp*` and the rest to the kernel. Locked like the other services (read-only, no-new-privileges, `cap_drop: ALL`), with `/data` and `/config` on tmpfs and `admin off`; it keeps one capability, `NET_BIND_SERVICE`, as the container's root (the owner's user under rootless Podman), because the image's binary carries that file capability and an unprivileged user cannot exec it under no-new-privileges (found: `exec /usr/bin/caddy: operation not permitted`). (c) **Checked:** `/ui/` answers 200 with the kernel's own headers (its CSP with `frame-ancestors 'none'`, nosniff, no-referrer); `/ui/views.json` lists view-bpm, view-devops, view-map, view-modules; `/mcp` lists tools without a token but refuses a call ("no bearer token"); `/ui/login` refuses a wrong password (401). `scripts/check.sh` checks the shell through the door, `caddy` is in its core, and the catalog has `component:caddy` and `api:kernel-http` (provided by the kernel). (d) **Signing in:** `scripts/kernel.sh person NAME` (`kk person add`: a reviewer's login) keeps the password in `.state/kernel/person-NAME.password` (mode 600) and prints only where it is, because `kk person add` prints it. (e) **Next (the spike):** windows and a launcher in the shell; framed apps each on an origin of their own (a site block each in the Caddyfile: a sandboxed frame on the shell's own origin with scripts and same-origin allowed could undo its sandbox), the shell's CSP `frame-src` naming them, each sending `frame-ancestors` for the shell (Caddy adds it for apps that do not), the person's token never in a frame and a small message bridge granting what a frame may do; an app that refuses framing opens in its own window; three apps first (a view module, Bifrost's dashboard, Substrate's map), checked by the kernel's browser test for headers and no CSP violations. The shell's CSP needs `'unsafe-eval'` for Alpine.js today; Alpine's CSP build would drop it (to check in the spike). | done | +| S-200 | **The desktop: the kernel's shell with windows, and framed apps behind the proxy on origins of their own** (2026-11-23; the owner: "signed in, start the spike ... the UI looks bad, but we'll work on it", then "caddy should be able to fix headers via proxy"; follows S-199 (e)). (a) **The kernel's part** is its D-127 (kernel PR #137, branch `claude/desktop`, `modules/ui` 0.3.0): a launcher (Kernel, Views, Apps) and windows (move, resize, front, minimise, maximise, close, places kept); framed apps from `/ui/apps.json` when the front door serves one; an app on the shell's own origin refused; the sandboxed frame, no referrer, no permissions; a bridge taking only `title` and `open` from an app's own frame and origin; the token box a plain text box with autofill off (the owner's "invalid token: Not enough segments" was a password manager filling it). Found on the way and fixed there: an Alpine `:style` string replaces the whole style attribute and wiped `x-show`'s `display:none`, so closed windows showed (an object binding now). (b) **Substrate's part, all in the proxy** (the owner's point: no app's code changes): Caddy serves `deploy/caddy/apps.json` at `/ui/apps.json` and rewrites the shell's CSP to add `frame-src http://127.0.0.1:8081 http://127.0.0.1:8082`; `:8081` proxies Bifrost's dashboard, deleting its `X-Frame-Options: DENY` and replacing only `frame-ancestors 'none'` with the desktop's origins (`http://127.0.0.1:8080 http://localhost:8080`); `:8082` does the same for the map pages (`ui/`), whose CSP is otherwise unchanged. Caddy's `header_down` replaces by an RE2 expression (its reverse_proxy docs, read 2026-11-23); the patterns have no special characters. The ports are fixed (8080, 8081, 8082, all on 127.0.0.1), because the origins are named in apps.json and the headers; `DESKTOP_PORT` (S-199) is dropped. (c) **Checked:** the trial `scripts/trials/desktop/` (`run.sh`, the map-diagram trial's pinned Playwright 1.64.1 image, host network, the person's password passed by name) passes 23/23 against the stack with the kernel serving the branch's shell (a local compose override, `.state/trials/desktop/dev.yaml`, not committed): sign-in, the launcher's three groups, windows opening in front, focus, moving, minimising, restoring, closing, no closed window showing, a view module in its window, both apps loaded from their own origins in sandboxed frames, the bridge renaming an app's window and ignoring the same message from the shell's own page, the token in no frame, an unlisted origin (the gateway's own port 8090) refused by the CSP, Chromium's sandbox warning once per app frame and for nothing else, no page errors, no other CSP violations; results and screenshots in `.state/trials/desktop/`. `scripts/check.sh` checks the shell's `frame-src` and each app's headers. (d) **Left:** the look (the owner: "we'll work on it"); Alpine's CSP build to drop `'unsafe-eval'`; Substrate's `ui/` as a view module rather than a framed app, when the map pages are rebuilt on the kernel; once kernel PR #137 is merged and its image published, the stack runs it without the override. | done | diff --git a/catalog/api-kernel-http.yaml b/catalog/api-kernel-http.yaml new file mode 100644 index 0000000..b3d3e38 --- /dev/null +++ b/catalog/api-kernel-http.yaml @@ -0,0 +1,31 @@ +# 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-http + title: The kernel over HTTP +spec: + type: http + lifecycle: experimental + owner: owner + system: substrate + definition: |- + { + "openapi": "3.1.0", + "info": { + "title": "kk serve: the UI shell and its view modules under /ui, MCP (streamable HTTP) at /mcp", + "version": "0" + }, + "paths": { + "/ui/": { + "get": { + "summary": "the UI shell (the kernel's D-44)" + } + }, + "/mcp": { + "post": { + "summary": "MCP over streamable HTTP, with the caller's bearer token" + } + } + } + } diff --git a/catalog/catalog-info.yaml b/catalog/catalog-info.yaml index f29afff..8286f60 100644 --- a/catalog/catalog-info.yaml +++ b/catalog/catalog-info.yaml @@ -9,6 +9,7 @@ spec: - ./api-anthropic-api.yaml - ./api-anthropic-messages.yaml - ./api-embeddings.yaml + - ./api-kernel-http.yaml - ./api-kernel-mcp-memory.yaml - ./api-kernel-mcp-substrate.yaml - ./api-llama-chat-fast.yaml @@ -18,6 +19,7 @@ spec: - ./api-ollama-api.yaml - ./api-ui-http.yaml - ./component-anthropic.yaml + - ./component-caddy.yaml - ./component-environment.yaml - ./component-gateway.yaml - ./component-kernel-catalog.yaml diff --git a/catalog/component-caddy.yaml b/catalog/component-caddy.yaml new file mode 100644 index 0000000..ca66365 --- /dev/null +++ b/catalog/component-caddy.yaml @@ -0,0 +1,22 @@ +# A catalog entry (S-176): Backstage's entity format, read into the kernel by encoder-backstage. +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: caddy + title: The front door + description: Caddy in front of the kernel's UI shell (/ui, the desktop) and MCP server (/mcp) on 127.0.0.1:8080, and the desktop's framed apps on origins of their own (8081 the gateway's dashboard, 8082 the map pages). + annotations: + substrate.dev/licence: Apache-2.0 + substrate.dev/image: docker.io/library/caddy + substrate.dev/compose-service: caddy + substrate.dev/decision: S-199, S-200 +spec: + type: service + lifecycle: experimental + owner: owner + system: substrate + consumesApis: + - kernel-http + - ui-http + dependsOn: + - component:kernel diff --git a/catalog/component-kernel.yaml b/catalog/component-kernel.yaml index 27a197c..1c825a5 100644 --- a/catalog/component-kernel.yaml +++ b/catalog/component-kernel.yaml @@ -4,16 +4,18 @@ kind: Component metadata: name: kernel title: The Knowledge Kernel - description: Claims with provenance, belief and clearance; validator and belief model (kk serve). + description: Claims with provenance, belief and clearance; kk serve runs the validator, MCP over HTTP and the UI shell. 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 + substrate.dev/decision: S-153, S-154, S-199 spec: type: service lifecycle: experimental owner: owner system: substrate + providesApis: + - kernel-http dependsOn: - resource:db diff --git a/deploy/caddy/Caddyfile b/deploy/caddy/Caddyfile index 268c142..df5860c 100644 --- a/deploy/caddy/Caddyfile +++ b/deploy/caddy/Caddyfile @@ -1,47 +1,52 @@ -# The front door (workbench/BRIEF.md section 7): -# /api/* PostgREST; the prefix is stripped, so /api/note is PostgREST's /note -# /wb/api/* the Workbench server: live events (streamed, so never buffered), extractors, MCP -# /sparql the graph endpoint (Ontop), read-only SPARQL over the same tables -# /plugins/*/web/* each installed plugin's browser files; nothing else in a plugin folder is served -# everything else Workbench's shell from workbench/web; / is index.html, a template that finds the plugins -# With PUBLIC_HOST set to a public host name, Caddy gets and renews a certificate. -{$PUBLIC_HOST::80} { +# The front door (S-199, S-200), on 127.0.0.1 only (deploy/compose.yaml publishes each port there): +# :8080 the desktop: the kernel's UI shell at /ui/ (its D-44, D-127) and MCP at /mcp; /ui/apps.json, the framed apps +# the shell lists (deploy/caddy/apps.json), is served from here, and the shell's own Content-Security-Policy +# gains a frame-src naming exactly those apps' origins +# :8081 Bifrost's dashboard (the gateway), framable by the desktop only +# :8082 Substrate's map pages (ui/), framable by the desktop only +# Each framed app is on an origin of its own: a frame on the shell's origin, allowed scripts and same-origin, could undo +# its sandbox and read the person's token. The apps' own headers are rewritten here, in the proxy, not in their code: +# only `frame-ancestors 'none'` becomes the desktop's origins, and Bifrost's X-Frame-Options (DENY, which a browser +# applies even beside frame-ancestors in some versions) is dropped; the rest of each policy is theirs, unchanged. +# Caddy's header_down replaces by an RE2 regular expression (caddyserver.com/docs/caddyfile/directives/reverse_proxy, +# read 2026-11-23); these patterns have no special characters, so they match literally. +{ + admin off + auto_https off +} + +:8080 { encode zstd gzip - redir /api /api/ - handle_path /api/* { - reverse_proxy postgrest:3000 + redir / /ui/ + handle /ui/apps.json { + root * /etc/caddy + rewrite * /apps.json + header Content-Type application/json + header X-Content-Type-Options nosniff + file_server } - - handle /sparql { - reverse_proxy graph:8080 + handle /mcp* { + reverse_proxy kernel:8000 } - - handle /wb/api/* { - reverse_proxy workbench:8100 { - flush_interval -1 + handle { + reverse_proxy kernel:8000 { + header_down Content-Security-Policy "default-src 'self';" "default-src 'self'; frame-src http://127.0.0.1:8081 http://127.0.0.1:8082;" } } +} - @pluginweb path_regexp ^/plugins/[a-z0-9_-]+/web/ - handle @pluginweb { - root * /srv - file_server - } - handle /plugins/* { - respond 404 +:8081 { + encode zstd gzip + reverse_proxy gateway:8080 { + header_down -X-Frame-Options + header_down Content-Security-Policy "frame-ancestors 'none'" "frame-ancestors http://127.0.0.1:8080 http://localhost:8080" } +} - handle { - root * /srv - # Alpine's CSP build and vendored Dockview need nothing inline; apps on other origins go in {$WB_FRAME_SRC} - header { - Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'self' {$WB_FRAME_SRC}; frame-ancestors 'self'; object-src 'none'; base-uri 'none'; form-action 'self'" - X-Content-Type-Options nosniff - Referrer-Policy same-origin - } - rewrite / /wb/index.html - templates - file_server +:8082 { + encode zstd gzip + reverse_proxy ui:8100 { + header_down Content-Security-Policy "frame-ancestors 'none'" "frame-ancestors http://127.0.0.1:8080 http://localhost:8080" } } diff --git a/deploy/caddy/apps.json b/deploy/caddy/apps.json new file mode 100644 index 0000000..d25c362 --- /dev/null +++ b/deploy/caddy/apps.json @@ -0,0 +1,4 @@ +[ + {"id": "gateway", "title": "Model gateway", "url": "http://127.0.0.1:8081/"}, + {"id": "maps", "title": "Substrate's maps", "url": "http://127.0.0.1:8082/"} +] diff --git a/deploy/compose.yaml b/deploy/compose.yaml index abab25f..d593be4 100644 --- a/deploy/compose.yaml +++ b/deploy/compose.yaml @@ -1,6 +1,6 @@ # Substrate's stack on the fresh tree (S-137): Postgres, the model gateway, local models, the kernel and the UI (S-140). # The old assistant's services (the companion, the voice head, the worker, the judge) were retired in S-194. -# SPARQL (deploy/ontop) and Caddy in front (deploy/caddy) come later (docs/plan.md 3b). +# SPARQL (deploy/ontop) comes later (docs/plan.md 3b); Caddy is the front door to the kernel's shell (S-199). # Images (S-167): each service names its published image (ghcr.io/openreplicant/substrate-NAME:SUBSTRATE_IMAGE_TAG, the # kernel's at KERNEL_IMAGE_TAG, both default main) and keeps its build: as the fallback. scripts/up.sh pulls first and builds # what did not pull (SUBSTRATE_BUILD=1 builds all). @@ -110,7 +110,8 @@ services: kernel: <<: *locked image: ghcr.io/openreplicant/kernel:${KERNEL_IMAGE_TAG:-main} - command: ["kk", "serve", "--only", "validator"] + # MCP over HTTP and the kernel's UI shell at /ui (the kernel's D-44), reached through caddy (S-199) + command: ["kk", "serve", "--host", "0.0.0.0", "--port", "8000", "--only", "mcp,validator"] tmpfs: [/tmp] environment: DATABASE_URL: postgresql://kk_authenticator:${KK_AUTHENTICATOR_PASSWORD:?set in .env}@db:5432/kernel @@ -169,6 +170,29 @@ services: depends_on: db: {condition: service_healthy} + # The front door (S-199): Caddy in front of the kernel's shell (/ui) and its MCP server (/mcp), on 127.0.0.1 only. + # Pinned as the kernel's own deploy pins it (deploy/.env.example there). deploy/caddy/Caddyfile says what goes where. + caddy: + <<: *locked + image: docker.io/library/caddy:2.11.7-alpine + # the image's caddy binary carries the file capability cap_net_bind_service, which an unprivileged user cannot + # take under no-new-privileges (exec fails): the container's root (the owner's own user under rootless Podman), + # holding only that one capability + cap_add: [NET_BIND_SERVICE] + tmpfs: [/data, /config] + environment: + XDG_DATA_HOME: /data + XDG_CONFIG_HOME: /config + volumes: + - ./caddy/Caddyfile:/etc/caddy/Caddyfile:ro + - ./caddy/apps.json:/etc/caddy/apps.json:ro + # the desktop, then its framed apps on origins of their own (S-200); the Caddyfile and apps.json name these ports + ports: + - "127.0.0.1:8080:8080" + - "127.0.0.1:8081:8081" + - "127.0.0.1:8082:8082" + depends_on: [kernel, gateway, ui] + # 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 model that answers at once # (llm-fast). The GPU's device nodes and driver libraries are still given (as deploy/compose.nvidia.yaml gives them to diff --git a/docs/framework.md b/docs/framework.md index bf3b8da..8fcf6f8 100644 --- a/docs/framework.md +++ b/docs/framework.md @@ -55,8 +55,11 @@ Like GNU on Linux, with Postgres made into the kernel: - **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. +- **Optimise:** the `optimize` skill chooses what to improve and which optimiser does it (S-198). **Morphogen** (its + Claude Code plugin) changes files and settings in a cell and judges them by tests and a measure; **an OpenEnv + environment's rubrics** score a model's or a policy's episodes, and a trainer (reinforcement learning, distillation) + learns from those scores. A winner becomes a proposal the person approves. Who proposes never grades their own + work: the judge, a cell's tests or an environment's rubric, is outside what is being changed. - **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. @@ -94,7 +97,7 @@ stay a database of its own on the same server.) | --- | --- | --- | --- | | 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 optimiser (S-198) | Morphogen's cell contract (files and settings); OpenEnv's rubrics (a model's or a policy's behaviour) | Morphogen; an OpenEnv environment with a trainer | 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 | diff --git a/docs/plan.md b/docs/plan.md index d6267c1..35a8045 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -97,7 +97,8 @@ are views of the same items and claims; what can be said in one format can be ca 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/`. +(S-186), not part of Substrate. Its design stands in S-178 to S-183, as an input to the new assistant and not a commitment; its code was removed +(S-194, S-195), and git keeps it. ## Next, in order (2026-11-23) @@ -115,11 +116,8 @@ and experience (S-179, S-183). 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. **Changed 2026-11-23 (S-194): the assistant is not ported; it starts again from scratch, so this step keeps only Substrate's own parts in shape and retires the old assistant's once the owner agrees.** 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 is retired (S-196: OpenEnv replaces it); 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. +3. **Done 2026-11-23 (S-194 to S-197): the old assistant's code removed, not ported; envkit retired; the pins moved to what runs; no reader of the dropped `store` schema left.** Left for later steps: Substrate's own map in the kernel (Q10, from v1's import) still names removed parts (`store/`, `voice/`), which step 7's snapshot map replaces. The repository in its shape (S-185, S-186): Substrate keeps the stack, the skills, the channel, the catalog + and the adapters; components and the judge (S-151) gave way to Morphogen. 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 @@ -130,8 +128,8 @@ and experience (S-179, S-183). 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 +6. **Everything else runs on top of the settled shape** (S-187): each distribution (the new assistant, started from + scratch once the owner names its first two or three uses, S-194; 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 @@ -146,8 +144,9 @@ and experience (S-179, S-183). 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). +9. **M-17's experiment** (S-186, MetaSoar), on OpenEnv: a task-family environment, a model proxy in the Anthropic + format, rubric scores as outcomes, the frozen blind run (S-179). The ladder's code is gone (S-195); if the new + assistant takes the ladder's design (S-178 to S-183), it is rebuilt there, not restored. 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 diff --git a/repos.yaml b/repos.yaml index e39b6e8..4a870b8 100644 --- a/repos.yaml +++ b/repos.yaml @@ -7,10 +7,10 @@ morphogen: url: https://github.com/OpenReplicant/Morphogen branch: main - checked: b57fbbbae477534066b3aa231bd6472bf461acbc # 2026-11-16 (#81 unnamed metrics kept; #82 a short-scored run refused; #83 the intake) + checked: 9769a0b5781d3f576ede95a90e1f7599caf05c24 # 2026-11-23 main after #101; the same commit the plugin is pinned to (.claude/settings.json, S-193) # 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; its published image (ghcr.io/openreplicant/kernel:main) is pulled (S-167). kernel: url: https://github.com/OpenReplicant/kernel branch: main - checked: 041146054f7b7a155a76dda3bc843ad1405b3739 # 2026-11-22 main after #132 (D-120 bundles); the image's revision; test_kernel, test_ui, test_worker pass + checked: e176b03a072f14e0a46150ecd4e53ccd7e3a8186 # 2026-11-23 main after #136 (D-125 compose codec, D-126 one database); the image's revision; all five suites pass diff --git a/scripts/check.sh b/scripts/check.sh index 08c330a..59e36cc 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" +CORE="db gateway ollama kernel ui caddy" 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 '-llm-' || true) +extra=$(printf '%s\n' $running | grep -v -e '-db-' -e '-gateway-' -e '-ollama-' -e '-kernel-' -e '-ui-' -e '-caddy-' -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") @@ -85,6 +85,24 @@ case "$hdr" in *" 200 "*) bad "the UI answers without its CSP (ui/server.py)" ;; *) bad "the UI does not answer at $ui/api/wholes (scripts/logs.sh ui)" ;; esac +# The front door (S-199): Caddy to the kernel's shell, with the kernel's own security headers on it +desk=http://127.0.0.1:8080 # fixed: the apps.json origins and frame-ancestors name it (S-200) +hdr=$(curl -s -D - -o /dev/null "$desk/ui/" 2>/dev/null | tr -d '\r') +case "$hdr" in + *" 200 "*"frame-src http://127.0.0.1:8081 http://127.0.0.1:8082;"*"frame-ancestors 'none'"*) + ok "desktop $desk/ (the kernel's shell; frames only the apps in deploy/caddy/apps.json; sign in: scripts/kernel.sh person NAME)" ;; + *" 200 "*) bad "the kernel's shell answers at $desk/ui/ without its CSP or the apps' frame-src (deploy/caddy/Caddyfile)" ;; + *) bad "the kernel's shell does not answer at $desk/ui/ (scripts/logs.sh caddy, scripts/logs.sh kernel)" ;; +esac +# Its framed apps (S-200): each on an origin of its own, framable by the desktop only, with no X-Frame-Options left +for app in 8081:gateway 8082:maps; do + hdr=$(curl -s -D - -o /dev/null "http://127.0.0.1:${app%%:*}/" 2>/dev/null | tr -d '\r') + case "$hdr" in + *[Xx]-[Ff]rame-[Oo]ptions*) bad "app ${app#*:} at :${app%%:*} still sends X-Frame-Options (deploy/caddy/Caddyfile)" ;; + *" 200 "*"frame-ancestors http://127.0.0.1:8080 http://localhost:8080"*) ok "app ${app#*:} http://127.0.0.1:${app%%:*}/ (framable by the desktop only)" ;; + *) bad "app ${app#*:} at :${app%%:*} does not answer with frame-ancestors for the desktop (scripts/logs.sh caddy)" ;; + esac +done say "Wiring" if st=$(sec_status 2>&1); then ok "secrets ($SECRETS): $st"; else bad "secrets ($SECRETS): $st"; fi diff --git a/scripts/kernel.sh b/scripts/kernel.sh index e24c4a4..5c2f827 100755 --- a/scripts/kernel.sh +++ b/scripts/kernel.sh @@ -9,6 +9,9 @@ # # 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 (for a service's own login) # scripts/kernel.sh mcp NAME # the stdio MCP server for that login (what .mcp.json runs) +# scripts/kernel.sh person NAME # a person's sign-in for the shell at the front door (S-199): a reviewer; the +# # password printed nowhere, kept in .state/kernel/person-NAME.password (mode 600); +# # run again for a new password set -eu . "$(dirname "$0")/lib.sh" # --no-deps: these need db up, not restarted. Without it, Podman's compose recreated db on every run, which restarted @@ -46,6 +49,22 @@ open(mcp, "w").write(json.dumps(cfg, indent=2) + "\n") print(" login %s: .state/kernel/%s.env; .mcp.json has the `kernel` server (tools mcp__kernel__*)" % (out["role"], name)) ' "$ROOT" "$name" "$(env_value DB_PORT)" "$nomcp" ;; + person) + name=${2:?usage: scripts/kernel.sh person NAME} + port=8080 + mkdir -p "$ROOT/.state/kernel" + out=$(compose run --rm --no-deps -T kernel-init kk person add "$name" | grep '^{' | tail -1) + printf '%s' "$out" | python3 -c ' +import json, os, sys +root, name, port = sys.argv[1:4] +out = json.load(sys.stdin) +path = os.path.join(root, ".state/kernel", "person-" + name + ".password") +fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) +with os.fdopen(fd, "w") as f: + f.write(out["password"] + "\n") +print(" %s signs in at http://127.0.0.1:%s/ui/ as %s, with the password in .state/kernel/person-%s.password" % (out["role"], port, name, name)) +' "$ROOT" "$name" "$port" + ;; mcp) name=${2:?usage: scripts/kernel.sh mcp NAME} login="$ROOT/.state/kernel/$name.env" @@ -56,7 +75,7 @@ print(" login %s: .state/kernel/%s.env; .mcp.json has the `kernel` server (tool exec "$ENGINE" run "$@" "$(image)" kernel-mcp ;; *) - sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//' >&2 + sed -n '2,16p' "$0" | sed 's/^# \{0,1\}//' >&2 exit 2 ;; esac diff --git a/scripts/logs.sh b/scripts/logs.sh index bc7583b..b84c18a 100755 --- a/scripts/logs.sh +++ b/scripts/logs.sh @@ -1,7 +1,7 @@ #!/bin/sh # A service's recent logs, by the runtime in .env. # -# scripts/logs.sh SERVICE # db, gateway, ollama, ui +# scripts/logs.sh SERVICE # db, gateway, ollama, kernel, ui, caddy, llm, llm-fast set -eu . "$(dirname "$0")/lib.sh" diff --git a/scripts/tests/kernelfx.py b/scripts/tests/kernelfx.py index 9de221e..d149512 100644 --- a/scripts/tests/kernelfx.py +++ b/scripts/tests/kernelfx.py @@ -1,7 +1,7 @@ """A throwaway Knowledge Kernel for the tests that read Substrate's store from it (S-154). k = Kernel(ADMIN_URL) # a database, `kk init`, and the kernel's validator running - k.export(store_url) # the store's items and statements as change sets, applied + k.seed(seed.Seed(...)) # a fixture's items and statements as change sets, applied (scripts/tests/seed.py) k.url # the kernel's login (kk_authenticator): the UI switches it to the read model's role k.close() # stops the validator and drops the database @@ -75,14 +75,17 @@ def wait_applied(self, seconds: int = 60) -> None: time.sleep(0.5) raise RuntimeError("change sets did not apply: is the validator running?") - def export(self, store_url: str) -> dict: - """encoder-substrate over the store, as the kernel's own module; waits for the validator to apply it.""" - out = subprocess.run([sys.executable, "-m", "encoder_substrate", "--store", store_url], check=True, env=self.env, - capture_output=True, text=True).stdout + def seed(self, fixture, scope: str | None = None) -> dict: + """A fixture (seed.Seed) submitted by the kernel's encoder-substrate, in its own role, as the claims the read + model answers from; waits for the validator to apply them.""" + from encoder_substrate.__main__ import export + from encoder_substrate.encode import SCOPE + from kk.lib import connect + with connect("kkm_encoder_substrate", url=self.url) as conn, conn.cursor() as cur: + summary = export(cur, list(fixture.entities.values()), fixture.statements, scope or SCOPE) self.wait_applied() with psycopg.connect(self.admin, autocommit=True) as c: bad = c.execute("select count(*) from kernel.change_set where status in ('invalid', 'rejected', 'conflict')").fetchone()[0] - summary = json.loads(out.strip().splitlines()[-1]) summary["not_applied"] = bad return summary diff --git a/scripts/tests/oldschema/001_store.sql b/scripts/tests/oldschema/001_store.sql deleted file mode 100644 index e5cb2bd..0000000 --- a/scripts/tests/oldschema/001_store.sql +++ /dev/null @@ -1,647 +0,0 @@ --- The store (S-135): Wikibase's data model in Postgres, with OpenWiki's pinned evidence. --- --- entity an item (Q1) or a property (P1, with a datatype): label, description, aliases, prose --- statement subject, property, a typed value, a rank; its value is fixed once written (a new belief is a --- new statement, the old one deprecated); qualifiers in store.qualifier --- reference who stated it (a parser's run, an interpreter and its version, a person, a rule and its --- premises) and the span it rests on; shared, write-once; store.cites links it to statements --- source/span a source cut into spans (paragraphs, line ranges), each a pinned text with its hash. A new read --- with different text supersedes the span and keeps the old one, so what was cited stays readable --- revision one row per entity per transaction that touched it, with who (store.actor) and a snapshot --- --- Derived, never stored: store.usable (Wikidata's best rank: preferred if any, else normal), store.flag --- (statements resting on a superseded span, and everything derived from them, by rule premises; no model --- call), store.violation (constraints, which are statements on properties, reported and never blocking). --- store.page caches each entity's rendered page for search; store.render() is always current. - --- No JIT here: the planner overestimates the recursive views (store.flag) by orders of magnitude, and compiling --- for each of a page's statements cost half a second a write; the store's queries are small. -do $$ begin execute format('alter database %I set jit = off', current_database()); end $$; - -create extension if not exists pg_trgm; -create extension if not exists vector; -create schema store; - -create sequence store.item_number; -create sequence store.property_number; - --- Entities ----------------------------------------------------------------------------------------------- - -create table store.entity ( - id text primary key check (id ~ '^[QP][1-9][0-9]*$'), - kind text not null generated always as (case left(id, 1) when 'Q' then 'item' else 'property' end) stored, - datatype text check (datatype in ('item', 'property', 'string', 'quantity', 'time', 'coordinate', 'url', 'external-id')), - key text unique check (key ~ '^[a-z0-9][a-z0-9:._/-]*$'), -- a stable name code and imports find it by - label text not null check (label <> ''), - description text, - aliases text[] not null default '{}', - prose text, -- the page's own words, beside its statements - created_at timestamptz not null default now(), - check ((left(id, 1) = 'P') = (datatype is not null)) -); -create index entity_label_trgm on store.entity using gin (label gin_trgm_ops); - -create function store.key(p_key text) returns text language sql stable as - $$ select id from store.entity where key = p_key $$; - -create function store.new_entity(p_kind text, p_label text, p_key text default null, p_description text default null, - p_datatype text default null, p_aliases text[] default '{}', p_prose text default null) -returns text language plpgsql as $$ -declare nid text; -begin - if p_key is not null then - select id into nid from store.entity where key = p_key; - if found then return nid; end if; - end if; - nid := case p_kind when 'item' then 'Q' || nextval('store.item_number') - when 'property' then 'P' || nextval('store.property_number') end; - if nid is null then raise exception 'store: an entity is an item or a property, not %', p_kind; end if; - insert into store.entity (id, key, label, description, datatype, aliases, prose) - values (nid, p_key, p_label, p_description, p_datatype, coalesce(p_aliases, '{}'), p_prose); - return nid; -end $$; - --- Sources and spans -------------------------------------------------------------------------------------- - -create table store.source ( - id uuid primary key default gen_random_uuid(), - uri text not null unique, - media_type text, - created_at timestamptz not null default now() -); - -create table store.span ( - id uuid primary key default gen_random_uuid(), - source_id uuid not null references store.source, - locator text not null check (locator <> ''), -- p3, L10-20: where in the source - text text not null, - hash text not null, -- sha256 of text, set on insert - read_at timestamptz not null default now(), - superseded_at timestamptz, -- a later read found other text here, or none - embedding vector -- filled once an embedding model is chosen -); -create unique index span_current on store.span (source_id, locator) where superseded_at is null; - -create function store.sha256(p text) returns text language sql immutable as - $$ select encode(sha256(convert_to(p, 'UTF8')), 'hex') $$; - -create function store.span_guard() returns trigger language plpgsql as $$ -begin - if tg_op = 'INSERT' then - new.hash := store.sha256(new.text); - return new; - elsif tg_op = 'UPDATE' then - if (new.id, new.source_id, new.locator, new.text, new.hash, new.read_at) - is distinct from (old.id, old.source_id, old.locator, old.text, old.hash, old.read_at) - or (old.superseded_at is not null and new.superseded_at is distinct from old.superseded_at) then - raise exception 'store: a span is pinned; a new read of its source makes a new span'; - end if; - return new; - end if; - raise exception 'store: spans are kept, so what cited them stays readable'; -end $$; -create trigger span_guard before insert or update or delete on store.span - for each row execute function store.span_guard(); - --- Read a source as a whole: [{locator, text}]. Unchanged spans are kept, changed ones superseded by new spans, --- and current spans this read did not return are superseded as gone. -create function store.read_source(p_uri text, p_media_type text, p_spans jsonb) -returns table (loc text, span_id uuid, change text) language plpgsql as $$ -declare src uuid; sp record; cur record; -begin - insert into store.source (uri, media_type) values (p_uri, p_media_type) - on conflict (uri) do update set media_type = coalesce(excluded.media_type, store.source.media_type) - returning id into src; - for sp in select x->>'locator' as l, x->>'text' as t from jsonb_array_elements(p_spans) x loop - select s.id, s.hash into cur from store.span s where s.source_id = src and s.locator = sp.l and s.superseded_at is null; - if found and cur.hash = store.sha256(sp.t) then - loc := sp.l; span_id := cur.id; change := 'same'; return next; - continue; - end if; - if found then - update store.span s set superseded_at = now() where s.id = cur.id; - change := 'changed'; - else - change := 'new'; - end if; - insert into store.span (source_id, locator, text) values (src, sp.l, sp.t) returning id into span_id; - loc := sp.l; return next; - end loop; - for cur in update store.span s set superseded_at = now() - where s.source_id = src and s.superseded_at is null - and s.locator not in (select x->>'locator' from jsonb_array_elements(p_spans) x) - returning s.id, s.locator loop - loc := cur.locator; span_id := cur.id; change := 'gone'; return next; - end loop; -end $$; - --- Statements and qualifiers ------------------------------------------------------------------------------ - -create table store.statement ( - id uuid primary key default gen_random_uuid(), - subject text not null references store.entity, - property text not null references store.entity, - snak text not null default 'value' check (snak in ('value', 'somevalue', 'novalue')), - value jsonb, -- the typed value, for every datatype but item and property - value_entity text references store.entity, -- the value, for item and property datatypes - rank text not null default 'normal' check (rank in ('preferred', 'normal', 'deprecated')), - created_at timestamptz not null default now(), - check (snak = 'value' or (value is null and value_entity is null)), - check (value is null or value_entity is null) -); -create index statement_subject on store.statement (subject, property); -create index statement_value_entity on store.statement (value_entity) where value_entity is not null; - -create table store.qualifier ( - statement_id uuid not null references store.statement, - ord int not null, - property text not null references store.entity, - snak text not null default 'value' check (snak in ('value', 'somevalue', 'novalue')), - value jsonb, - value_entity text references store.entity, - primary key (statement_id, ord), - check (snak = 'value' or (value is null and value_entity is null)), - check (value is null or value_entity is null) -); - --- A value fits its property's datatype, or the write fails: typed values are what keep the store computable. -create function store.check_value(p_property text, p_snak text, p_value jsonb, p_entity text) -returns void language plpgsql stable as $$ -declare dt text; t text; k text; s text; -begin - select datatype into dt from store.entity where id = p_property; - if dt is null then raise exception 'store: % is not a property', p_property; end if; - if p_snak <> 'value' then return; end if; - if dt in ('item', 'property') then - if p_entity is null or p_value is not null or left(p_entity, 1) <> (case dt when 'item' then 'Q' else 'P' end) then - raise exception 'store: % takes an entity (%) as its value', p_property, dt; - end if; - return; - end if; - if p_entity is not null or p_value is null then - raise exception 'store: % takes a % value, not an entity', p_property, dt; - end if; - t := jsonb_typeof(p_value); - if dt in ('string', 'external-id', 'url') then - if t <> 'string' or p_value #>> '{}' = '' then - raise exception 'store: % takes a non-empty string (%)', p_property, dt; - end if; - if dt = 'url' and (p_value #>> '{}') !~ '^[A-Za-z][A-Za-z0-9+.-]*:\S+$' then - raise exception 'store: % takes a URL, not %', p_property, p_value; - end if; - return; - end if; - if t <> 'object' then raise exception 'store: % takes a % object, not %', p_property, dt, p_value; end if; - if dt = 'quantity' then - for k in select jsonb_object_keys(p_value) loop - if k not in ('amount', 'unit', 'lower', 'upper') then raise exception 'store: a quantity has no field %', k; end if; - end loop; - if coalesce(jsonb_typeof(p_value->'amount'), '') <> 'number' then - raise exception 'store: a quantity needs a numeric amount, not %', p_value; - end if; - if p_value ? 'unit' and jsonb_typeof(p_value->'unit') <> 'null' - and not exists (select 1 from store.entity e where e.id = p_value->>'unit' and e.kind = 'item') then - raise exception 'store: a quantity''s unit is an item, not %', p_value->'unit'; - end if; - foreach k in array array['lower', 'upper'] loop - if p_value ? k then - if jsonb_typeof(p_value->k) <> 'number' then raise exception 'store: a quantity''s % is a number', k; end if; - if (k = 'lower' and (p_value->>k)::numeric > (p_value->>'amount')::numeric) - or (k = 'upper' and (p_value->>k)::numeric < (p_value->>'amount')::numeric) then - raise exception 'store: a quantity''s bounds hold its amount (%)', p_value; - end if; - end if; - end loop; - elsif dt = 'time' then - for k in select jsonb_object_keys(p_value) loop - if k not in ('time', 'precision') then raise exception 'store: a time has no field %', k; end if; - end loop; - s := p_value->>'time'; - if coalesce(jsonb_typeof(p_value->'time'), '') <> 'string' - or s !~ '^[+-][0-9]{1,16}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$' then - raise exception 'store: a time is like +2026-11-17T00:00:00Z (Wikidata''s form), not %', p_value->'time'; - end if; - if coalesce(jsonb_typeof(p_value->'precision'), '') <> 'number' - or (p_value->>'precision') !~ '^[0-9]+$' or (p_value->>'precision')::int > 14 then - raise exception 'store: a time''s precision is 0 to 14 (9 a year, 11 a day), not %', p_value->'precision'; - end if; - elsif dt = 'coordinate' then - for k in select jsonb_object_keys(p_value) loop - if k not in ('latitude', 'longitude', 'precision') then raise exception 'store: a coordinate has no field %', k; end if; - end loop; - if coalesce(jsonb_typeof(p_value->'latitude'), '') <> 'number' or coalesce(jsonb_typeof(p_value->'longitude'), '') <> 'number' - or (p_value ? 'precision' and jsonb_typeof(p_value->'precision') <> 'number') then - raise exception 'store: a coordinate has numeric latitude and longitude, not %', p_value; - end if; - if abs((p_value->>'latitude')::numeric) > 90 or abs((p_value->>'longitude')::numeric) > 180 then - raise exception 'store: a coordinate is out of range (%)', p_value; - end if; - end if; -end $$; - -create function store.statement_guard() returns trigger language plpgsql as $$ -begin - if tg_op = 'INSERT' then - perform store.check_value(new.property, new.snak, new.value, new.value_entity); - if (select kind from store.entity where id = new.property) <> 'property' then - raise exception 'store: % is not a property', new.property; - end if; - return new; - elsif tg_op = 'UPDATE' then - if (new.id, new.subject, new.property, new.snak, new.value, new.value_entity, new.created_at) - is distinct from (old.id, old.subject, old.property, old.snak, old.value, old.value_entity, old.created_at) then - raise exception 'store: a statement''s value is fixed; add a new statement and deprecate this one'; - end if; - return new; - end if; - raise exception 'store: statements are deprecated, not deleted'; -end $$; -create trigger statement_guard before insert or update or delete on store.statement - for each row execute function store.statement_guard(); - -create function store.qualifier_guard() returns trigger language plpgsql as $$ -begin - if tg_op = 'INSERT' then - perform store.check_value(new.property, new.snak, new.value, new.value_entity); - return new; - end if; - raise exception 'store: qualifiers are part of their statement and fixed with it'; -end $$; -create trigger qualifier_guard before insert or update or delete on store.qualifier - for each row execute function store.qualifier_guard(); - -create function store.entity_guard() returns trigger language plpgsql as $$ -begin - if tg_op = 'UPDATE' then - if (new.id, new.datatype, new.created_at) is distinct from (old.id, old.datatype, old.created_at) - or (old.key is not null and new.key is distinct from old.key) then - raise exception 'store: an entity''s id, key and datatype are fixed'; - end if; - return new; - end if; - raise exception 'store: entities are kept'; -end $$; -create trigger entity_guard before update or delete on store.entity - for each row execute function store.entity_guard(); - --- References --------------------------------------------------------------------------------------------- - -create table store.reference ( - id uuid primary key default gen_random_uuid(), - by_kind text not null check (by_kind in ('parser', 'interpreter', 'person', 'rule')), - by_name text not null check (by_name <> ''), - by_version text, -- an interpreter's version - run text, -- a parser's run - span_id uuid references store.span, - note text, - fingerprint text not null unique, -- the same reference is one row, as in Wikibase - created_at timestamptz not null default now(), - check (by_kind <> 'interpreter' or by_version is not null), - check (by_kind <> 'parser' or run is not null) -); -create index reference_span on store.reference (span_id) where span_id is not null; - -create table store.premise ( -- a rule's reference: the statements it derived from - reference_id uuid not null references store.reference, - statement_id uuid not null references store.statement, - primary key (reference_id, statement_id) -); -create index premise_statement on store.premise (statement_id); - -create table store.cites ( - statement_id uuid not null references store.statement, - reference_id uuid not null references store.reference, - primary key (statement_id, reference_id) -); -create index cites_reference on store.cites (reference_id); - -create function store.write_once() returns trigger language plpgsql as $$ -begin raise exception 'store: % rows are written once', tg_table_name; end $$; -create trigger reference_write_once before update or delete on store.reference - for each row execute function store.write_once(); -create trigger premise_write_once before update or delete on store.premise - for each row execute function store.write_once(); - --- Find or make a reference and cite it from a statement. A rule's reference names its premises, and only a --- rule's does. -create function store.cite(p_statement uuid, p_kind text, p_name text, p_version text default null, p_run text default null, - p_span uuid default null, p_premises uuid[] default '{}', p_note text default null) -returns uuid language plpgsql as $$ -declare fp text; rid uuid; -begin - p_premises := coalesce(p_premises, '{}'); - if (p_kind = 'rule') <> (cardinality(p_premises) > 0) then - raise exception 'store: a rule''s reference names its premises, and only a rule''s does'; - end if; - if p_statement = any (p_premises) then raise exception 'store: a statement is not its own premise'; end if; - fp := store.sha256(jsonb_build_array(p_kind, p_name, p_version, p_run, p_span, p_note, - (select coalesce(jsonb_agg(x order by x), '[]') from unnest(p_premises) x))::text); - insert into store.reference (by_kind, by_name, by_version, run, span_id, note, fingerprint) - values (p_kind, p_name, p_version, p_run, p_span, p_note, fp) - on conflict (fingerprint) do nothing returning id into rid; - if rid is null then - select id into rid from store.reference where fingerprint = fp; - else - insert into store.premise select rid, unnest(p_premises); - end if; - insert into store.cites values (p_statement, rid) on conflict do nothing; - return rid; -end $$; - --- Every statement says who stated it: checked at commit, so a statement and its reference go in together. -create function store.statement_cited() returns trigger language plpgsql as $$ -begin - if not exists (select 1 from store.cites where statement_id = new.id) then - raise exception 'store: statement % (% on %) has no reference; say who stated it', new.id, new.property, new.subject; - end if; - return null; -end $$; -create constraint trigger statement_cited after insert on store.statement deferrable initially deferred - for each row execute function store.statement_cited(); - --- Derived views ------------------------------------------------------------------------------------------ - -create view store.usable as - select s.* from store.statement s - where s.rank = 'preferred' - or (s.rank = 'normal' and not exists ( - select 1 from store.statement p where p.subject = s.subject and p.property = s.property and p.rank = 'preferred')); - --- What a changed span puts in doubt: the statements citing it, then everything derived from those. -create view store.flag as - with recursive f (statement_id, span_id, via) as ( - select c.statement_id, s.id, null::uuid - from store.span s join store.reference r on r.span_id = s.id join store.cites c on c.reference_id = r.id - where s.superseded_at is not null - union - select c.statement_id, f.span_id, f.statement_id - from f join store.premise p on p.statement_id = f.statement_id join store.cites c on c.reference_id = p.reference_id - ) - select distinct f.statement_id, f.span_id, f.via, - case when f.via is not null then 'derived from a flagged statement' - when exists (select 1 from store.span n where n.source_id = s.source_id and n.locator = s.locator and n.superseded_at is null) - then 'its span changed' else 'its span is gone' end as reason - from f join store.span s on s.id = f.span_id; - -create function store.is_instance(p_item text, p_class text) returns boolean language sql stable as $$ - with recursive up (cls) as ( - select u.value_entity from store.usable u where u.subject = p_item and u.property = store.key('instance-of') - union - select u.value_entity from store.usable u join up on u.subject = up.cls where u.property = store.key('subclass-of') - ) - select exists (select 1 from up where cls = p_class) $$; - --- Constraints are statements on properties (property-constraint), with their parameters as qualifiers. -create view store.violation as - with c as ( - select s.id as constraint_id, s.subject as property, k.key as kind - from store.usable s join store.entity k on k.id = s.value_entity - where s.property = store.key('property-constraint') - ) - select x.statement_id, x.subject, x.property, x.constraint_id, x.kind, x.message from ( - select u.id as statement_id, u.subject, u.property, c.constraint_id, 'single-value'::text as kind, - format('%s has %s usable values for %s; it takes one', u.subject, count(*) over (partition by u.subject, u.property, c.constraint_id), u.property) as message, - count(*) over (partition by u.subject, u.property, c.constraint_id) as n - from store.usable u join c on c.property = u.property and c.kind = 'single-value-constraint' - ) x where x.n > 1 - union all - select u.id, u.subject, u.property, c.constraint_id, 'format', - format('%s does not match the format %s', u.value, q.value #>> '{}') - from store.usable u join c on c.property = u.property and c.kind = 'format-constraint' - join store.qualifier q on q.statement_id = c.constraint_id and q.property = store.key('format-as-regex') - where jsonb_typeof(u.value) = 'string' and (u.value #>> '{}') !~ ('^(?:' || (q.value #>> '{}') || ')$') - union all - select u.id, u.subject, u.property, c.constraint_id, 'one-of', - format('%s is not one of the values %s allows', u.value_entity, u.property) - from store.usable u join c on c.property = u.property and c.kind = 'one-of-constraint' - where u.value_entity is not null and not exists ( - select 1 from store.qualifier q where q.statement_id = c.constraint_id - and q.property = store.key('item-of-property-constraint') and q.value_entity = u.value_entity) - union all - select u.id, u.subject, u.property, c.constraint_id, 'value-type', - format('%s is not an instance of a class %s allows', u.value_entity, u.property) - from store.usable u join c on c.property = u.property and c.kind = 'value-type-constraint' - where u.value_entity is not null and not exists ( - select 1 from store.qualifier q where q.statement_id = c.constraint_id - and q.property = store.key('class') and store.is_instance(u.value_entity, q.value_entity)); - --- Pages -------------------------------------------------------------------------------------------------- - -create function store.fmt(p_property text, p_snak text, p_value jsonb, p_entity text) returns text -language plpgsql stable as $$ -declare dt text; t text; p int; r text; -begin - if p_snak = 'somevalue' then return 'unknown value'; end if; - if p_snak = 'novalue' then return 'no value'; end if; - if p_entity is not null then - return (select format('%s (%s)', label, id) from store.entity where id = p_entity); - end if; - select datatype into dt from store.entity where id = p_property; - if dt = 'quantity' then - r := p_value->>'amount'; - if p_value ? 'lower' or p_value ? 'upper' then - r := r || format(' [%s to %s]', coalesce(p_value->>'lower', '?'), coalesce(p_value->>'upper', '?')); - end if; - if p_value->>'unit' is not null then - r := r || ' ' || coalesce((select label from store.entity where id = p_value->>'unit'), p_value->>'unit'); - end if; - return r; - elsif dt = 'time' then - t := ltrim(p_value->>'time', '+'); p := (p_value->>'precision')::int; - return case when p >= 14 then replace(rtrim(t, 'Z'), 'T', ' ') - when p >= 11 then split_part(t, 'T', 1) - when p = 10 then left(split_part(t, 'T', 1), -3) - when p = 9 then split_part(t, '-', 1) || case when left(p_value->>'time', 1) = '-' then ' BCE' else '' end - else format('%s (precision %s)', split_part(t, '-', 1), p) end; - elsif dt = 'coordinate' then - return format('%s, %s', p_value->>'latitude', p_value->>'longitude'); - elsif dt = 'url' then - return '<' || (p_value #>> '{}') || '>'; - elsif dt = 'external-id' then - return '`' || (p_value #>> '{}') || '`'; - end if; - return p_value #>> '{}'; -end $$; - --- One line about a statement: subject, property, value. -create function store.gloss(p_statement uuid) returns text language sql stable as $$ - select format('%s %s %s', e.label, p.label, store.fmt(s.property, s.snak, s.value, s.value_entity)) - from store.statement s join store.entity e on e.id = s.subject join store.entity p on p.id = s.property - where s.id = p_statement $$; - -create function store.fmt_reference(p_reference uuid) returns text language sql stable as $$ - select concat_ws(' ', - format('%s %s', r.by_kind, r.by_name), - case when r.by_version is not null then format('(version %s)', r.by_version) end, - case when r.run is not null then format('(run %s)', r.run) end, - case when r.span_id is not null then ( - select format('in %s at %s: "%s"%s', so.uri, sp.locator, - case when length(sp.text) > 160 then left(sp.text, 157) || '...' else sp.text end, - case when sp.superseded_at is not null then ' (changed since it was cited)' else '' end) - from store.span sp join store.source so on so.id = sp.source_id where sp.id = r.span_id) end, - case when r.by_kind = 'rule' then ( - select 'from: ' || string_agg(store.gloss(pr.statement_id), '; ' order by pr.statement_id) - from store.premise pr where pr.reference_id = r.id) end, - case when r.note is not null then format('(%s)', r.note) end) - from store.reference r where r.id = p_reference $$; - --- The page people and agents read: the entity's usable statements (all of them with p_all_ranks), qualifiers, --- numbered references, and what is flagged. -create function store.render(p_id text, p_all_ranks boolean default false) returns text -language plpgsql stable set jit = off as $$ -declare e store.entity; out text; r record; q record; ref uuid; refs uuid[] := '{}'; n int; marks text; prev text; hidden int; why text; -begin - select * into e from store.entity where id = p_id; - if not found then return null; end if; - out := format(E'# %s (%s)\n', e.label, e.id); - if e.description is not null then out := out || E'\n' || e.description || E'\n'; end if; - if e.datatype is not null then out := out || format(E'\nA property; its values are of type %s.\n', e.datatype); end if; - if cardinality(e.aliases) > 0 then out := out || E'\nAlso known as: ' || array_to_string(e.aliases, ', ') || E'\n'; end if; - if e.prose is not null then out := out || E'\n' || e.prose || E'\n'; end if; - for r in - select s.*, p.label as plabel from store.statement s join store.entity p on p.id = s.property - where s.subject = p_id and (p_all_ranks or s.id in (select u.id from store.usable u where u.subject = p_id)) - order by p.label, s.property, s.created_at, s.id - loop - if prev is null then out := out || E'\n## Statements\n'; end if; - if r.property is distinct from prev then out := out || format(E'\n**%s** (%s)\n', r.plabel, r.property); prev := r.property; end if; - marks := ''; - for ref in select c.reference_id from store.cites c join store.reference x on x.id = c.reference_id - where c.statement_id = r.id order by x.created_at, x.id loop - n := array_position(refs, ref); - if n is null then refs := refs || ref; n := cardinality(refs); end if; - marks := marks || format('[%s]', n); - end loop; - select string_agg(distinct f.reason, '; ') into why from store.flag f where f.statement_id = r.id; - out := out || format(E'- %s%s%s%s\n', replace(store.fmt(r.property, r.snak, r.value, r.value_entity), E'\n', E'\n '), - case when r.rank <> 'normal' then format(' (%s)', r.rank) else '' end, - case when marks <> '' then ' ' || marks else '' end, - case when why is not null then format(' **flagged: %s**', why) else '' end); - for q in select qq.*, p.label as plabel from store.qualifier qq join store.entity p on p.id = qq.property - where qq.statement_id = r.id order by qq.ord loop - out := out || format(E' - %s: %s\n', q.plabel, replace(store.fmt(q.property, q.snak, q.value, q.value_entity), E'\n', E'\n ')); - end loop; - end loop; - if not p_all_ranks then - select count(*) into hidden from store.statement s where s.subject = p_id - and s.id not in (select u.id from store.usable u where u.subject = p_id); - if hidden > 0 then - out := out || format(E'\n%s statement(s) at a lower rank are not shown (read with all ranks to see them).\n', hidden); - end if; - end if; - if cardinality(refs) > 0 then - out := out || E'\n## References\n\n'; - for n in 1 .. cardinality(refs) loop - out := out || format(E'%s. %s\n', n, store.fmt_reference(refs[n])); - end loop; - end if; - return out; -end $$; - -create table store.page ( - entity_id text primary key references store.entity, - markdown text not null, - tsv tsvector generated always as (to_tsvector('simple', markdown)) stored, - rendered_at timestamptz not null default now(), - embedding vector -- of markdown; filled once an embedding model is chosen -); -create index page_tsv on store.page using gin (tsv); - -create function store.search(p_query text, p_limit int default 10) -returns table (id text, label text, description text, score real) language sql stable as $$ - select e.id, e.label, e.description, - greatest(similarity(e.label, p_query), - coalesce((select max(similarity(a, p_query)) from unnest(e.aliases) a), 0), - coalesce(ts_rank(pg.tsv, websearch_to_tsquery('simple', p_query)), 0))::real as score - from store.entity e left join store.page pg on pg.entity_id = e.id - where e.id = upper(p_query) or e.key = p_query or e.label % p_query or e.label ilike '%' || p_query || '%' - or exists (select 1 from unnest(e.aliases) a where a ilike '%' || p_query || '%') - or pg.tsv @@ websearch_to_tsquery('simple', p_query) - order by (e.id = upper(p_query) or e.key = p_query) desc, score desc, e.id - limit p_limit $$; - --- Revisions ---------------------------------------------------------------------------------------------- - -create table store.revision ( - id bigserial primary key, - entity_id text not null references store.entity, - txid xid8 not null default pg_current_xact_id(), - at timestamptz not null default now(), - by text not null, - summary text, - snapshot jsonb not null, - unique (entity_id, txid) -); - -create function store.snapshot(p_id text) returns jsonb language sql stable as $$ - select jsonb_build_object('id', e.id, 'key', e.key, 'label', e.label, 'description', e.description, - 'aliases', e.aliases, 'prose', e.prose, 'datatype', e.datatype, - 'statements', coalesce(( - select jsonb_agg(jsonb_build_object('id', s.id, 'property', s.property, 'snak', s.snak, 'value', s.value, - 'value_entity', s.value_entity, 'rank', s.rank, - 'qualifiers', coalesce((select jsonb_agg(jsonb_build_object('property', q.property, 'snak', q.snak, - 'value', q.value, 'value_entity', q.value_entity) order by q.ord) - from store.qualifier q where q.statement_id = s.id), '[]'), - 'references', coalesce((select jsonb_agg(c.reference_id order by c.reference_id) - from store.cites c where c.statement_id = s.id), '[]')) - order by s.created_at, s.id) - from store.statement s where s.subject = e.id), '[]')) - from store.entity e where e.id = p_id $$; - --- One revision per entity per transaction, by whoever set store.actor; the page is re-rendered with it. -create function store.touch(p_id text) returns void language plpgsql set jit = off as $$ -declare actor text := nullif(current_setting('store.actor', true), ''); -begin - if actor is null then - raise exception 'store: say who is editing first (set store.actor), so the revision names them'; - end if; - insert into store.revision (entity_id, by, summary, snapshot) - values (p_id, actor, nullif(current_setting('store.summary', true), ''), store.snapshot(p_id)) - on conflict (entity_id, txid) do update - set snapshot = excluded.snapshot, at = now(), summary = coalesce(excluded.summary, store.revision.summary); - insert into store.page (entity_id, markdown) values (p_id, store.render(p_id)) - on conflict (entity_id) do update set markdown = excluded.markdown, rendered_at = now(), embedding = null; -end $$; - -create function store.touch_entity() returns trigger language plpgsql as $$ -begin perform store.touch(x.id) from (select distinct id from changed) x; return null; end $$; -create function store.touch_statement() returns trigger language plpgsql as $$ -begin perform store.touch(x.subject) from (select distinct subject from changed) x; return null; end $$; -create function store.touch_by_statement() returns trigger language plpgsql as $$ -begin - perform store.touch(x.subject) from (select distinct s.subject from changed c join store.statement s on s.id = c.statement_id) x; - return null; -end $$; - -create trigger entity_revision_ins after insert on store.entity referencing new table as changed - for each statement execute function store.touch_entity(); -create trigger entity_revision_upd after update on store.entity referencing new table as changed - for each statement execute function store.touch_entity(); -create trigger statement_revision_ins after insert on store.statement referencing new table as changed - for each statement execute function store.touch_statement(); -create trigger statement_revision_upd after update on store.statement referencing new table as changed - for each statement execute function store.touch_statement(); -create trigger qualifier_revision after insert on store.qualifier referencing new table as changed - for each statement execute function store.touch_by_statement(); -create trigger cites_revision_ins after insert on store.cites referencing new table as changed - for each statement execute function store.touch_by_statement(); -create trigger cites_revision_del after delete on store.cites referencing old table as changed - for each statement execute function store.touch_by_statement(); - --- The core vocabulary ------------------------------------------------------------------------------------ --- Wikidata's own, by key (its P/Q numbers in the descriptions); ids here are this store's. - -select set_config('store.actor', 'store:migration 001', true); -select set_config('store.summary', 'the core vocabulary', true); - -select store.new_entity('property', 'instance of', 'instance-of', 'that class of which this subject is a particular example (Wikidata P31)', 'item'); -select store.new_entity('property', 'subclass of', 'subclass-of', 'every instance of this subject is an instance of that class (Wikidata P279)', 'item'); -select store.new_entity('property', 'property constraint', 'property-constraint', 'a constraint on this property''s use, checked and reported, never blocking (Wikidata P2302)', 'item'); -select store.new_entity('property', 'format as a regular expression', 'format-as-regex', 'a format constraint''s pattern, matched against the whole value (Wikidata P1793)', 'string'); -select store.new_entity('property', 'class', 'class', 'a value-type constraint''s allowed class (Wikidata P2308)', 'item'); -select store.new_entity('property', 'item of property constraint', 'item-of-property-constraint', 'a one-of constraint''s allowed value (Wikidata P2305)', 'item'); -select store.new_entity('property', 'reason for deprecated rank', 'reason-for-deprecated-rank', 'why a statement was deprecated (Wikidata P2241, a string here)', 'string'); -select store.new_entity('item', 'single-value constraint', 'single-value-constraint', 'the property usually has one usable value per subject (Wikidata Q19474404)'); -select store.new_entity('item', 'format constraint', 'format-constraint', 'the property''s string values match a pattern (Wikidata Q21502404)'); -select store.new_entity('item', 'one-of constraint', 'one-of-constraint', 'the property''s values are among those listed (Wikidata Q21510859)'); -select store.new_entity('item', 'value-type constraint', 'value-type-constraint', 'the property''s values are instances of a class (Wikidata Q21510865)'); diff --git a/scripts/tests/oldschema/003_components.sql b/scripts/tests/oldschema/003_components.sql deleted file mode 100644 index 9985728..0000000 --- a/scripts/tests/oldschema/003_components.sql +++ /dev/null @@ -1,103 +0,0 @@ --- Components, roles, interfaces, catalogs and goals (S-139): how any thing, software or not, is taken apart into --- parts, what each part does in its whole, what makes parts interchangeable, and what a change is judged on. --- --- a whole has part (P527) a part, qualified by object has role (P3831): the role the part plays there --- a role requires interface: what anything filling it must provide --- a part provides interface; a candidate from a catalog the same, with catalog id (qualified by catalog) --- and described at URL (P973) --- a whole has goal: a goal has a metric and a target; a measurement (on a part or candidate) is qualified --- by its goal and point in time (P585) --- a verdict on a candidate, qualified by for role, against (the incumbent) and goal; its reference is the judge --- --- store.alternatives(role): what provides every interface a role requires, beside what fills it now. --- store.read_span: one span of a source, for a single quote (store.read_source reads a source whole). - -select set_config('store.actor', 'store:migration 003', true); -select set_config('store.summary', 'components, roles, interfaces, catalogs and goals', true); - -select store.new_entity('item', 'role', 'role', 'what a part does in its whole: a slot that another part providing the same interfaces could fill'); -select store.new_entity('item', 'interface', 'interface', 'what a part provides and a role requires: a contract, an API, a fitting, a protocol, a shape'); -select store.new_entity('item', 'goal', 'goal', 'something measurable a whole is meant to do better at'); -select store.new_entity('item', 'catalog', 'catalog', 'a registry candidates come from (a package index, a vendor list, a parts book)'); -select store.new_entity('item', 'better', 'verdict-better', 'a verdict: the candidate scored higher on the goal than what fills the role'); -select store.new_entity('item', 'worse', 'verdict-worse', 'a verdict: the candidate scored lower on the goal'); -select store.new_entity('item', 'no measurable difference', 'verdict-same', 'a verdict: no difference the judge could measure'); -select store.new_entity('item', 'verdict', 'verdict-class', 'the class of verdicts'); - -select store.new_entity('property', 'has part', 'has-part', 'this whole has that part (Wikidata P527); qualify with object has role', 'item'); -select store.new_entity('property', 'object has role', 'object-has-role', 'the role the value plays in this statement: the part''s role in its whole (Wikidata P3831)', 'item'); -select store.new_entity('property', 'requires interface', 'requires-interface', 'anything filling this role must provide that interface', 'item'); -select store.new_entity('property', 'provides interface', 'provides-interface', 'this part or candidate provides that interface', 'item'); -select store.new_entity('property', 'catalog id', 'catalog-id', 'this candidate''s id in a catalog; qualify with catalog', 'external-id'); -select store.new_entity('property', 'catalog', 'in-catalog', 'which catalog an id or a candidate is from', 'item'); -select store.new_entity('property', 'described at URL', 'described-at-url', 'a page describing this (Wikidata P973)', 'url'); -select store.new_entity('property', 'has goal', 'has-goal', 'this whole is judged on that goal', 'item'); -select store.new_entity('property', 'metric', 'metric', 'how a goal is measured, in words a judge can apply', 'string'); -select store.new_entity('property', 'target', 'target', 'the value a goal aims for', 'quantity'); -select store.new_entity('property', 'measurement', 'measurement', 'a measured value; qualify with goal and point in time', 'quantity'); -select store.new_entity('property', 'goal', 'for-goal', 'which goal a measurement or verdict is about', 'item'); -select store.new_entity('property', 'point in time', 'point-in-time', 'when (Wikidata P585)', 'time'); -select store.new_entity('property', 'verdict', 'verdict', 'a judge''s verdict on this candidate; qualify with for role, against and goal', 'item'); -select store.new_entity('property', 'for role', 'for-role', 'the role a verdict or candidate is about', 'item'); -select store.new_entity('property', 'against', 'against', 'what the candidate was compared with', 'item'); - -do $$ -declare st uuid; q record; -begin - for q in select * from (values ('verdict-better'), ('verdict-worse'), ('verdict-same')) v(subj) loop - insert into store.statement (subject, property, value_entity) - values (store.key(q.subj), store.key('instance-of'), store.key('verdict-class')) returning id into st; - perform store.cite(st, 'parser', 'store:migration', null, '003'); - end loop; - -- constraints: interfaces are interfaces, roles are roles, verdicts are verdicts - for q in select * from (values ('requires-interface', 'interface'), ('provides-interface', 'interface'), - ('object-has-role', 'role'), ('for-role', 'role'), ('verdict', 'verdict-class'), - ('has-goal', 'goal'), ('for-goal', 'goal'), ('in-catalog', 'catalog')) v(prop, cls) loop - insert into store.statement (subject, property, value_entity) - values (store.key(q.prop), store.key('property-constraint'), store.key('value-type-constraint')) returning id into st; - insert into store.qualifier (statement_id, ord, property, value_entity) values (st, 0, store.key('class'), store.key(q.cls)); - perform store.cite(st, 'parser', 'store:migration', null, '003'); - end loop; -end $$; - --- One span of a source, without reading the rest of it: kept if its text is the same, superseded if not. -create function store.read_span(p_uri text, p_locator text, p_text text, p_media_type text default null) -returns table (span_id uuid, change text) language plpgsql as $$ -declare src uuid; cur record; -begin - insert into store.source (uri, media_type) values (p_uri, p_media_type) - on conflict (uri) do update set media_type = coalesce(excluded.media_type, store.source.media_type) - returning id into src; - select s.id, s.hash into cur from store.span s where s.source_id = src and s.locator = p_locator and s.superseded_at is null; - if found and cur.hash = store.sha256(p_text) then - span_id := cur.id; change := 'same'; return next; return; - end if; - if found then - update store.span s set superseded_at = now() where s.id = cur.id; - change := 'changed'; - else - change := 'new'; - end if; - insert into store.span (source_id, locator, text) values (src, p_locator, p_text) returning id into span_id; - return next; -end $$; - --- What could fill a role: everything that provides every interface the role requires (none required: none --- found), with whether it fills the role now, and in which whole. -create function store.alternatives(p_role text) -returns table (entity text, label text, fills_now boolean, in_whole text, provides text[]) language sql stable as $$ - with need as ( - select value_entity as iface from store.usable where subject = p_role and property = store.key('requires-interface') - ), cand as ( - select u.subject, array_agg(distinct u.value_entity order by u.value_entity) as provides - from store.usable u where u.property = store.key('provides-interface') group by u.subject - ), filling as ( - select h.value_entity as part, h.subject as whole - from store.usable h join store.qualifier q on q.statement_id = h.id - where h.property = store.key('has-part') and q.property = store.key('object-has-role') and q.value_entity = p_role - ) - select c.subject, e.label, exists (select 1 from filling f where f.part = c.subject), - (select string_agg(f.whole, ', ' order by f.whole) from filling f where f.part = c.subject), c.provides - from cand c join store.entity e on e.id = c.subject - where exists (select 1 from need) and (select array_agg(iface) from need) <@ c.provides - order by 3 desc, e.label $$; diff --git a/scripts/tests/oldschema/004_map.sql b/scripts/tests/oldschema/004_map.sql deleted file mode 100644 index e14e600..0000000 --- a/scripts/tests/oldschema/004_map.sql +++ /dev/null @@ -1,56 +0,0 @@ --- A map as a graph (S-139), for the UI's map diagram and the agent: a whole, its parts to any depth with the role --- each plays, the interfaces roles require and parts provide, and what else could fill each role. --- --- store.map(whole, depth) -> edges: source, target, kind, statement (null for a derived edge), flagged --- has-part whole -> part (usable has part statements, recursively to depth) --- plays part -> role (the has part statement's object has role qualifier) --- requires role -> interface --- provides part -> interface (and a candidate's) --- could-fill candidate -> role (store.alternatives: provides every interface the role requires, fills --- no role in this map) --- store.map_nodes(whole, depth) -> id, label, description, kind (whole, part, role, interface, candidate) --- --- Only usable statements (preferred, else normal) are followed, so a deprecated part drops out of the map. - -select set_config('store.actor', 'store:migration 004', true); - -create function store.map(p_whole text, p_depth int default 6) -returns table (source text, target text, kind text, statement uuid, flagged boolean) language sql stable as $$ - with recursive part (whole, part, st, depth) as ( - select h.subject, h.value_entity, h.id, 1 from store.usable h - where h.subject = p_whole and h.property = store.key('has-part') and h.value_entity is not null - union - select h.subject, h.value_entity, h.id, p.depth + 1 from part p join store.usable h on h.subject = p.part - where h.property = store.key('has-part') and h.value_entity is not null and p.depth < p_depth - ), plays as ( - select p.part, q.value_entity as role, p.st from part p join store.qualifier q on q.statement_id = p.st - where q.property = store.key('object-has-role') and q.value_entity is not null - ), holder as ( -- everything that can provide an interface: the whole and its parts - select p_whole as e union select part from part - ), role as (select distinct role from plays), - cand as ( - select a.entity, r.role from role r, store.alternatives(r.role) a - where a.entity not in (select e from holder) - ), edge as ( - select whole, part, 'has-part', st from part - union all select part, role, 'plays', null::uuid from plays - union all select u.subject, u.value_entity, 'requires', u.id from store.usable u - where u.property = store.key('requires-interface') and u.subject in (select role from role) - union all select u.subject, u.value_entity, 'provides', u.id from store.usable u - where u.property = store.key('provides-interface') - and (u.subject in (select e from holder) or u.subject in (select entity from cand)) - union all select entity, role, 'could-fill', null::uuid from cand - ) - select distinct e.*, exists (select 1 from store.flag f where f.statement_id = e.st) from edge e $$; - -create function store.map_nodes(p_whole text, p_depth int default 6) -returns table (id text, label text, description text, kind text) language sql stable as $$ - with m as (select * from store.map(p_whole, p_depth)), - n as (select p_whole as id union select source from m union select target from m) - select n.id, e.label, e.description, - case when n.id = p_whole then 'whole' - when exists (select 1 from m where m.target = n.id and m.kind in ('plays', 'could-fill')) then 'role' - when exists (select 1 from m where m.target = n.id and m.kind in ('requires', 'provides')) then 'interface' - when exists (select 1 from m where m.source = n.id and m.kind = 'could-fill') then 'candidate' - else 'part' end - from n join store.entity e on e.id = n.id order by 1 $$; diff --git a/scripts/tests/oldschema/legacy.py b/scripts/tests/oldschema/legacy.py deleted file mode 100644 index bb9d615..0000000 --- a/scripts/tests/oldschema/legacy.py +++ /dev/null @@ -1,204 +0,0 @@ -"""The old `store` schema's writer, kept only to build fixtures for the one-off exporter (S-156). - -Substrate's store (S-135) lives in the Knowledge Kernel now (S-153, S-154). Its schema (001_store.sql, -003_components.sql, 004_map.sql here) and this writer stay as test fixtures so the kernel's encoder-substrate, which -reads that schema from a machine that has not exported yet (scripts/kernel.sh export), is still tested end to end. -Nothing else imports this. - - from legacy import Store, person, interpreter, parser - apply(conn) # the three schema files, in order - s = Store(conn, actor="test") - with s.edit("what this edit does"): - q = s.item("Workbench", key="workbench", description="...") - s.say(q, s.id("instance-of"), s.id("role"), by=person("pete")) -""" -from __future__ import annotations - -import re -from contextlib import contextmanager -from dataclasses import dataclass, field -from decimal import Decimal -from pathlib import Path - -from psycopg.types.json import Jsonb - -SQL = Path(__file__).parent -SOME, NONE = object(), object() # Wikibase's "unknown value" and "no value" - - -def apply(conn) -> None: - """The old schema's files the exporter reads (not the graph's, nor the env schema, which lives in environment/sql/).""" - for f in ("001_store", "003_components", "004_map"): - with conn.transaction(): - conn.execute((SQL / f"{f}.sql").read_text()) - -@dataclass(frozen=True) -class Ref: - """Who stated something, and the span it rests on (a span id from Store.read_source).""" - kind: str - name: str - version: str | None = None - run: str | None = None - span: str | None = None - premises: tuple = field(default_factory=tuple) - note: str | None = None - - -def person(name, span=None, note=None): - return Ref("person", name, span=span, note=note) - - -def interpreter(name, version, span=None, note=None): - """A claim's author: the LLM, a distilled component or Claude Code, with its version.""" - return Ref("interpreter", name, version=version, span=span, note=note) - - -def parser(name, run, span=None, note=None): - return Ref("parser", name, run=run, span=span, note=note) - - -def rule(name, premises, note=None): - """A derivation: its premises are the statements it rests on, so a flag on any of them reaches it.""" - return Ref("rule", name, premises=tuple(str(p) for p in premises), note=note) - - -def paragraphs(text: str) -> list[tuple[str, str]]: - """A text cut at blank lines: [("p1", ...), ...].""" - parts = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()] - return [(f"p{i}", p) for i, p in enumerate(parts, 1)] - - -def time_value(v: str) -> dict: - """'2026', '2026-11' or '2026-11-17' as a Wikidata time value with its precision.""" - m = re.fullmatch(r"(-?)(\d{1,16})(?:-(\d\d)(?:-(\d\d))?)?", v) - if not m: - raise ValueError(f"not a date: {v!r}") - sign, y, mo, d = m.groups() - precision = 11 if d else 10 if mo else 9 - return {"time": f"{'-' if sign else '+'}{y.zfill(4)}-{mo or '00'}-{d or '00'}T00:00:00Z", "precision": precision} - - -class Store: - def __init__(self, conn, actor: str): - self.c = conn - self._types: dict[str, str | None] = {} - conn.execute("select set_config('store.actor', %s, false)", (actor,)) - - @contextmanager - def edit(self, summary: str | None = None): - with self.c.transaction(): - self.c.execute("select set_config('store.summary', %s, true)", (summary or "",)) - yield self - - # Writing ------------------------------------------------------------------------------------------ - - def _entity(self, kind, label, key, description, datatype, aliases, prose): - if key is not None: - row = self.c.execute("select id, label, description, aliases, prose from store.entity where key = %s", (key,)).fetchone() - if row: - want = (label, description, list(aliases or []), prose) - if (row[1], row[2], row[3], row[4]) != want: - self.c.execute("update store.entity set label = %s, description = %s, aliases = %s, prose = %s where id = %s", - (*want, row[0])) - return row[0] - return self.c.execute("select store.new_entity(%s, %s, %s, %s, %s, %s, %s)", - (kind, label, key, description, datatype, list(aliases or []), prose)).fetchone()[0] - - def item(self, label, key=None, description=None, aliases=(), prose=None) -> str: - """Make an item, or with a key find it and bring its label, description, aliases and prose up to date.""" - return self._entity("item", label, key, description, None, aliases, prose) - - def property(self, label, datatype, key=None, description=None, aliases=()) -> str: - return self._entity("property", label, key, description, datatype, aliases, None) - - def id(self, key: str) -> str: - row = self.c.execute("select id from store.entity where key = %s", (key,)).fetchone() - if not row: - raise KeyError(key) - return row[0] - - def datatype(self, prop: str) -> str | None: - if prop not in self._types: - row = self.c.execute("select datatype from store.entity where id = %s", (prop,)).fetchone() - self._types[prop] = row[0] if row else None - return self._types[prop] - - def _encode(self, prop, value): - if value is SOME: - return "somevalue", None, None - if value is NONE: - return "novalue", None, None - dt = self.datatype(prop) - if dt in ("item", "property"): - return "value", None, value - if dt == "quantity" and isinstance(value, (int, float, Decimal)): - value = {"amount": value} - elif dt == "time" and isinstance(value, str): - value = time_value(value) - elif dt == "coordinate" and isinstance(value, (tuple, list)): - value = {"latitude": value[0], "longitude": value[1]} - if isinstance(value, dict): - value = {k: (float(v) if isinstance(v, Decimal) else v) for k, v in value.items()} - return "value", Jsonb(value), None - - def say(self, subject, prop, value, *, by: Ref | list[Ref], qualifiers=(), rank="normal") -> str: - """A statement and its references; qualifiers are (property, value) pairs. Returns its id.""" - refs = [by] if isinstance(by, Ref) else list(by) - if not refs: - raise ValueError("a statement says who stated it") - with self.c.transaction(): - snak, v, ve = self._encode(prop, value) - sid = self.c.execute("insert into store.statement (subject, property, snak, value, value_entity, rank) " - "values (%s, %s, %s, %s, %s, %s) returning id", (subject, prop, snak, v, ve, rank)).fetchone()[0] - for i, (qp, qv) in enumerate(qualifiers): - self._qualify(sid, i, qp, qv) - for r in refs: - self.cite(sid, r) - return str(sid) - - def _qualify(self, sid, ord_, prop, value): - snak, v, ve = self._encode(prop, value) - self.c.execute("insert into store.qualifier (statement_id, ord, property, snak, value, value_entity) " - "values (%s, %s, %s, %s, %s, %s)", (sid, ord_, prop, snak, v, ve)) - - def cite(self, statement, ref: Ref) -> str: - return str(self.c.execute("select store.cite(%s, %s, %s, %s, %s, %s, %s::uuid[], %s)", - (statement, ref.kind, ref.name, ref.version, ref.run, ref.span, - list(ref.premises), ref.note)).fetchone()[0]) - - def recite(self, statement, old_reference, ref: Ref) -> str: - """After review of a flagged statement: cite the new reference in place of the old one.""" - with self.c.transaction(): - new = self.cite(statement, ref) - self.c.execute("delete from store.cites where statement_id = %s and reference_id = %s", (statement, old_reference)) - return new - - def rank(self, statement, rank, reason=None): - """Prefer, keep normal or deprecate a statement; a deprecation can say why.""" - with self.c.transaction(): - self.c.execute("update store.statement set rank = %s where id = %s", (rank, statement)) - if reason: - n = self.c.execute("select coalesce(max(ord) + 1, 0) from store.qualifier where statement_id = %s", (statement,)).fetchone()[0] - self._qualify(statement, n, self.id("reason-for-deprecated-rank"), reason) - - def constrain(self, prop, kind, by: Ref, **params) -> str: - """A constraint on a property: kind is single-value, format (regex=), one-of (values=[...]) or - value-type (classes=[...]).""" - q = [(self.id("format-as-regex"), params["regex"])] if kind == "format" else [] - q += [(self.id("item-of-property-constraint"), v) for v in params.get("values", [])] - q += [(self.id("class"), c) for c in params.get("classes", [])] - return self.say(prop, self.id("property-constraint"), self.id(f"{kind}-constraint"), by=by, qualifiers=q) - - def read_source(self, uri, spans, media_type=None) -> dict[str, tuple[str, str]]: - """Read a source whole: spans as [(locator, text)] or {locator: text}. Returns {locator: (span id, change)}, - change being same, new, changed or gone.""" - items = spans.items() if isinstance(spans, dict) else spans - rows = self.c.execute("select loc, span_id, change from store.read_source(%s, %s, %s)", - (uri, media_type, Jsonb([{"locator": k, "text": t} for k, t in items]))).fetchall() - return {loc: (str(sid), ch) for loc, sid, ch in rows} - - def read_span(self, uri, locator, text, media_type=None) -> tuple[str, str]: - """One span of a source (a quote), leaving its other spans alone. Returns (span id, change).""" - sid, ch = self.c.execute("select span_id, change from store.read_span(%s, %s, %s, %s)", - (uri, locator, text, media_type)).fetchone() - return str(sid), ch diff --git a/scripts/tests/seed.py b/scripts/tests/seed.py new file mode 100644 index 0000000..6b5df8a --- /dev/null +++ b/scripts/tests/seed.py @@ -0,0 +1,88 @@ +"""Fixtures for the tests that read Substrate's store from the Knowledge Kernel: items and statements built in memory +and submitted straight into a throwaway kernel (kernelfx.Kernel.seed), with no `store` schema (dropped, S-191). + +The rows are the plain dicts the kernel's encoder-substrate takes (its encode.py: entities and statements with +qualifiers and references), so the claims have the shapes the kernel's read model and its `substrate` MCP profile +answer from. + + s = Seed() + me = person("tester") + hammer = s.item("hammer", description="a tool for nails", aliases=["mallet"]) + old = s.say(hammer, "described-at-url", "https://old.example/hammer", by=me) + s.rank(old, "deprecated", "moved") + k.seed(s) # kernelfx.Kernel: submitted and applied +""" +from __future__ import annotations + +import uuid +from dataclasses import dataclass + +# The properties the tests use, with the datatype the encoder reads their values by (the old store's keys, +# which encoder-substrate maps to Wikidata's and Substrate's pack terms). +PROPERTIES = { + "instance-of": "item", "subclass-of": "item", "has-part": "item", "object-has-role": "item", + "requires-interface": "item", "provides-interface": "item", "described-at-url": "url", + "reason-for-deprecated-rank": "string", "for-role": "item", "in-catalog": "item", "catalog-id": "external-id", +} +# Items the kernel's packs already define, by the key encoder-substrate knows them by. +PACK_ITEMS = ("role", "interface", "goal", "catalog") + + +@dataclass(frozen=True) +class Ref: + kind: str + name: str + version: str | None = None + + +def person(name: str) -> Ref: + return Ref("person", name) + + +class Seed: + def __init__(self, first: int = 1): + """`first`: the first item's number, so a second seed into the same kernel makes ids of its own.""" + self.entities: dict[str, dict] = {} + self.statements: list[dict] = [] + self._by_key: dict[str, str] = {} + self._n = first - 1 + for i, (key, dt) in enumerate(PROPERTIES.items(), 1): + self._add(f"P{i}", "property", key, key.replace("-", " "), datatype=dt) + for key in PACK_ITEMS: + self.item(key, key=key) + + def _add(self, eid, kind, key, label, description=None, aliases=(), datatype=None): + self.entities[eid] = {"id": eid, "kind": kind, "datatype": datatype, "key": key, "label": label, + "description": description, "aliases": list(aliases), "prose": None} + if key: + self._by_key[key] = eid + return eid + + def id(self, key: str) -> str: + return self._by_key[key] + + def item(self, label, key=None, description=None, aliases=()) -> str: + """A new item; its id is a Qid, as the store's were.""" + self._n += 1 + return self._add(f"Q{self._n}", "item", key, label, description, aliases) + + def _snak(self, prop: str, value) -> dict: + if self.entities[prop]["datatype"] == "item": + return {"property": prop, "snak": "value", "value": None, "value_entity": value} + return {"property": prop, "snak": "value", "value": value, "value_entity": None} + + def say(self, subject, prop, value, *, by: Ref, qualifiers=(), rank="normal") -> str: + """A statement; `prop` and qualifiers' properties by key. Returns the statement's id.""" + p = self.id(prop) + st = {"id": str(uuid.uuid4()), "subject": subject, **self._snak(p, value), "rank": rank, + "qualifiers": [{"ord": i, **self._snak(self.id(qp), qv)} for i, (qp, qv) in enumerate(qualifiers)], + "references": [{"id": str(uuid.uuid4()), "by_kind": by.kind, "by_name": by.name, + "by_version": by.version, "run": None, "span": None}]} + self.statements.append(st) + return st["id"] + + def rank(self, statement: str, rank: str, reason: str | None = None) -> None: + st = next(s for s in self.statements if s["id"] == statement) + st["rank"] = rank + if reason: + st["qualifiers"].append({"ord": len(st["qualifiers"]), **self._snak(self.id("reason-for-deprecated-rank"), reason)}) diff --git a/scripts/tests/test_kernel.py b/scripts/tests/test_kernel.py index 64b5769..efd898f 100644 --- a/scripts/tests/test_kernel.py +++ b/scripts/tests/test_kernel.py @@ -1,13 +1,13 @@ """The Knowledge Kernel as Substrate's store (S-153, S-154; the old `store` package is retired, S-156), in a throwaway -kernel it drops after (ADMIN_URL from scripts/test.sh). A small store in the old schema (scripts/tests/oldschema, the -exporter's fixture) is exported into the kernel. It should: -- export: the items and statements apply, and exporting again submits nothing +kernel it drops after (ADMIN_URL from scripts/test.sh). A small fixture (scripts/tests/seed.py) is submitted into the +kernel directly. It should: +- seed: the items and statements apply, and seeding again submits nothing - answer the agent's tools over the kernel's MCP server in the substrate profile (search, read, expand, locate, path, alternatives, violations, create_item, say, deprecate) with claim handles and belief - write as the calling agent's claims, and deprecate only its own -It needs the kernel's `kk` command and modules (scripts/tests/kernelfx.py), pgvector and pg_trgm; the old schema's -files 001, 003 and 004 only. Not pgGraph, pgmq or pg_cron. +It needs the kernel's `kk` command and modules (scripts/tests/kernelfx.py), pgvector and pg_trgm. Not pgGraph, pgmq +or pg_cron. scripts/test.sh scripts/tests/test_kernel.py """ @@ -21,10 +21,8 @@ import psycopg sys.path.insert(0, str(Path(__file__).resolve().parent)) -sys.path.insert(0, str(Path(__file__).resolve().parent / "oldschema")) import kernelfx # noqa: E402 -import legacy # noqa: E402 -from legacy import Store, person # noqa: E402 +from seed import Seed, person # noqa: E402 checks = [] @@ -44,33 +42,31 @@ def main(): sys.exit(0 if all(checks) else 1) -def kernel_fixture(c): +def kernel_fixture(): """A store with what the agent's tools are asked about: a hammer with an alias, a preferred and a deprecated statement; a bicycle taken apart into a part with a role, an interface, and a candidate.""" - legacy.apply(c) - s = Store(c, actor="test") + s = Seed() me = person("tester") ids = {} - with s.edit("the kernel test's things"): - tool = s.item("tool", key="tool") - hammer = s.item("hammer", key="hammer", description="a tool for nails", aliases=["mallet"]) - s.say(hammer, s.id("instance-of"), tool, by=me) - old = s.say(hammer, s.id("described-at-url"), "https://old.example/hammer", by=me) - s.say(hammer, s.id("described-at-url"), "https://example.org/hammer", by=me, rank="preferred") - s.say(hammer, s.id("described-at-url"), "https://example.org/forged-hammer", by=me, rank="preferred") - s.rank(old, "deprecated", "moved") - bike = s.item("bicycle") - drive = s.item("drivetrain role") - s.say(drive, s.id("instance-of"), s.id("role"), by=me) - fit = s.item("1/2 x 3/32 inch chain fitting") - s.say(fit, s.id("instance-of"), s.id("interface"), by=me) - s.say(drive, s.id("requires-interface"), fit, by=me) - chain, belt, other = s.item("derailleur chain"), s.item("belt drive"), s.item("single-speed chain") - for x in (chain, other): - s.say(x, s.id("provides-interface"), fit, by=me) - s.say(bike, s.id("has-part"), chain, by=me, qualifiers=[(s.id("object-has-role"), drive)]) + tool = s.item("tool", key="tool") + hammer = s.item("hammer", key="hammer", description="a tool for nails", aliases=["mallet"]) + s.say(hammer, "instance-of", tool, by=me) + old = s.say(hammer, "described-at-url", "https://old.example/hammer", by=me) + s.say(hammer, "described-at-url", "https://example.org/hammer", by=me, rank="preferred") + s.say(hammer, "described-at-url", "https://example.org/forged-hammer", by=me, rank="preferred") + s.rank(old, "deprecated", "moved") + bike = s.item("bicycle") + drive = s.item("drivetrain role") + s.say(drive, "instance-of", s.id("role"), by=me) + fit = s.item("1/2 x 3/32 inch chain fitting") + s.say(fit, "instance-of", s.id("interface"), by=me) + s.say(drive, "requires-interface", fit, by=me) + chain, belt, other = s.item("derailleur chain"), s.item("belt drive"), s.item("single-speed chain") + for x in (chain, other): + s.say(x, "provides-interface", fit, by=me) + s.say(bike, "has-part", chain, by=me, qualifiers=[("object-has-role", drive)]) ids.update(tool=tool, hammer=hammer, bike=bike, drive=drive, fit=fit, chain=chain, belt=belt, other=other) - return ids + return s, ids async def kernel_part(admin): @@ -79,18 +75,13 @@ async def kernel_part(admin): why = kernelfx.available() if why: raise RuntimeError(why) - sname = f"store_kfx_{os.getpid()}" - with psycopg.connect(admin, autocommit=True) as a: - a.execute(f"create database {sname}") - surl = admin.rsplit("/", 1)[0] + "/" + sname k = None try: - with psycopg.connect(surl, autocommit=True) as c: - ids = kernel_fixture(c) + fixture, ids = kernel_fixture() k = kernelfx.Kernel(admin) - out = k.export(surl) - check("kernel: the store's items and statements are exported and applied", out["new"] > 0 and out["not_applied"] == 0, out) - check("kernel: exporting again submits nothing", k.export(surl)["new"] == 0) + out = k.seed(fixture) + check("kernel: the fixture's items and statements are submitted and applied", out["new"] > 0 and out["not_applied"] == 0, out) + check("kernel: seeding again submits nothing", k.seed(fixture)["new"] == 0) agent = k.agent("substrate-test") env = {x: os.environ[x] for x in ("PATH", "PYTHONPATH", "HOME") if x in os.environ} env.update(DATABASE_URL=agent, KK_PROFILE="substrate", KK_SUBSTRATE_WAIT="30") @@ -101,8 +92,6 @@ async def kernel_part(admin): finally: if k: k.close() - with psycopg.connect(admin, autocommit=True) as a: - a.execute(f'drop database if exists "{sname}" with (force)') async def kernel_tools(session, ids, k): diff --git a/scripts/tests/test_ui.py b/scripts/tests/test_ui.py index bf9929e..e2089cb 100644 --- a/scripts/tests/test_ui.py +++ b/scripts/tests/test_ui.py @@ -1,6 +1,5 @@ -"""The UI (S-140, S-154, S-156), against throwaway databases it drops after (ADMIN_URL from scripts/test.sh): a store -in the old schema (scripts/tests/oldschema, the exporter's fixture) with a bicycle's map, exported into a throwaway -Knowledge Kernel (scripts/tests/kernelfx.py), and the UI on that kernel. It should: +"""The UI (S-140, S-154, S-156), against a throwaway Knowledge Kernel it drops after (ADMIN_URL from scripts/test.sh; +scripts/tests/kernelfx.py): a bicycle's map seeded into it (scripts/tests/seed.py), and the UI on that kernel. It should: - serve its vendored files as recorded in ui/static/vendor/VENDOR.md (SHA-256), with their licences beside them - answer search, wholes, an entity's page and a map (nodes by kind, edges by kind) - send its CSP (scripts and styles from itself only) on every response, and its page needs nothing more: no inline @@ -15,7 +14,6 @@ import json import os import re -import subprocess import sys import threading import urllib.error @@ -29,9 +27,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) import kernelfx # noqa: E402 -sys.path.insert(0, str(Path(__file__).resolve().parent / "oldschema")) -import legacy # noqa: E402 -from legacy import Store, person # noqa: E402 +from seed import Seed, person # noqa: E402 from ui import server # noqa: E402 checks = [] @@ -51,17 +47,7 @@ def get(base, path): def main(): - admin = os.environ["ADMIN_URL"] - name = f"ui_test_{os.getpid()}" - with psycopg.connect(admin, autocommit=True) as a: - a.execute(f"create database {name}") - url = admin.rsplit("/", 1)[0] + "/" + name - try: - with psycopg.connect(url, autocommit=True) as c: - run(c, url, admin) - finally: - with psycopg.connect(admin, autocommit=True) as a: - a.execute(f"drop database {name} with (force)") + run(os.environ["ADMIN_URL"]) print(f"{sum(checks)}/{len(checks)} checks passed") sys.exit(0 if all(checks) else 1) @@ -82,22 +68,20 @@ def vendored(): check("the script never writes HTML", "innerHTML" not in js and "insertAdjacentHTML" not in js and "document.write" not in js) -def run(c, url, admin): +def run(admin): vendored() - legacy.apply(c) - s = Store(c, actor="test") + s = Seed() me = person("tester") - with s.edit("a bicycle"): - bike = s.item("bicycle", description="a whole") - drive = s.item("drivetrain role") - s.say(drive, s.id("instance-of"), s.id("role"), by=me) - fit = s.item("1/2 x 3/32 inch chain fitting") - s.say(fit, s.id("instance-of"), s.id("interface"), by=me) - s.say(drive, s.id("requires-interface"), fit, by=me) - chain, other = s.item("derailleur chain"), s.item("single-speed chain") - for x in (chain, other): - s.say(x, s.id("provides-interface"), fit, by=me) - s.say(bike, s.id("has-part"), chain, by=me, qualifiers=[(s.id("object-has-role"), drive)]) + bike = s.item("bicycle", description="a whole") + drive = s.item("drivetrain role") + s.say(drive, "instance-of", s.id("role"), by=me) + fit = s.item("1/2 x 3/32 inch chain fitting") + s.say(fit, "instance-of", s.id("interface"), by=me) + s.say(drive, "requires-interface", fit, by=me) + chain, other = s.item("derailleur chain"), s.item("single-speed chain") + for x in (chain, other): + s.say(x, "provides-interface", fit, by=me) + s.say(bike, "has-part", chain, by=me, qualifiers=[("object-has-role", drive)]) ids = dict(bike=bike, drive=drive, fit=fit, chain=chain, other=other) why = kernelfx.available() @@ -106,15 +90,15 @@ def run(c, url, admin): return k = kernelfx.Kernel(admin) try: - out = k.export(url) - check("the store is exported into a kernel", out["new"] > 0 and out["not_applied"] == 0, out) - scenario("kernel", url, k.url, ids) - kernel_only(k, url, ids) + out = k.seed(s) + check("the fixture is seeded into a kernel", out["new"] > 0 and out["not_applied"] == 0, out) + scenario("kernel", k.url, ids) + kernel_only(k, ids) finally: k.close() -def scenario(backend, url, kernel, ids): +def scenario(backend, kernel, ids): bike, drive, fit, chain, other = (ids[x] for x in ("bike", "drive", "fit", "chain", "other")) srv = server.serve("127.0.0.1", 0, kernel) threading.Thread(target=srv.serve_forever, daemon=True).start() @@ -157,7 +141,7 @@ def scenario(backend, url, kernel, ids): srv.shutdown() -def kernel_only(k, url, ids): +def kernel_only(k, ids): """The kernel's own rules reach the UI: its session is the read model's role, read-only, and sees only the scopes that role is cleared for.""" st = server.Store(k.url, role=server.KERNEL_ROLE) @@ -178,15 +162,11 @@ def kernel_only(k, url, ids): a.execute("insert into kernel.scope(iri, label) values (%s, 'ui test: private')", (scope,)) for role, w in (("kkm_encoder_substrate", True), ("kkm_validator", False)): a.execute("insert into kernel.scope_grant(scope, db_role, can_read, can_write) values (%s, %s, true, %s)", (scope, role, w)) - with psycopg.connect(url, autocommit=True) as sc: - s = Store(sc, actor="test-private") - with s.edit("something private"): - vault = s.item("Zebrafish vault", description="a secret whole") - part = s.item("Zebrafish part") - s.say(vault, s.id("has-part"), part, by=person("pete")) - cmd = [sys.executable, "-m", "encoder_substrate", "--store", url, "--scope", scope] - subprocess.run(cmd, check=True, env=k.env, capture_output=True) - k.wait_applied() + s = Seed(first=1000) + vault = s.item("Zebrafish vault", description="a secret whole") + part = s.item("Zebrafish part") + s.say(vault, "has-part", part, by=person("pete")) + k.seed(s, scope=scope) srv = server.serve("127.0.0.1", 0, k.url) threading.Thread(target=srv.serve_forever, daemon=True).start() base = f"http://127.0.0.1:{srv.server_port}" diff --git a/scripts/trials/desktop/run.py b/scripts/trials/desktop/run.py new file mode 100644 index 0000000..a362919 --- /dev/null +++ b/scripts/trials/desktop/run.py @@ -0,0 +1,133 @@ +"""The desktop spike (S-200), in a real browser against the running stack: the kernel's shell as a desktop at the front +door (127.0.0.1:8080), its windows, two framed apps on origins of their own, the bridge, and the headers. Results and +screenshots go to .state/trials/desktop/. Runs in the map-diagram trial's pinned Playwright image (run.sh). + +Checks: +- sign in as a person (KK_PERSON, password in KK_PASSWORD); the token box is a plain text box with autofill off +- the launcher lists the kernel's tools, the view modules and the apps from /ui/apps.json +- windows open, come to the front when focused, minimise, close; the graph draws in its window +- each app loads in a sandboxed frame from its own origin, and the frame is not the shell's origin +- the bridge: a framed app's {kk: 'title'} message renames its window; the same message from anywhere else does not +- a page on an origin not in the shell's frame-src cannot be framed (the CSP refuses it) +- no page errors; no CSP violations but the one provoked +""" +import json, os, sys +from pathlib import Path +from playwright.sync_api import sync_playwright + +BASE = os.environ.get("DESKTOP_URL", "http://127.0.0.1:8080") +OUT = Path(__file__).resolve().parents[3] / ".state/trials/desktop" +OUT.mkdir(parents=True, exist_ok=True) +checks = [] + + +def check(name, ok, detail=""): + checks.append({"check": name, "ok": bool(ok), "detail": str(detail)[:300]}) + print(("ok " if ok else "FAIL"), name, "" if ok else detail, flush=True) + + +with sync_playwright() as p: + browser = p.chromium.launch() + page = browser.new_page(viewport={"width": 1440, "height": 900}) + errors, csp = [], [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.on("console", lambda m: csp.append(m.text) if "Content Security Policy" in m.text or "Refused to" in m.text else None) + warned = [] + page.on("console", lambda m: warned.append(m.text) if "escape its sandboxing" in m.text else None) + + page.goto(BASE + "/") + token_box = page.get_by_label("Token") + check("the token box is plain text with autofill off", + token_box.get_attribute("type") == "text" and token_box.get_attribute("autocomplete") == "off") + page.get_by_label("Name").fill(os.environ["KK_PERSON"]) + page.get_by_label("Password").fill(os.environ["KK_PASSWORD"]) + page.get_by_role("button", name="Sign in").click() + page.wait_for_function("() => (document.querySelector('.who .muted')?.textContent || '').includes('person')", timeout=15000) + check("a person signs in", True) + + nav = page.locator("nav") + groups = nav.locator("h2").all_text_contents() + entries = [b.locator("span").first.text_content() for b in nav.get_by_role("button").all()] + check("the launcher has the kernel's tools, the views and the apps", groups == ["Kernel", "Views", "Apps"] + and {"Search", "Review", "Graph", "Model gateway", "Substrate's maps"} <= set(entries), (groups, entries)) + + nav.get_by_role("button", name="Graph").click() + page.wait_for_function("() => +document.getElementById('cy').dataset.nodes > 0", timeout=30000) + check("the graph draws in its window", int(page.get_attribute("#cy", "data-nodes")) > 0, page.get_attribute("#cy", "data-nodes")) + nav.get_by_role("button", name="Search").click() + z = lambda w: int(page.eval_on_selector(f'[data-window="{w}"]', "e => +getComputedStyle(e).zIndex")) + check("a new window opens in front", z("search") > z("graph"), (z("search"), z("graph"))) + page.locator('[data-window="graph"] .bar').click(position={"x": 60, "y": 10}) + check("clicking a window brings it to the front", z("graph") > z("search"), (z("graph"), z("search"))) + before = page.eval_on_selector('[data-window="graph"]', "e => [e.offsetLeft, e.offsetTop]") + bar = page.locator('[data-window="graph"] .bar').bounding_box() + page.mouse.move(bar["x"] + 80, bar["y"] + 10); page.mouse.down(); page.mouse.move(bar["x"] + 280, bar["y"] + 110, steps=5); page.mouse.up() + after = page.eval_on_selector('[data-window="graph"]', "e => [e.offsetLeft, e.offsetTop]") + check("a window moves by its title bar", after[0] - before[0] == 200 and after[1] - before[1] == 100, (before, after)) + page.locator('[data-window="search"] [aria-label="Minimise"]').click() + page.locator('[data-window="search"]').wait_for(state="hidden", timeout=5000) + check("a window minimises, and the launcher shows it", not page.locator('[data-window="search"]').is_visible() + and "min" in (nav.get_by_role("button", name="Search").get_attribute("class") or "")) + nav.get_by_role("button", name="Search").click() + page.locator('[data-window="search"]').wait_for(state="visible", timeout=5000) + check("the launcher restores it", page.locator('[data-window="search"]').is_visible()) + page.locator('[data-window="search"] [aria-label="Close"]').click() + page.locator('[data-window="search"]').wait_for(state="hidden", timeout=5000) + check("a window closes", not nav.get_by_role("button", name="Search").get_attribute("class")) + + hidden = page.evaluate("""() => { const open = new Set(Alpine.$data(document.body).open.filter(w => !w.min).map(w => w.id)); + return [...document.querySelectorAll('.window')].filter(e => e.offsetParent !== null && !open.has(e.dataset.window)) + .map(e => e.dataset.window); }""") + check("no window shows that is not open", not hidden, hidden) + nav.get_by_role("button", name="Modules").click() + page.wait_for_selector('.view[data-view="view-modules"] table', timeout=15000) + check("a view module renders in its own window", page.locator('[data-window="view:view-modules"] .view table').count() == 1) + + frames = {} + for app, title in (("gateway", "Model gateway"), ("maps", "Substrate's maps")): + nav.get_by_role("button", name=title).click() + el = page.locator(f'iframe[data-app="{app}"]') + el.wait_for(state="visible", timeout=15000) + page.wait_for_timeout(2500) + f = el.element_handle().content_frame() + frames[app] = f + origin = f.evaluate("() => location.origin") if f else None + body = f.evaluate("() => document.body ? document.body.innerText.length : 0") if f else 0 + check(f"{app}: loads in a frame from its own origin", origin and origin != BASE and body > 0, (origin, body)) + check(f"{app}: the frame is sandboxed, with no referrer and no permissions", + el.get_attribute("sandbox") == "allow-scripts allow-forms allow-same-origin allow-popups allow-downloads" + and el.get_attribute("referrerpolicy") == "no-referrer" and el.get_attribute("allow") == "") + page.screenshot(path=str(OUT / f"desktop-{app}.png")) + + # the bridge + frames["maps"].evaluate("() => parent.postMessage({kk: 'title', text: 'Maps, renamed by the app'}, '*')") + page.wait_for_timeout(300) + title = page.locator('[data-window="app:maps"] .bar strong').text_content() + check("bridge: an app renames its own window", title == "Maps, renamed by the app", title) + page.evaluate("() => window.postMessage({kk: 'title', text: 'forged'}, '*')") + frames["gateway"].evaluate("() => parent.postMessage({kk: 'token'}, '*')") + page.wait_for_timeout(300) + titles = page.locator(".window .bar strong").all_text_contents() + check("bridge: the same message from the shell's own page or an unknown kind does nothing", "forged" not in titles, titles) + check("bridge: the token is in no frame", all("kk_token" not in (f.evaluate("() => { try { return JSON.stringify(sessionStorage) } catch (e) { return '' } }") or "") + for f in frames.values())) + + # a page on an origin the shell does not list cannot be framed + n = len(csp) + page.evaluate("""() => { const f = document.createElement('iframe'); f.src = 'http://127.0.0.1:8090/'; + f.id = 'stranger'; document.body.appendChild(f); }""") + page.wait_for_timeout(1500) + refused = [m for m in csp[n:] if "frame-src" in m] + check("the CSP refuses to frame an origin not in apps.json", refused, csp[n:]) + del csp[n:] + page.screenshot(path=str(OUT / "desktop.png")) + # Chromium warns on any frame allowed scripts and same-origin; it matters only on the shell's own origin + check("the sandbox warning comes once per app frame, none for any other window", len(warned) == 2, len(warned)) + check("no page errors", not errors, errors) + check("no CSP violations (but the one provoked)", not csp, csp) + browser.close() + +ok = all(c["ok"] for c in checks) +(OUT / "results.json").write_text(json.dumps(checks, indent=1)) +print(f"{sum(c['ok'] for c in checks)}/{len(checks)} checks", "passed" if ok else "FAILED") +sys.exit(0 if ok else 1) diff --git a/scripts/trials/desktop/run.sh b/scripts/trials/desktop/run.sh new file mode 100755 index 0000000..ab18d91 --- /dev/null +++ b/scripts/trials/desktop/run.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# The desktop spike's browser run (S-200), in the map-diagram trial's pinned Playwright image (Playwright 1.64.1), on the +# host's network so it reaches the front door on 127.0.0.1. Signs in as NAME (default owner) with the password that +# scripts/kernel.sh person NAME kept; the password goes to the container by name, never on a command line. +# +# scripts/trials/desktop/run.sh [NAME] +set -eu +ROOT=$(cd "$(dirname "$0")/../../.." && pwd) +ENGINE=${CONTAINER_ENGINE:-podman} +IMAGE=localhost/substrate-trial-browser:1.64.1 +NAME=${1:-owner} +"$ENGINE" image exists "$IMAGE" 2>/dev/null || "$ENGINE" build -q -t "$IMAGE" -f "$ROOT/scripts/trials/map-diagram/Containerfile" "$ROOT/scripts/trials/map-diagram" >/dev/null +KK_PERSON=$NAME KK_PASSWORD=$(cat "$ROOT/.state/kernel/person-$NAME.password") \ + exec "$ENGINE" run --rm --network=host --userns=keep-id -e KK_PERSON -e KK_PASSWORD -v "$ROOT:/w:Z" -w /w "$IMAGE" \ + python3 scripts/trials/desktop/run.py diff --git a/scripts/trials/embedding-model/trial.py b/scripts/trials/embedding-model/trial.py deleted file mode 100644 index b587a5c..0000000 --- a/scripts/trials/embedding-model/trial.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Historical (S-156): reads the old `store` schema, which stays in database `substrate` until the owner drops it; the -store package it was written against is retired. - -The store's embedding model (Q120), research skill step 3: every candidate on the same cases from the store. - -Cases: each DECISIONS.md row that a store page names (S-n), asked two ways, by the row's bold title and by the -owner's quoted words; the right answers are the pages naming that row. Documents: every page in store.page. -A words-only baseline ranks the same pages by full-text (any of the query's words, ts_rank) as the store's -search does today. One line per candidate and case, then a summary per candidate, in -.state/trials/embedding-model/results.txt. Models are Ollama's, pinned by digest below and checked. - - bin/in-tools python3 scripts/trials/embedding-model/trial.py -""" -import json, math, re, sys, time, urllib.request -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[3] -sys.path[:0] = [str(ROOT / "scripts"), str(ROOT)] -from db import connect, DB # noqa: E402 -from gateway import settings # noqa: E402 - -OLLAMA = "http://127.0.0.1:11434" -OUT = ROOT / ".state/trials/embedding-model" -K = 5 - -# name: (Ollama digest prefix, query prefix, document prefix), each from the model's card -CANDIDATES = { - "qwen3-embedding:0.6b": ("ac6da0dfba84", "Instruct: Given a question, retrieve the parts and decisions it is about\nQuery: ", ""), - "embeddinggemma-2:270m": ("c21dd30c1e38", "task: search result | query: ", "title: none | text: "), - "nomic-embed-text:v1.5": ("0a109f422b47", "search_query: ", "search_document: "), - "snowflake-arctic-embed2:568m": ("5de93a84837d", "query: ", ""), - "bge-m3:567m": ("790764642607", "", ""), -} - - -def ollama(path, body=None): - req = urllib.request.Request(OLLAMA + path, data=json.dumps(body).encode() if body else None, - headers={"Content-Type": "application/json"}) - return json.loads(urllib.request.urlopen(req, timeout=600).read()) - - -def embed(model, texts): - out = [] - for i in range(0, len(texts), 16): - out += ollama("/api/embed", {"model": model, "input": texts[i:i + 16], "truncate": True})["embeddings"] - return out - - -def cases(): - """(decision, kind, query) for each row a page names, with a title and, where there is one, the owner's words.""" - rows = {} - for line in (ROOT / "DECISIONS.md").read_text().splitlines(): - m = re.match(r"\| (S-\d+) \| \*\*(.+?)\*\*(.*)", line) - if m: - rows[m[1]] = (m[2], m[3]) - return rows - - -def rank_words(c, q): - words = [w for w in re.findall(r"\w+", q.lower()) if len(w) > 2] - if not words: - return [] - tsq = " | ".join(words) - return [r[0] for r in c.execute( - "select entity_id from store.page, to_tsquery('simple', %s) q where tsv @@ q " - "order by ts_rank(tsv, q) desc, entity_id", (tsq,))] - - -def score(ranked, targets): - hit = sum(1 for d in ranked[:K] if d in targets) / min(K, len(targets)) - rr = next((1 / (i + 1) for i, d in enumerate(ranked) if d in targets), 0.0) - return hit, rr - - -def main(): - OUT.mkdir(parents=True, exist_ok=True) - have = {m["name"]: m["digest"] for m in ollama("/api/tags")["models"]} - for name, (digest, *_) in CANDIDATES.items(): - if not have.get(name, "").startswith(digest): - sys.exit(f"{name}: not pulled at digest {digest} (have {have.get(name)})") - - with connect(settings(), DB) as c: - pages = c.execute("select entity_id, markdown from store.page order by entity_id").fetchall() - rows = cases() - qs = [] # (case id, query, targets) - for sid, (title, rest) in sorted(rows.items(), key=lambda r: int(r[0][2:])): - targets = {e for e, md in pages if re.search(rf"\b{sid}\b", md)} - if not targets: - continue - qs.append((f"{sid}/title", title, targets)) - owner = re.search(r'owner[^"“]{0,40}["“](.+?)["”]', rest) - if owner and len(owner[1]) > 15: - qs.append((f"{sid}/owner", owner[1], targets)) - words = {cid: rank_words(c, q) for cid, q, _ in qs} - - ids = [e for e, _ in pages] - lines, summary = [], {} - per = {"words (full-text)": {cid: score(words[cid], t) for cid, _, t in qs}} - for name, (_, qp, dp) in CANDIDATES.items(): - embed(name, ["warm up"]) - t0 = time.monotonic() - dv = embed(name, [dp + md for _, md in pages]) - doc_ms = (time.monotonic() - t0) * 1000 / len(pages) - qv = embed(name, [qp + q for _, q, _ in qs]) - norm = lambda v: [x / (math.sqrt(sum(y * y for y in v)) or 1) for x in v] # noqa: E731 - dv = [norm(v) for v in dv] - res = {} - for (cid, _, t), v in zip(qs, qv): - v = norm(v) - sims = sorted(((sum(a * b for a, b in zip(v, d)), i) for i, d in zip(ids, dv)), reverse=True) - res[cid] = score([i for _, i in sims], t) - per[name] = res - summary[name] = (len(dv[0]), doc_ms) - - base = per["words (full-text)"] - for name, res in per.items(): - for cid, (hit, rr) in res.items(): - lines.append(f"{name}\t{cid}\trecall@{K} {hit:.2f}\tmrr {rr:.3f}") - lines.append("") - lines.append(f"cases: {len(qs)} ({sum(1 for q in qs if q[0].endswith('/title'))} titles, " - f"{sum(1 for q in qs if q[0].endswith('/owner'))} owner quotes); documents: {len(pages)} pages") - for name, res in per.items(): - r = sum(h for h, _ in res.values()) / len(res) - m = sum(x for _, x in res.values()) / len(res) - better = sum(1 for cid in res if res[cid][1] > base[cid][1]) - worse = sum(1 for cid in res if res[cid][1] < base[cid][1]) - n = better + worse - p = min(1.0, 2 * sum(math.comb(n, i) for i in range(min(better, worse) + 1)) / 2 ** n) if n else 1.0 - dim, ms = summary.get(name, ("-", 0)) - lines.append(f"SUMMARY\t{name}\trecall@{K} {r:.3f}\tmrr {m:.3f}\tvs words (mrr): {better} better, " - f"{worse} worse, sign p {p:.3f}\tdim {dim}\tms/page {ms:.0f}") - (OUT / "results.txt").write_text("\n".join(lines) + "\n") - print("\n".join(l for l in lines if l.startswith("SUMMARY") or l.startswith("cases"))) - - -if __name__ == "__main__": - main() diff --git a/scripts/trials/map-diagram/cases.py b/scripts/trials/map-diagram/cases.py index 797897b..070d660 100644 --- a/scripts/trials/map-diagram/cases.py +++ b/scripts/trials/map-diagram/cases.py @@ -1,27 +1,24 @@ -"""Historical (S-156): reads the old `store` schema, which stays in database `substrate` until the owner drops it; the -store package it was written against is retired. - -The trial's cases as JSON (nodes with kind, edges with kind) in .state/trials/map-diagram/cases/: -substrate.json is Substrate's own map from the store (store.map_nodes, store.map on Q10, the real data); +"""The trial's cases as JSON (nodes with kind, edges with kind) in .state/trials/map-diagram/cases/: +substrate.json is Substrate's own map from the kernel, read through the UI's API (/api/map/Q10, the real data; the UI +must be up, scripts/up.sh); wide.json is a synthetic map ten times its size (a whole, 4 subsystems of 12 parts, a role each, interfaces shared between roles, 2 candidates per subsystem), for how the layout copes as maps grow. bin/in-tools python3 scripts/trials/map-diagram/cases.py """ -import json, sys +import json, os, urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[3] -sys.path[:0] = [str(ROOT / "scripts"), str(ROOT)] -from db import connect, DB # noqa: E402 -from gateway import settings # noqa: E402 +UI = os.environ.get("UI_URL", "http://127.0.0.1:8100") OUT = ROOT / ".state/trials/map-diagram/cases" OUT.mkdir(parents=True, exist_ok=True) -with connect(settings(), DB) as c: - nodes = [{"id": i, "label": la, "kind": k} for i, la, _, k in c.execute("select * from store.map_nodes('Q10')")] - edges = [{"source": s, "target": t, "kind": k} for s, t, k, *_ in c.execute("select * from store.map('Q10')")] +with urllib.request.urlopen(f"{UI}/api/map/Q10", timeout=30) as r: + got = json.load(r) +nodes = [{"id": n["id"], "label": n["label"], "kind": n["kind"]} for n in got["nodes"]] +edges = [{"source": e["source"], "target": e["target"], "kind": e["kind"]} for e in got["edges"]] (OUT / "substrate.json").write_text(json.dumps({"nodes": nodes, "edges": edges})) N, E = [{"id": "W", "label": "a whole", "kind": "whole"}], []