Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83f8eca0b5 | ||
|
|
8f473a5928 | ||
|
|
78b1957551 | ||
|
|
848d1fc016 | ||
|
|
94baedef20 | ||
|
|
c1180a75ff | ||
|
|
eef7f34110 | ||
|
|
78cac20d50 | ||
|
|
2c37812c03 | ||
|
|
294845acbb | ||
|
|
49e0d0b0b3 | ||
|
|
8e1809eea4 | ||
|
|
05d9169421 | ||
|
|
8bc639c7ae | ||
|
|
0128f98e0e | ||
|
|
c74276555e | ||
|
|
8378152fb2 | ||
|
|
bf46fb5724 | ||
|
|
68a5f55eb6 | ||
|
|
89b0a4104a | ||
|
|
8cbd97084b | ||
|
|
0520eacd77 |
+4
-10
@@ -19,7 +19,7 @@ ROOT_PATH=
|
||||
# streams every other module to its backend. This is that FIXED map, slug=http://service:port,
|
||||
# comma-separated; the upstream never comes from a request. A slug left out answers 404. Empty for
|
||||
# the standalone stack in docker-compose.yml (Atrium alone, at /atrium).
|
||||
# FRONTDOOR_UPSTREAMS=galena=http://galena-backend:8000,sygna=http://sygna-backend:8000,counsel=http://counsel-backend:8000,insider=http://insider-backend:8000,arbiter=http://arbiter-backend:8000,lexicon=http://lexicon-backend:8000,agora=http://agora-backend:8000,parafa=http://parafa-backend:8000,scribe=http://scribe-backend:8000,workflow=http://workflow-backend:8000
|
||||
# FRONTDOOR_UPSTREAMS=galena=http://galena-backend:8000,sygna=http://sygna-backend:8000,counsel=http://counsel-backend:8000,insider=http://insider-backend:8000,arbiter=http://arbiter-backend:8000,lexicon=http://lexicon-backend:8000,agora=http://agora-backend:8000,panorama=http://panorama-backend:8000,parafa=http://parafa-backend:8000,scribe=http://scribe-backend:8000
|
||||
FRONTDOOR_UPSTREAMS=
|
||||
|
||||
# ── Database ─────────────────────────────────────────────────────────────────
|
||||
@@ -110,11 +110,9 @@ MODEL_PROVIDER_MIGRATOR_ROLES=
|
||||
# 0.20.0, revision 0011): SELECT + INSERT under row-level security, each only once it is also in
|
||||
# IDENTITY_READER_ROLES. The hub's own runtime role always takes part. Empty standalone.
|
||||
MODULE_EVENT_EMITTER_ROLES=
|
||||
# The READER tier (dredd-core 0.23.0): runtime roles that may only SELECT the log (a module that
|
||||
# reports on it and says nothing). A role is an emitter or a reader, never both. Empty standalone.
|
||||
MODULE_EVENT_READER_ROLES=
|
||||
# The shared counterparty register (dredd-core 0.21.0, revision 0012): the modules' runtime roles
|
||||
# that WRITE it (Sygna, Galena), the ones that only READ it (Agora, Parafa), and the migrators that move their own counterparties in (import door) and point foreign keys
|
||||
# that WRITE it (Sygna; without Sygna, the module that needs counterparties), the ones that only READ
|
||||
# it, and the migrators that move their own counterparties in (import door) and point foreign keys
|
||||
# at it. Each only once also joined (IDENTITY_READER_ROLES / IDENTITY_MIGRATOR_ROLES). The hub's own
|
||||
# runtime role holds nothing there. Empty standalone.
|
||||
COUNTERPARTY_WRITER_ROLES=
|
||||
@@ -142,7 +140,7 @@ CORS_ALLOW_ORIGINS=
|
||||
# ── Bootstrap admin (seed) ───────────────────────────────────────────────────
|
||||
BOOTSTRAP_ADMIN_EMAIL=admin@example.com
|
||||
BOOTSTRAP_ADMIN_PASSWORD=admin12345
|
||||
# The seed also puts the Dredd family (Galena, Sygna, Counsel Scorecard, Insider, Arbiter, Lexicon, Agora, Parafa, Scribe, Workflow) into the module
|
||||
# The seed also puts the Dredd family (Galena, Sygna, Counsel Scorecard, Insider, Arbiter, Lexicon, Agora, Panorama, Parafa, Scribe) into the module
|
||||
# catalog — once per instance, without addresses; add those under Administration → Modules.
|
||||
|
||||
# ── App tokens ───────────────────────────────────────────────────────────────
|
||||
@@ -158,7 +156,3 @@ APP_TOKEN_RENEW_AFTER_HOURS=12
|
||||
OTEL_ENABLED=false
|
||||
OTEL_SERVICE_NAME=atrium-backend
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
|
||||
# The Archive's technical account (Atrium#53): the fixed id the seed creates it under, to
|
||||
# be granted user access in Parafa, Workflow, Agora and Arbiter only. Keep the default.
|
||||
ARCHIVE_READER_ID=a2c41e00-0000-4000-8000-000000000053
|
||||
|
||||
+19
-34
@@ -1,19 +1,5 @@
|
||||
name: CI
|
||||
on:
|
||||
push:
|
||||
# main only: a branch is tested through its pull request (a push of many branches at once
|
||||
# must not flood the runners)
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
# dredd-core is private on the Haski Gitea, and so is every repository this workflow may fetch.
|
||||
# All git traffic to the Gitea host (pip installing dredd-core from requirements, above all) goes
|
||||
# through the read-only bot haski-reader: its token is the Haski org secret DREDD_CORE_TOKEN,
|
||||
# which Gitea masks in logs. Docker builds get the same token as a BuildKit secret instead.
|
||||
env:
|
||||
GIT_CONFIG_COUNT: "1"
|
||||
GIT_CONFIG_KEY_0: url.http://x-access-token:${{ secrets.DREDD_CORE_TOKEN }}@77.216.148.202:3000/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: http://77.216.148.202:3000/
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
backend:
|
||||
@@ -57,6 +43,17 @@ jobs:
|
||||
-- EXISTS then no-ops, so the least-privilege migrator never needs extension rights.
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
SQL
|
||||
- name: Authenticate to dredd-core
|
||||
# dredd-core is a PRIVATE repo, so the `git+https://` requirement cannot be fetched
|
||||
# anonymously — without this step `pip install` fails with a git auth prompt/404.
|
||||
# The rewrite injects the token for that ONE repo URL; every other GitHub URL is untouched,
|
||||
# and the secret stays out of the requirements file and the pip log.
|
||||
# Add the secret under Settings → Secrets and variables → Actions → DREDD_CORE_TOKEN
|
||||
# (a fine-grained PAT with read-only Contents access on Alpaq92/dredd-core).
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
@@ -65,9 +62,7 @@ jobs:
|
||||
run: alembic upgrade head && python -m app.identity_grants && python -m app.seed
|
||||
- name: Tests
|
||||
working-directory: backend
|
||||
# The deploy kit's tests (tests/test_deploy_*.py) run once, in deploy-kit-tests: they drive
|
||||
# init.sh/push.sh on files and need no database, so they need not run per Postgres version.
|
||||
run: pytest -q --cov=app --cov-report=term-missing --ignore-glob='tests/test_deploy_*.py'
|
||||
run: pytest -q --cov=app --cov-report=term-missing
|
||||
- name: Console syntax
|
||||
# A duplicate `const` inside one function silently stops the whole file parsing, so every
|
||||
# function after it disappears — and the symptom is a blank screen with no console error.
|
||||
@@ -170,6 +165,11 @@ jobs:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with: { python-version: "3.12" }
|
||||
- name: Authenticate to dredd-core
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
@@ -229,7 +229,7 @@ jobs:
|
||||
run: alembic upgrade head && python -m app.identity_grants && python -m app.seed
|
||||
- name: Tests (as atrium_app)
|
||||
working-directory: backend
|
||||
run: pytest -q --ignore-glob='tests/test_deploy_*.py' # those run in deploy-kit-tests
|
||||
run: pytest -q
|
||||
- name: Managed check, as the runtime role and as the migrator
|
||||
# `--identity-tier owner`, not `writer`: Atrium's migrator OWNS the shared schema, so
|
||||
# measuring it against the writer tier reports an "escalation" on a perfectly correct
|
||||
@@ -301,21 +301,6 @@ jobs:
|
||||
# docker-compose.yml, the Dockerfile (and its front door) or db/init — and the private dredd-core install
|
||||
# inside the image is exactly what broke unnoticed before. This job runs the real stack, the way a
|
||||
# deployer does. (Modelled on Sygna's compose-smoke job, which proved the approach.)
|
||||
deploy-kit-tests:
|
||||
# The deploy kit's own tests: each runs init.sh / push.sh (a bash-heavy ~10 s apiece) against
|
||||
# files, no database. Once, not per Postgres version, and spread over every core.
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with: { python-version: "3.12" }
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
- name: Deploy kit tests
|
||||
working-directory: backend
|
||||
run: pytest -q -n auto tests/test_deploy_*.py
|
||||
|
||||
compose-smoke:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
name: deploy box
|
||||
# Co niedzielę o 22:00 (czas polski) i na żądanie aktualizuje rodzinę Dredd na
|
||||
# deploy@185.252.234.165 (/srv/atrium, projekt Compose dredd-family) z gałęzi main na Gitei, krokami
|
||||
# deploy/README.md §11 "Updates":
|
||||
# git pull + submodule update -> preflight.sh -> docker compose build -> push.sh -> up -d
|
||||
#
|
||||
# Bezpieczniki:
|
||||
# - tryb "dry-run" (domyślny) niczego nie zmienia: pokazuje, co by weszło, i uruchamia
|
||||
# push.sh --dry-run na obecnym checkoucie;
|
||||
# - przed buildem zrzut całej bazy (pg_dumpall, ~4 GB) do ~/predeploy/, trzymane 2 ostatnie;
|
||||
# zrzut nie startuje, jeśli po nim zostałoby mniej niż 15 GB wolnego miejsca;
|
||||
# - tylko fast-forward: jeśli checkout na serwerze rozjechał się z main, job staje;
|
||||
# - każdy krok przerywa przy błędzie (set -e); push.sh zatrzymuje się, zanim cokolwiek
|
||||
# zrestartuje, a działające kontenery zostają na starych obrazach do `up -d`;
|
||||
# - skrypt trafia na serwer jako plik i działa ze stdin = /dev/null: żadne polecenie w nim nie
|
||||
# może "zjeść" reszty skryptu (tak 30.11 `docker compose exec` przerwał nocny przebieg po zrzucie).
|
||||
#
|
||||
# Sekret DEPLOY_SSH_KEY_B64: klucz prywatny w base64, jedna linia (Gitea maskuje w logach tylko
|
||||
# sekrety jednoliniowe); klucz przyjmowany przez serwer tylko z IP Gitei (from= w authorized_keys).
|
||||
# Zmienna DEPLOY_KNOWN_HOSTS: klucz hosta serwera (ssh-keyscan), żeby nikt się nie podszył.
|
||||
on:
|
||||
# Co tydzień: niedziela 22:00 czasu polskiego (prawdziwe wdrożenie, włączone na prośbę 2026-11-30).
|
||||
schedule:
|
||||
- cron: "CRON_TZ=Europe/Warsaw 0 22 * * 0"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: "dry-run = tylko pokaż i sprawdź; deploy = wdroż"
|
||||
required: true
|
||||
default: dry-run
|
||||
type: choice
|
||||
options: [dry-run, deploy]
|
||||
|
||||
concurrency:
|
||||
group: deploy-box
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: deploy # osobny runner: wdrozenie nie czeka w kolejce CI
|
||||
timeout-minutes: 180
|
||||
env:
|
||||
BOX: deploy@185.252.234.165
|
||||
MODE: ${{ github.event_name == 'schedule' && 'deploy' || github.event.inputs.mode || 'dry-run' }}
|
||||
steps:
|
||||
- name: SSH to the box
|
||||
env:
|
||||
KEY_B64: ${{ secrets.DEPLOY_SSH_KEY_B64 }}
|
||||
KNOWN: ${{ vars.DEPLOY_KNOWN_HOSTS }}
|
||||
run: |
|
||||
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||
printf '%s' "$KEY_B64" | base64 -d > ~/.ssh/deploy && chmod 600 ~/.ssh/deploy
|
||||
printf '%s\n' "$KNOWN" > ~/.ssh/known_hosts
|
||||
ssh -i ~/.ssh/deploy -o BatchMode=yes "$BOX" 'echo "connected to $(hostname)"' </dev/null
|
||||
|
||||
- name: Copy the update script to the box
|
||||
run: |
|
||||
ssh -i ~/.ssh/deploy -o BatchMode=yes "$BOX" 'cat > ~/deploy-box.sh && chmod 700 ~/deploy-box.sh' <<'REMOTE'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
MODE=$1
|
||||
GITEA=http://77.216.148.202:3000/Haski/Atrium.git
|
||||
cd /srv/atrium
|
||||
[ "$(git remote get-url origin)" = "$GITEA" ] || git remote set-url origin "$GITEA"
|
||||
git fetch --quiet --no-recurse-submodules origin main
|
||||
BEFORE=$(git rev-parse HEAD); TARGET=$(git rev-parse origin/main)
|
||||
echo "box: ${BEFORE:0:7} gitea main: ${TARGET:0:7}"
|
||||
if ! git merge-base --is-ancestor "$BEFORE" "$TARGET"; then
|
||||
echo "::error::the box's checkout is not an ancestor of main - refusing (fix by hand)"; exit 1
|
||||
fi
|
||||
echo "--- commits to deploy:"; git log --oneline "$BEFORE..$TARGET" | head -40
|
||||
echo "--- module pins that move:"; git diff "$BEFORE" "$TARGET" -- deploy/modules | grep '^[-+]Subproject' || echo "(none)"
|
||||
|
||||
if [ "$MODE" != deploy ]; then
|
||||
echo "--- dry run: push.sh --dry-run on the current checkout"
|
||||
cd deploy && ./push.sh --dry-run
|
||||
echo "dry run done, nothing changed"; exit 0
|
||||
fi
|
||||
if [ "$BEFORE" = "$TARGET" ]; then echo "already at main - nothing to deploy"; exit 0; fi
|
||||
|
||||
TS=$(date +%Y%m%d-%H%M)
|
||||
LOG=~/build-$TS.log
|
||||
echo "--- full log on the box: $LOG"
|
||||
exec > >(tee -a "$LOG") 2>&1
|
||||
|
||||
echo "--- 1/6 database dump (before anything changes)"
|
||||
mkdir -p ~/predeploy
|
||||
LAST=$(ls -1t ~/predeploy/dredd-*.sql.gz 2>/dev/null | head -1 || true)
|
||||
NEED_KB=$(( ${LAST:+$(du -k "$LAST" | cut -f1)} + 0 ))
|
||||
FREE_KB=$(df -Pk ~ | awk 'NR==2 {print $4}')
|
||||
if [ $(( FREE_KB - NEED_KB )) -lt $(( 15 * 1024 * 1024 )) ]; then
|
||||
echo "::error::not enough disk for a dump: $((FREE_KB/1024/1024)) GB free, last dump $((NEED_KB/1024/1024)) GB, 15 GB must stay free"; exit 1
|
||||
fi
|
||||
(cd deploy && docker compose exec -T postgres pg_dumpall -U postgres </dev/null) | gzip > ~/predeploy/dredd-$TS.sql.gz
|
||||
ls -1t ~/predeploy/dredd-*.sql.gz | tail -n +3 | xargs -r rm -f
|
||||
echo "dump: $(du -h ~/predeploy/dredd-$TS.sql.gz | cut -f1)"
|
||||
|
||||
echo "--- 2/6 fetch the code (rollback: git -C /srv/atrium checkout ${BEFORE:0:7} && git submodule update)"
|
||||
git merge --ff-only --quiet origin/main
|
||||
git submodule sync --quiet --recursive
|
||||
git submodule update --init --recursive
|
||||
git submodule status
|
||||
|
||||
cd deploy
|
||||
echo "--- 3/6 preflight"; bash preflight.sh
|
||||
echo "--- 4/6 build"
|
||||
# dredd-core is private: the build fetches it with haski-reader's read-only token, kept on the box
|
||||
export DREDD_CORE_TOKEN=$(cat ~/.config/haski/reader-token)
|
||||
docker compose build
|
||||
unset DREDD_CORE_TOKEN
|
||||
echo "--- 5/6 push (migrations + checks)"; ./push.sh
|
||||
echo "--- 6/6 restart"; docker compose up -d
|
||||
sleep 20
|
||||
docker compose ps --format '{{.Service}}\t{{.Status}}'
|
||||
if docker compose ps --format '{{.Status}}' | grep -q -i -E 'unhealthy|exited|restarting'; then
|
||||
echo "::error::a service is not healthy after the restart"; exit 1
|
||||
fi
|
||||
echo "deployed ${TARGET:0:7}"
|
||||
REMOTE
|
||||
|
||||
- name: Update the box (${{ env.MODE }})
|
||||
run: ssh -i ~/.ssh/deploy -o BatchMode=yes -o ServerAliveInterval=30 "$BOX" "bash ~/deploy-box.sh $MODE" </dev/null
|
||||
|
||||
- name: Clean up
|
||||
if: always()
|
||||
run: rm -f ~/.ssh/deploy
|
||||
@@ -12,7 +12,6 @@ name: deploy kit
|
||||
# complete.
|
||||
on:
|
||||
push:
|
||||
branches: [main] # main only; branches are tested through their PR
|
||||
paths:
|
||||
- "deploy/**"
|
||||
- ".github/workflows/deploy-kit.yml"
|
||||
|
||||
@@ -18,3 +18,6 @@ deploy/db.env
|
||||
deploy/env/*.env
|
||||
# Parafa's signer (PKCS#12 + passphrase), mounted read-only into parafa-backend: never committed.
|
||||
deploy/parafa-signer/
|
||||
.meduza/CONTRACT.md
|
||||
.meduza/.budget-fired
|
||||
.meduza/.stub-script.json
|
||||
|
||||
+3
-3
@@ -16,6 +16,9 @@
|
||||
[submodule "deploy/modules/agora"]
|
||||
path = deploy/modules/agora
|
||||
url = ../Agora.git
|
||||
[submodule "deploy/modules/panorama"]
|
||||
path = deploy/modules/panorama
|
||||
url = ../Panorama.git
|
||||
[submodule "deploy/modules/parafa"]
|
||||
path = deploy/modules/parafa
|
||||
url = ../Parafa.git
|
||||
@@ -25,6 +28,3 @@
|
||||
[submodule "deploy/modules/arbiter"]
|
||||
path = deploy/modules/arbiter
|
||||
url = ../Arbiter.git
|
||||
[submodule "deploy/modules/workflow"]
|
||||
path = deploy/modules/workflow
|
||||
url = ../Workflow.git
|
||||
|
||||
@@ -6,7 +6,7 @@ Guidance for Claude Code when working in this repository.
|
||||
|
||||
**Atrium** — the Dredd family's front door: a launcher (the sidebar's *Apps*), a home page
|
||||
(*Strona główna*: search over the modules, the figures,
|
||||
your pending access requests and, for an administrator, the platform's state), a **marketplace** of modules (Galena, Sygna, Counsel Scorecard, Insider, Arbiter, …; Workflow/`compass` was retired 2026-11-14 — revision `0014` drops its catalogue row and `module_permission` rows; Panorama was taken off the platform in Atrium#53 — its trends are home's `GET /home/trends`, revision `0018` hides its row) and the
|
||||
your pending access requests and, for an administrator, the platform's state), a **marketplace** of modules (Galena, Sygna, Counsel Scorecard, Insider, Arbiter, …; Workflow/`compass` was retired 2026-11-14 — revision `0014` drops its catalogue row and `module_permission` rows) and the
|
||||
administration that decides who is offered what. Built on **dredd-core**, the shared substrate of
|
||||
this app family:
|
||||
identity, sessions, auth, the access-control resolver, the org tree, audit and the security
|
||||
|
||||
@@ -76,7 +76,7 @@ changes when the family shares a host.
|
||||
| Who | Endpoints (under `/api/v1`) |
|
||||
|---|---|
|
||||
| anyone | `GET /health` · `POST /auth/login` · `POST /auth/logout` |
|
||||
| any signed-in user | `GET /auth/me` · `GET /launcher` · `GET /marketplace?q=&category=` · `GET /marketplace/{slug}` · `POST /marketplace/{slug}/requests` · `GET /me/access-requests` · `GET /config` · `GET /users` (names and email addresses; who holds which tier is told to an administrator only) · `POST /me/password` · `GET/POST /me/tokens` · `DELETE /me/tokens/{id}` · `POST /me/modules/{slug}/tokens` (an app token for a module — minting lives only here, because no module holds `INSERT` on `session`) · the org tree, filtered to units you can read: `GET /tree/containers` · `GET /nodes/{id}/children` |
|
||||
| any signed-in user | `GET /auth/me` · `GET /launcher` · `GET /marketplace?q=&category=` · `GET /marketplace/{slug}` · `POST /marketplace/{slug}/requests` · `GET /me/access-requests` · `GET /config` · `GET /users` · `POST /me/password` · `GET/POST /me/tokens` · `DELETE /me/tokens/{id}` · `POST /me/modules/{slug}/tokens` (an app token for a module — minting lives only here, because no module holds `INSERT` on `session`) · the org tree, filtered to units you can read: `GET /tree/containers` · `GET /nodes/{id}/children` |
|
||||
| administrators | `POST /users` · `POST /users/{id}/deactivate\|reactivate` · `POST /users/{id}/administrator` (the platform-wide tier; refuses to remove the last one) · `GET/POST /admin/modules` · `GET/PATCH/DELETE /admin/modules/{slug}` · `GET/POST /admin/modules/{slug}/moderators` · `DELETE /admin/modules/{slug}/moderators/{user_id}` · `POST /admin/modules/{slug}/assignments` · `DELETE /admin/modules/{slug}/assignments/{id}` · `POST /admin/modules/{slug}/probe` · `GET /admin/access-requests?status=` · `POST /admin/access-requests/{id}/approve\|decline` · `GET/PUT /admin/settings` · `GET /admin/overview` · `GET /admin/audit?action=` |
|
||||
| unit managers (and administrators) | `POST /nodes` (a top-level workspace: administrators only) · `DELETE /nodes/{id}` · `GET/PUT /nodes/{id}/grants` · `DELETE /nodes/{id}/grants/{user_id}` |
|
||||
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ── build stage: resolve dependencies, including the private one ─────────────
|
||||
# `dredd-core` is a private repository on the Haski Gitea pinned by tag in requirements.txt, so installing it
|
||||
# `dredd-core` is a private GitHub repository pinned by tag in requirements.txt, so installing it
|
||||
# needs two things the runtime image should never have: `git`, and a credential.
|
||||
#
|
||||
# The credential arrives as a BuildKit SECRET, not a build argument. A build arg is baked into the
|
||||
@@ -27,8 +27,8 @@ RUN --mount=type=secret,id=dredd_core_token,required=true \
|
||||
test -s /run/secrets/dredd_core_token \
|
||||
|| { echo "build secret dredd_core_token is empty - export DREDD_CORE_TOKEN" >&2; exit 1; }; \
|
||||
GIT_CONFIG_COUNT=1 \
|
||||
GIT_CONFIG_KEY_0="url.http://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@77.216.148.202:3000/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="http://77.216.148.202:3000/" \
|
||||
GIT_CONFIG_KEY_0="url.https://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@github.com/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="https://github.com/" \
|
||||
pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||
|
||||
# ── runtime stage: no git, no credential, no compiler ────────────────────────
|
||||
|
||||
@@ -54,9 +54,8 @@ down_revision = "0014"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# The same evidence tables as 0011 (see 0008's note: a shorter list would re-open them). `module_event`
|
||||
# is skipped where it does not exist (on a platform it lives in the identity schema, not here).
|
||||
APPEND_ONLY = ("audit_log", "module_event")
|
||||
# The same evidence tables as 0003 / 0008 / 0009 (see 0008's note: a shorter list would re-open them).
|
||||
APPEND_ONLY = ("audit_log",)
|
||||
NO_DELETE: tuple[str, ...] = ()
|
||||
READ_ONLY = ("alembic_version",)
|
||||
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
"""Service modules: `module.in_menu`, and Galena becomes one (Atrium#53).
|
||||
|
||||
Galena is on everywhere and not in the menu: other modules (Workflow, the contracts module, the chat)
|
||||
open its screens by link. That is a new state, not `availability = off` — `off` takes access away
|
||||
(`sync_module` empties the roster) while a service module keeps everything it had: its launcher
|
||||
entry, its deep links inside Atrium's frame, its stats tiles on Home and every `module_permission`
|
||||
row. Only the sidebar entry and the catalogue card go (`services/marketplace.py`, `frontend/app.js`).
|
||||
|
||||
**Idempotent.** On a fresh database `0001` builds `module` from the live metadata, which already has
|
||||
the column, so it is added only `IF NOT EXISTS`. Galena is switched to a service only in the row the
|
||||
seed wrote (slug `galena`); an administrator can switch it back under Administration → Modules, and
|
||||
a second run of this revision never happens (Alembic records it). Nothing is granted: no new table.
|
||||
|
||||
Downgrade drops the column, and with it the choice — every module is a menu entry again.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0016"
|
||||
down_revision = "0015"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_module = sa.table("module", sa.column("slug", sa.String), sa.column("in_menu", sa.Boolean))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute("ALTER TABLE module ADD COLUMN IF NOT EXISTS in_menu boolean NOT NULL DEFAULT true")
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug == "galena").values(in_menu=False))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute("ALTER TABLE module DROP COLUMN IF EXISTS in_menu")
|
||||
@@ -1,31 +0,0 @@
|
||||
"""Arbiter becomes a service module, as Galena did in `0016`.
|
||||
|
||||
Contracts are checked from the chat (the report panel beside it), and Arbiter's own screens open by
|
||||
link: the panel, a contract card's "Otwórz analizę". So on the platform it loses its sidebar entry
|
||||
and catalogue card and keeps everything else (launcher, deep links, stats tiles, access). Its screens
|
||||
that have no home in Atrium yet (subjects, red lines, card corrections, the laptop worker) stay where
|
||||
they are, reachable by link and by administrators in the catalogue; they move one by one.
|
||||
|
||||
Only the seeded row (slug `arbiter`) changes; an administrator can switch it back under
|
||||
Administration → Modules. Downgrade puts it back in the menu. Nothing is granted.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0017"
|
||||
down_revision = "0016"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_module = sa.table("module", sa.column("slug", sa.String), sa.column("in_menu", sa.Boolean))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug == "arbiter").values(in_menu=False))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug == "arbiter").values(in_menu=True))
|
||||
@@ -1,30 +0,0 @@
|
||||
"""Panorama folds into Atrium's home: it leaves the menu and the catalogue.
|
||||
|
||||
Its trends now live on the home page (`services/trends`, `GET /home/trends`), and the module tiles
|
||||
were already the home page's. So Panorama's row becomes a service module (`in_menu` false, as Galena
|
||||
in `0016` and Arbiter in `0017`): nobody is offered it any more, and nothing anybody had is taken
|
||||
away while it still runs. Removing it from the platform (its container, the front door, its event
|
||||
reader grant) is a deploy step of its own, after this.
|
||||
|
||||
Downgrade puts it back in the menu.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0018"
|
||||
down_revision = "0017"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_module = sa.table("module", sa.column("slug", sa.String), sa.column("in_menu", sa.Boolean))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug == "panorama").values(in_menu=False))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug == "panorama").values(in_menu=True))
|
||||
@@ -1,31 +0,0 @@
|
||||
"""Lexicon and Scribe become service modules: the chat is the only screen for contracts.
|
||||
|
||||
Decision 1 of 18.11 (issue #53): Arbiter, Lexicon and Scribe are one module „Umowy” under the chat;
|
||||
the logic stays in each module and the chat calls it. Arbiter left the menu in `0017`; Lexicon and
|
||||
Scribe no longer have a console at all, so they leave the menu and the catalogue the same way. The
|
||||
console shows the three as one entry, „Umowy”, which opens the chat (CONTRACTS in app.js).
|
||||
|
||||
Only the seeded rows (slugs `lexicon`, `scribe`) change, and setting `in_menu` false again is a
|
||||
no-op, so this is idempotent. Downgrade puts them back in the menu. Nothing is granted.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0019"
|
||||
down_revision = "0018"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_module = sa.table("module", sa.column("slug", sa.String), sa.column("in_menu", sa.Boolean))
|
||||
_SLUGS = ("lexicon", "scribe")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug.in_(_SLUGS)).values(in_menu=False))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug.in_(_SLUGS)).values(in_menu=True))
|
||||
@@ -1,35 +0,0 @@
|
||||
"""The shared `session` table refuses a module that revives or prolongs a credential (dredd-core 0.26.1).
|
||||
|
||||
Every module runtime role holds `UPDATE (last_seen_at, expires_at, revoked_at)` on `<identity>.session`
|
||||
(the reader tier), and a column grant cannot say which VALUES may be written: any one module role could
|
||||
set `revoked_at = NULL` on a session the hub revoked, or push `expires_at` to infinity. Core's
|
||||
`session_update_guard_sql` installs a row-level BEFORE UPDATE trigger that refuses exactly that for
|
||||
every role but the identity owner (this migrator) and the hub's runtime role. Idempotent; standalone a
|
||||
no-op (there is no shared table). Downgrade leaves the guard in place: removing a protection is not a
|
||||
rollback anybody needs.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.schema import session_update_guard_sql
|
||||
from sqlalchemy import text
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
|
||||
revision = "0020"
|
||||
down_revision = "0019"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
settings = get_settings()
|
||||
if not settings.shares_identity:
|
||||
return
|
||||
owner = op.get_bind().execute(text("SELECT current_user")).scalar()
|
||||
op.execute(session_update_guard_sql(settings.identity_schema, owner_role=owner,
|
||||
writer_role=settings.db_app_role))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -1,40 +0,0 @@
|
||||
"""Mint the Archive's read-only token (Atrium#53) and print it once, for Galena's deployment.
|
||||
|
||||
docker compose run --rm --no-deps -T atrium-migrate python -m app.archive_reader
|
||||
|
||||
Prints the raw token on stdout and nothing else, so it can be piped straight into a secret store;
|
||||
put it into Galena's env file as ARCHIVE_READER_TOKEN (never a committed file). Run it again to
|
||||
rotate: the old token stays valid until it is revoked in the hub (Users → the account → tokens).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from dredd_core.db import make_engine, make_session_factory
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from .config import get_settings
|
||||
from .services import archive_reader
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not get_settings().shares_identity:
|
||||
print("IDENTITY_SCHEMA is empty: a standalone hub has no modules to read from.",
|
||||
file=sys.stderr)
|
||||
return 2
|
||||
engine = make_engine(get_settings().database_url, poolclass=NullPool)
|
||||
try:
|
||||
db = make_session_factory(engine)()
|
||||
try:
|
||||
_row, raw = archive_reader.mint(db)
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
finally:
|
||||
engine.dispose()
|
||||
print(raw)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -12,7 +12,6 @@ no-op instead of a crash.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from functools import lru_cache
|
||||
|
||||
from dredd_core.db import require_verified_tls
|
||||
@@ -127,7 +126,7 @@ class Settings(BaseSettings):
|
||||
# role here and migrating revokes it.
|
||||
module_event_emitter_roles: str = ""
|
||||
# The READER tier (dredd-core 0.23.0): runtime roles that may SELECT the log and nothing else
|
||||
# (none since Panorama left the platform; kept for a module that reports on the log). Same rules: only
|
||||
# (`panorama_app`, whose trends aggregate it and which says nothing itself). Same rules: only
|
||||
# once also in IDENTITY_READER_ROLES, removed = revoked on the next migrate, and a role is an
|
||||
# emitter or a reader, never both (the grant block refuses the overlap).
|
||||
module_event_reader_roles: str = ""
|
||||
@@ -158,9 +157,6 @@ class Settings(BaseSettings):
|
||||
# open the launcher, so a `user` row would say nothing, and the hub has administrators whose job
|
||||
# is not delegable one module at a time.
|
||||
module_slug: str = "atrium"
|
||||
# The Archive's technical account (Atrium#53, services/archive_reader.py): the fixed id the seed
|
||||
# creates it under and every module fences to its evidence routes (their ARCHIVE_READER_ID).
|
||||
archive_reader_id: uuid.UUID = uuid.UUID("a2c41e00-0000-4000-8000-000000000053")
|
||||
|
||||
# Auth / sessions (cookie-based, DB-backed — one `session` row is the whole of single sign-on)
|
||||
# The cookie's name. One account means one cookie: at the cutover every app in the family is set
|
||||
|
||||
@@ -21,7 +21,6 @@ from .enums import SessionKind, TokenScope
|
||||
from .errors import AuthenticationError, AuthorizationError
|
||||
from .models import AppUser
|
||||
from .services import auth as auth_service
|
||||
from .services import skills as skill_service
|
||||
|
||||
SESSION_COOKIE = get_settings().session_cookie_name
|
||||
|
||||
@@ -146,12 +145,3 @@ def require_administrator(user: AppUser = Depends(get_current_user)) -> AppUser:
|
||||
if not user.is_admin:
|
||||
raise AuthorizationError("This area is for administrators.")
|
||||
return user
|
||||
|
||||
|
||||
def require_skill_approver(user: AppUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)) -> AppUser:
|
||||
"""Whoever decides publish requests: an administrator, or an approver on the firm's workspace.
|
||||
Wider than `require_administrator` on purpose; the rule itself is `skills.may_approve`."""
|
||||
if not skill_service.may_approve(db, user):
|
||||
raise AuthorizationError("This area is for approvers.")
|
||||
return user
|
||||
|
||||
@@ -53,8 +53,8 @@ Send = Callable[[dict], Awaitable[None]]
|
||||
#: Atrium is served in-process; these are the modules it may proxy to. A slug outside this set can
|
||||
#: never be configured, so a typo in FRONTDOOR_UPSTREAMS refuses start-up.
|
||||
ATRIUM = "atrium"
|
||||
MODULES = ("galena", "sygna", "counsel", "insider", "arbiter", "lexicon", "agora",
|
||||
"parafa", "scribe", "workflow")
|
||||
MODULES = ("galena", "sygna", "counsel", "insider", "arbiter", "lexicon", "agora", "panorama",
|
||||
"parafa", "scribe")
|
||||
SLUGS = (ATRIUM, *MODULES)
|
||||
|
||||
#: Uploads above this are refused: 413 up front on a declared Content-Length, or as soon as a chunked
|
||||
@@ -65,7 +65,7 @@ MAX_BODY = 100 * 1024 * 1024
|
||||
TIMEOUT = httpx.Timeout(connect=5.0, read=300.0, write=300.0, pool=10.0)
|
||||
|
||||
NOT_FOUND = (b"Not found. This server serves /atrium, /galena, /sygna, /counsel, /insider, "
|
||||
b"/arbiter, /lexicon, /agora, /parafa, /scribe and /workflow.")
|
||||
b"/arbiter, /lexicon, /agora, /panorama, /parafa and /scribe.")
|
||||
|
||||
# RFC 9110 7.6.1, plus the two non-standard ones still seen in the wild. Never forwarded either way,
|
||||
# together with every header a `Connection` header names.
|
||||
|
||||
@@ -115,8 +115,12 @@ async def ensure_loaded(root: str, key: str | None, model: str, *, may_switch: b
|
||||
raise ModelBusy(instances[0][0] or instances[0][1])
|
||||
for _, instance_id in instances:
|
||||
await _json(client, "POST", f"{root}/api/v1/models/unload", key, {"instance_id": instance_id})
|
||||
# Never more than the model was trained on: Bielik 11B v3.x stops at 32 768, and asking for
|
||||
# DEFAULT_CONTEXT stretched it past what it reads well. LM Studio says so in `max_context_length`.
|
||||
trained = next((m.get("max_context_length") for m in typed.get("data", []) if m.get("id") == model), None)
|
||||
context = min(DEFAULT_CONTEXT, trained) if isinstance(trained, int) and trained > 0 else DEFAULT_CONTEXT
|
||||
await _json(client, "POST", f"{root}/api/v1/models/load", key,
|
||||
{"model": model, "context_length": DEFAULT_CONTEXT})
|
||||
{"model": model, "context_length": context})
|
||||
|
||||
|
||||
async def stream_chat(root: str, key: str | None, model: str, messages: list[dict],
|
||||
|
||||
+2
-1
@@ -39,6 +39,7 @@ from .routers import (
|
||||
admin,
|
||||
admin_modules,
|
||||
admin_providers,
|
||||
attachments,
|
||||
auth,
|
||||
health,
|
||||
marketplace,
|
||||
@@ -168,7 +169,7 @@ async def _security_headers(request, call_next):
|
||||
|
||||
for router in (
|
||||
health.router, auth.router, users.router, admin.router, admin_modules.router,
|
||||
admin_providers.router, nodes.router, marketplace.router, models.router, skills.router,
|
||||
admin_providers.router, nodes.router, marketplace.router, models.router, skills.router, attachments.router,
|
||||
skills.agents, skills.publish_requests,
|
||||
):
|
||||
app.include_router(router, prefix=API_PREFIX)
|
||||
|
||||
@@ -17,7 +17,6 @@ import uuid
|
||||
|
||||
from dredd_core import Base, TimestampMixin, UUIDPkMixin
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
@@ -57,11 +56,6 @@ class Module(UUIDPkMixin, TimestampMixin, Base):
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
availability: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("100"))
|
||||
# False: a SERVICE module — on and reachable like any other (launcher, deep links, stats tiles,
|
||||
# module_permission all unchanged), but not an entry in the sidebar or the catalogue. Galena is
|
||||
# one (on everywhere, not in the menu): other modules open its screens by link.
|
||||
# Separate from `availability` on purpose: `off` takes access away, this only takes the entry.
|
||||
in_menu: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
|
||||
|
||||
__table_args__ = (
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
A stable identity (`skill`, `agent`) points at frozen versions (`skill_version`, `agent_version`):
|
||||
changing content is a new version, never an edit, which is why the runtime role holds no UPDATE or
|
||||
DELETE on the version tables (revision 0015). The identity rows stay mutable — scope, status and
|
||||
DELETE on the version tables (revision 0010). The identity rows stay mutable — scope, status and
|
||||
`current_version_id` move through publication and archiving.
|
||||
|
||||
These are NOT nodes of the org tree (the tree holds units only), so access is not `authz`'s: it is
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""POST /chat/attachments: the text of a file attached to a Home chat question. Nothing is stored.
|
||||
|
||||
The body is the file's raw bytes (no multipart, so no parser dependency), its name in `?name=`. The
|
||||
audit row names the file and its size, never its content.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user
|
||||
from ..models import AppUser
|
||||
from ..services import attachments, audit
|
||||
|
||||
router = APIRouter(tags=["chat"])
|
||||
|
||||
|
||||
@router.post("/chat/attachments")
|
||||
async def extract(request: Request, name: str = Query(min_length=1, max_length=255),
|
||||
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
data = bytearray()
|
||||
async for chunk in request.stream():
|
||||
data += chunk
|
||||
if len(data) > attachments.MAX_BYTES:
|
||||
break # extract() refuses it; nothing past the limit is read
|
||||
# A 300-page PDF parses for seconds: off the event loop, or every other request waits for it.
|
||||
# ponytail: no time budget per document; a subprocess with a timeout if a crafted PDF ever stalls a worker.
|
||||
out = await run_in_threadpool(attachments.extract, name, bytes(data))
|
||||
audit.record(db, action="chat.attachment", entity_type="attachment", actor_id=user.id, detail=name[:200],
|
||||
ip=client_ip(request), diff={"kind": out["kind"], "bytes": len(data), "pages": out["pages"],
|
||||
"chars": out["chars"]})
|
||||
db.commit()
|
||||
return out
|
||||
@@ -9,11 +9,11 @@ from fastapi import APIRouter, Depends, Query, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user, require_administrator
|
||||
from ..deps import client_ip, get_current_user
|
||||
from ..models import AppUser
|
||||
from ..schemas import NoteIn
|
||||
from ..services import marketplace as service
|
||||
from ..services import stats, trends
|
||||
from ..services import stats
|
||||
|
||||
router = APIRouter(tags=["marketplace"])
|
||||
|
||||
@@ -30,14 +30,6 @@ def home_stats(db: Session = Depends(get_db),
|
||||
return stats.home(db, user)
|
||||
|
||||
|
||||
@router.get("/home/trends")
|
||||
def home_trends(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(require_administrator)) -> dict:
|
||||
"""Trends from the event log: events per day and kind over 30 days, and how long documents took
|
||||
from their first version to signature. Platform-wide sums, so platform administrators only."""
|
||||
return trends.home(db)
|
||||
|
||||
|
||||
@router.get("/marketplace")
|
||||
def browse(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user),
|
||||
q: str = Query("", max_length=100),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""A person's skills and agents: list, read, write versions, archive, publish, export and import —
|
||||
and the approvers' queue of publish requests that the T1 setting (`skills_firm_publish`) fills.
|
||||
and the administrator's queue of publish requests that the T1 setting (`skills_firm_publish`) fills.
|
||||
|
||||
No access rule lives here. Skills are not org-tree nodes, so `authz` has nothing to say about them;
|
||||
`services/skills.py` is the one place that decides who sees and changes what (its docstring says why
|
||||
@@ -18,7 +18,7 @@ from fastapi.routing import APIRoute
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user, require_skill_approver
|
||||
from ..deps import client_ip, get_current_user, require_administrator
|
||||
from ..models import AppUser
|
||||
from ..schemas import AgentCreateIn, AgentVersionIn, NoteIn, SkillCreateIn, SkillVersionIn
|
||||
from ..services import skills as service
|
||||
@@ -108,12 +108,6 @@ def import_skills(request: Request, filename: str | None = Query(default=None, m
|
||||
return out
|
||||
|
||||
|
||||
# Before `/{skill_id}`, which would take "permissions" for an id and answer 422.
|
||||
@router.get("/permissions")
|
||||
def permissions(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return {"approve": service.may_approve(db, user)}
|
||||
|
||||
|
||||
@router.get("/{skill_id}")
|
||||
def get_skill(skill_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
@@ -135,13 +129,6 @@ def get_version(skill_id: uuid.UUID, n: int, db: Session = Depends(get_db),
|
||||
return service.get_version(db, user, skill_id, n)
|
||||
|
||||
|
||||
@router.get("/{skill_id}/versions/{n}/files/{path:path}")
|
||||
def get_file(skill_id: uuid.UUID, n: int, path: str, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
media_type, content = service.get_file(db, user, skill_id, n, path)
|
||||
return Response(content=content, media_type=media_type)
|
||||
|
||||
|
||||
@router.post("/{skill_id}/archive")
|
||||
def archive_skill(skill_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
@@ -232,18 +219,18 @@ def export_agent(agent_id: uuid.UUID, request: Request, n: int | None = Query(de
|
||||
return zip_response(name, data)
|
||||
|
||||
|
||||
# The service checks the approver again; the guard here is what keeps the routes out of reach
|
||||
# The service checks the administrator again; the guard here is what keeps the routes out of reach
|
||||
# of anybody else before a database is touched.
|
||||
@publish_requests.get("")
|
||||
def pending_publish_requests(db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_skill_approver)) -> list[dict]:
|
||||
admin: AppUser = Depends(require_administrator)) -> list[dict]:
|
||||
return service.pending_publish_requests(db, admin)
|
||||
|
||||
|
||||
@publish_requests.post("/{request_id}/approve")
|
||||
def approve_publish(request_id: uuid.UUID, request: Request, body: NoteIn | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_skill_approver)) -> dict:
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
out = service.decide_publish(db, admin, request_id, approve=True,
|
||||
note=body.note if body else None, ip=client_ip(request))
|
||||
db.commit()
|
||||
@@ -253,7 +240,7 @@ def approve_publish(request_id: uuid.UUID, request: Request, body: NoteIn | None
|
||||
@publish_requests.post("/{request_id}/decline")
|
||||
def decline_publish(request_id: uuid.UUID, request: Request, body: NoteIn | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_skill_approver)) -> dict:
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
out = service.decide_publish(db, admin, request_id, approve=False,
|
||||
note=body.note if body else None, ip=client_ip(request))
|
||||
db.commit()
|
||||
|
||||
@@ -34,7 +34,6 @@ from ..schemas import (
|
||||
ModuleTokenIn,
|
||||
PasswordChangeIn,
|
||||
PasswordResetIn,
|
||||
UserBriefOut,
|
||||
UserCreateIn,
|
||||
UserOut,
|
||||
UserProfileIn,
|
||||
@@ -55,31 +54,15 @@ def _user_out(u: AppUser, modules: dict[str, str] | None = None) -> dict:
|
||||
"modules": modules or {}}
|
||||
|
||||
|
||||
def _user_brief(u: AppUser) -> UserBriefOut:
|
||||
"""What anybody signed in may know about an account: who it is, and whether it can be picked."""
|
||||
return UserBriefOut(id=str(u.id), email=u.email, full_name=u.full_name, is_active=u.is_active)
|
||||
|
||||
|
||||
@router.get("/users", response_model=list[UserOut] | list[UserBriefOut])
|
||||
@router.get("/users", response_model=list[UserOut])
|
||||
def list_users(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> list[UserOut] | list[UserBriefOut]:
|
||||
"""Every signed-in user may list users: a picker needs names, and an email address inside the
|
||||
instance is not the secret worth hiding here.
|
||||
|
||||
**Who holds which tier is another matter, and only an administrator is told.** `is_admin` and
|
||||
the per-module roles are the map of whose account is worth taking over, and this route answers
|
||||
any credential — an ordinary account, a read-only app token. They used to come along because
|
||||
one helper built every row. So an administrator gets the whole standing (`UserOut`, what the
|
||||
Users screen draws) and everybody else gets `UserBriefOut`: the fields a picker uses and nothing
|
||||
about tiers. Absent, not `false` or empty: a row that said `is_admin: false` about an
|
||||
administrator would be a lie, and a client must not be able to mistake "not told" for "none".
|
||||
"""
|
||||
_: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
"""Every signed-in user may list users: the console needs names to render "assigned to"
|
||||
pickers, and an email address inside the instance is not the secret worth hiding here."""
|
||||
users = auth_service.list_users(db)
|
||||
if not user.is_admin:
|
||||
return [_user_brief(u) for u in users]
|
||||
# One query for the whole page, not one per row — see services/moderation.py.
|
||||
standing = moderation.module_roles_by_user(db, [u.id for u in users])
|
||||
return [UserOut(**_user_out(u, standing.get(u.id))) for u in users]
|
||||
return [_user_out(u, standing.get(u.id)) for u in users]
|
||||
|
||||
|
||||
@router.post("/users", response_model=UserOut, status_code=201)
|
||||
|
||||
+6
-25
@@ -74,16 +74,6 @@ class UserOut(BaseModel):
|
||||
modules: dict[str, str] = {}
|
||||
|
||||
|
||||
class UserBriefOut(BaseModel):
|
||||
"""A person as anybody signed in may see them in `GET /users`: enough to pick somebody, and
|
||||
nothing about what they may do. The tiers (`is_admin`, `modules`) are for administrators only
|
||||
and are left out here rather than blanked — see `routers/users.list_users`."""
|
||||
id: str
|
||||
email: str
|
||||
full_name: str
|
||||
is_active: bool
|
||||
|
||||
|
||||
class LoginOut(BaseModel):
|
||||
"""The reply to a sign-in: who signed in, and NOT the session token. That lives in the HttpOnly
|
||||
cookie only, where no page script can read it (`routers/auth.py`). `response_model` filters the
|
||||
@@ -215,8 +205,6 @@ class ModuleUpdateIn(BaseModel):
|
||||
status: str | None = Field(default=None, max_length=16)
|
||||
availability: str | None = Field(default=None, max_length=16)
|
||||
sort_order: int | None = Field(default=None, ge=0, le=10000)
|
||||
# False makes a service module: reachable as before, but no entry in the sidebar or catalogue.
|
||||
in_menu: bool | None = None
|
||||
|
||||
|
||||
class ModuleCreateIn(ModuleUpdateIn):
|
||||
@@ -305,6 +293,11 @@ class ProviderPolicyIn(BaseModel):
|
||||
eu_only: bool | None = None
|
||||
|
||||
|
||||
class MyModelKeyIn(BaseModel):
|
||||
"""A person's own API key for a `key_mode = "user"` provider. Write-only, like the firm's."""
|
||||
api_key: str = Field(max_length=4096, repr=False)
|
||||
|
||||
|
||||
# ── skills ─────────────────────────────────────────────────────────────────────
|
||||
# Lengths and transport only. What a skill may say (kebab slug, description ≤ 1024, body ≤ 30 000,
|
||||
# file types and signatures) is `services/skill_pack.read_pack`'s, so a typed skill and an imported
|
||||
@@ -344,22 +337,13 @@ SmallJson = Annotated[dict[str, Any] | None, AfterValidator(_small_json)]
|
||||
|
||||
|
||||
class SkillVersionIn(BaseModel):
|
||||
"""A new version. `None` = carried over from the base version; `files: {}` removes them all.
|
||||
|
||||
The base is `base_n` when given (the version the person was looking at, which they must be able
|
||||
to read: Ruling 15). Without it, Ruling 9: the actor's own newest version if it is newer than
|
||||
the current one, else the current one, else the owner's newest. Never "the newest overall",
|
||||
which may be somebody else's proposal."""
|
||||
"""A new version. `None` = carried over from the newest one; `files: {}` removes them all."""
|
||||
name: str | None = Field(default=None, max_length=200)
|
||||
description: str | None = Field(default=None, max_length=2000)
|
||||
body: str | None = Field(default=None, max_length=60_000)
|
||||
license: str | None = Field(default=None, max_length=200)
|
||||
metadata: SmallJson = None
|
||||
files: SkillFiles = Field(default=None, max_length=200)
|
||||
# path -> base64: the previous version's files with these replaced or added. Not with `files`.
|
||||
file_updates: SkillFiles = Field(default=None, max_length=200)
|
||||
# The version this one is made on (the one the person was looking at); None = the default base.
|
||||
base_n: int | None = Field(default=None, ge=1)
|
||||
|
||||
|
||||
class SkillCreateIn(SkillVersionIn):
|
||||
@@ -382,6 +366,3 @@ class AgentVersionIn(BaseModel):
|
||||
class AgentCreateIn(AgentVersionIn):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
instructions: str = Field(max_length=60_000)
|
||||
class MyModelKeyIn(BaseModel):
|
||||
"""A person's own API key for a `key_mode = "user"` provider. Write-only, like the firm's."""
|
||||
api_key: str = Field(max_length=4096, repr=False)
|
||||
|
||||
+17
-37
@@ -16,7 +16,6 @@ from .config import get_settings
|
||||
from .db import SessionLocal
|
||||
from .enums import Availability, ModuleStatus, NodeKind
|
||||
from .models import AppSetting, Module, Node
|
||||
from .services import archive_reader
|
||||
from .services import auth as auth_service
|
||||
from .services import marketplace
|
||||
|
||||
@@ -36,11 +35,9 @@ CATALOG_SEEDED = "_seed.catalog"
|
||||
# is already in the catalogue — an administrator added it by hand — only the marker is written; once
|
||||
# the marker exists the entry is never offered again, so deleting it afterwards sticks. A fresh
|
||||
# install gets these with the rest of FAMILY and sets their markers then. The next module that
|
||||
# joins appends its slug here. The one exception is Panorama, retired from the platform:
|
||||
# it left FAMILY and this tuple, a box seeded earlier keeps its row, hidden from the menu by
|
||||
# revision 0018, and a fresh install never offers it.
|
||||
ADDED_AFTER_FIRST_SEED: tuple[str, ...] = ("insider", "arbiter", "lexicon", "agora",
|
||||
"parafa", "scribe", "workflow")
|
||||
# joins appends its slug here; nothing ever leaves this tuple.
|
||||
ADDED_AFTER_FIRST_SEED: tuple[str, ...] = ("insider", "arbiter", "lexicon", "agora", "panorama",
|
||||
"parafa", "scribe")
|
||||
|
||||
|
||||
def _marker(slug: str) -> str:
|
||||
@@ -67,8 +64,6 @@ def _marker(slug: str) -> str:
|
||||
FAMILY: list[dict] = [
|
||||
{
|
||||
"slug": "galena", "name": "Galena", "hue": "violet", "glyph": "galena", "sort_order": 10,
|
||||
# A service, not a menu entry: other modules open its screens by link.
|
||||
"in_menu": False,
|
||||
"category": "Dokumenty",
|
||||
"tagline": "Dysk w chmurze z pełną historią zmian w repozytoriach git.",
|
||||
"description": (
|
||||
@@ -120,9 +115,6 @@ FAMILY: list[dict] = [
|
||||
# (Open Color indigo, its CLAUDE.md). In English the tagline reads "Contract analysis with
|
||||
# a lawyer's sign-off". The slug is its path (/arbiter), schema, roles and MODULE_SLUG.
|
||||
"slug": "arbiter", "name": "Arbiter", "hue": "indigo", "glyph": "shield", "sort_order": 60,
|
||||
# A service too, and a headless one: Arbiter has no console (Atrium#53, stage 2). Contracts
|
||||
# are checked from the chat and its report panel, which call Arbiter's API.
|
||||
"in_menu": False,
|
||||
"category": "Umowy",
|
||||
"tagline": "Analiza umów z akceptacją prawnika.",
|
||||
"description": (
|
||||
@@ -136,14 +128,12 @@ FAMILY: list[dict] = [
|
||||
# (Open Color green, its CLAUDE.md). In English the tagline reads "The clause library and
|
||||
# standards". The slug is its path (/lexicon), schema, roles and MODULE_SLUG.
|
||||
"slug": "lexicon", "name": "Lexicon", "hue": "green", "glyph": "file", "sort_order": 70,
|
||||
# No console of its own (decision of 18.11, issue #53): a service the chat calls; the
|
||||
# catalogue and the menu show the three contract modules as one entry, „Umowy”.
|
||||
"in_menu": False,
|
||||
"category": "Umowy",
|
||||
"tagline": "Biblioteka klauzul.",
|
||||
"tagline": "Biblioteka klauzul i standardów.",
|
||||
"description": (
|
||||
"Lexicon tnie wzory umów na klauzule, indeksuje je do wyszukiwania pełnotekstowego, "
|
||||
"porządkuje według typów. Standardy sprawdzania umów są w skillach (Atrium → Skille)."
|
||||
"porządkuje według typów i przechowuje standardy (reguła, wzorcowe brzmienie, "
|
||||
"stanowisko rezerwowe), według których Arbiter sprawdza umowy."
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -157,6 +147,17 @@ FAMILY: list[dict] = [
|
||||
"jako kolejne wersje w Galenie, porównanie dwóch rund i wewnętrzne komentarze zespołu."
|
||||
),
|
||||
},
|
||||
{
|
||||
# The platform's dashboard (the split plan's M4). Pink is Panorama's own brand colour (Open
|
||||
# Color pink, its CLAUDE.md). In English the tagline reads "The platform dashboard".
|
||||
"slug": "panorama", "name": "Panorama", "hue": "pink", "glyph": "chart", "sort_order": 90,
|
||||
"category": "Pulpit",
|
||||
"tagline": "Pulpit platformy.",
|
||||
"description": (
|
||||
"Panorama zbiera bieżące liczby z modułów platformy, każdą z uprawnieniami oglądającej "
|
||||
"osoby, i pokazuje trendy z dziennika zdarzeń."
|
||||
),
|
||||
},
|
||||
{
|
||||
# Electronic signing of PDFs (the split plan's M6): PAdES signatures through pyHanko, on an
|
||||
# uploaded file or a Galena document. Yellow is Parafa's own brand colour (Open Color yellow,
|
||||
@@ -176,9 +177,6 @@ FAMILY: list[dict] = [
|
||||
# (Open Color lime, its CLAUDE.md). In English the tagline reads "Drafting documents from
|
||||
# templates and clauses". The slug is its path (/scribe), schema, roles and MODULE_SLUG.
|
||||
"slug": "scribe", "name": "Scribe", "hue": "lime", "glyph": "file", "sort_order": 110,
|
||||
# No console of its own (decision of 18.11, issue #53): a service the chat calls; the
|
||||
# catalogue and the menu show the three contract modules as one entry, „Umowy”.
|
||||
"in_menu": False,
|
||||
"category": "Dokumenty", "status": ModuleStatus.live.value,
|
||||
"tagline": "Tworzenie dokumentów z szablonów i klauzul.",
|
||||
"description": (
|
||||
@@ -186,20 +184,6 @@ FAMILY: list[dict] = [
|
||||
"zapisanymi w kodzie i eksportuje gotowy projekt do Galeny jako nowy dokument."
|
||||
),
|
||||
},
|
||||
{
|
||||
# The platform's general approval engine (decision of 2026-11-18; not the retired `compass`,
|
||||
# whose slug revision 0014 removed). Gray is the one tile hue no sibling wears. In English the
|
||||
# tagline reads "Approval runs for documents, files and requests". The slug is its path
|
||||
# (/workflow), schema, roles and MODULE_SLUG.
|
||||
"slug": "workflow", "name": "Workflow", "hue": "gray", "glyph": "clock", "sort_order": 120,
|
||||
"category": "Dokumenty", "status": ModuleStatus.live.value,
|
||||
"tagline": "Obiegi akceptacji dokumentów, plików i wniosków.",
|
||||
"description": (
|
||||
"Workflow prowadzi obieg akceptacji — na dokumencie z Galeny, przesłanym pliku albo "
|
||||
"wniosku — przez etapy zatwierdzane przez osoby, grupy zatwierdzających albo role z "
|
||||
"Galeny, z historią każdej decyzji i powrotem do wcześniejszego etapu po odrzuceniu."
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@@ -279,10 +263,6 @@ def run(session_factory: sessionmaker | None = None) -> None:
|
||||
for module in db.scalars(select(Module)).all():
|
||||
marketplace.sync_module(db, None, module)
|
||||
|
||||
# The Archive's technical account and its four grants (Atrium#53). Idempotent; its token is
|
||||
# minted once by an operator (`python -m app.archive_reader`), never here.
|
||||
archive_reader.ensure(db)
|
||||
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -57,28 +57,6 @@ def count_administrators(db: DbSession, *, excluding: uuid.UUID | None = None) -
|
||||
return db.scalar(stmt) or 0
|
||||
|
||||
|
||||
def _lock_administrators(db: DbSession) -> None:
|
||||
"""Hold every usable administrator's row until this transaction ends, so that the count that
|
||||
follows is still true when the change is written.
|
||||
|
||||
Without it the guard is a check followed by a write with nothing in between: "demote A" and
|
||||
"demote B", in flight at once, each count the other as still there, both pass, and the platform
|
||||
is left with nobody — the very state the guard is for, reached by two clicks landing together.
|
||||
With it the second request waits here; when the first commits, PostgreSQL re-checks the rows it
|
||||
waited for, and the count below (a new statement) sees what was committed, so the second one is
|
||||
refused.
|
||||
|
||||
`FOR NO KEY UPDATE`, not `FOR UPDATE`: every row another table writes with a foreign key to
|
||||
`app_user` — a session, an audit row, in any module — takes a key-share lock on the person, and
|
||||
`FOR UPDATE` would make all of those wait on an administrator's row. The weaker lock still
|
||||
excludes itself and every `UPDATE` of the row, which is all this needs. Ordered by id, so two
|
||||
requests always take the rows in the same order and cannot deadlock each other.
|
||||
"""
|
||||
db.execute(select(AppUser.id)
|
||||
.where(AppUser.is_admin.is_(True), AppUser.is_active.is_(True))
|
||||
.order_by(AppUser.id).with_for_update(key_share=True)).all()
|
||||
|
||||
|
||||
def _assert_not_last_administrator(db: DbSession, user: AppUser) -> None:
|
||||
"""Refuse a change that would leave the platform with no administrator who can sign in.
|
||||
|
||||
@@ -86,14 +64,9 @@ def _assert_not_last_administrator(db: DbSession, user: AppUser) -> None:
|
||||
administrator is perfectly ordinary while somebody else still holds the tier. What is refused is
|
||||
the *last* one, and the message says what to do instead, because a person who hits this guard
|
||||
has a job to finish and a bare 409 does not help them finish it.
|
||||
|
||||
Counted under a lock on the administrators' rows (`_lock_administrators`): the caller writes
|
||||
straight after this returns, in the same transaction, and two such changes must not each pass on
|
||||
a count the other is about to make false.
|
||||
"""
|
||||
if not user.is_admin or not user.is_active:
|
||||
return
|
||||
_lock_administrators(db)
|
||||
if count_administrators(db, excluding=user.id) == 0:
|
||||
raise ConflictError(
|
||||
"This is the last administrator. Make someone else an administrator first: with "
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
"""The Archive's technical account (Atrium#53, step 4): how Galena reads evidence without a person.
|
||||
|
||||
When Galena hears `document.signed` or `workflow.signed_on_paper` there is no person's token to
|
||||
collect the archive package with, so it uses this account's. Least privilege, in four layers:
|
||||
|
||||
* **No password, so no sign-in.** `password_hash` is NULL; `authenticate` refuses such an account
|
||||
with the same timing as a wrong password. The only credential is the app token minted here.
|
||||
* **A read-only token.** `scope = read`: every module refuses an unsafe method with it at the edge
|
||||
(the one exception is Parafa's `POST /seal`, which Parafa allows to this account alone).
|
||||
* **User tier in exactly four modules** — Parafa, Workflow, Agora, Arbiter — written directly, not
|
||||
through the catalogue's assignments, and kept out of the reconciliation (`marketplace._active_ids`
|
||||
leaves it out), so a module whose availability is `everyone` never admits it as well, and a sweep
|
||||
never takes these four away.
|
||||
* **A fixed id** (`ARCHIVE_READER_ID`) every module knows, which fences it to `GET /evidence` there
|
||||
(404 on every other route). An id, not an e-mail, so nobody can register their way into it.
|
||||
|
||||
The seed calls `ensure` on every deploy (idempotent). The token is minted once by an operator —
|
||||
`python -m app.archive_reader` in the hub's migrate container — and goes into Galena's deployment
|
||||
as `ARCHIVE_READER_TOKEN`; it is printed once and never stored here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..config import get_settings
|
||||
from ..models import AppUser, Session
|
||||
from . import accounts, audit, moderation
|
||||
|
||||
EMAIL = "archive-reader@archiwum.galena"
|
||||
FULL_NAME = "Archiwum (konto techniczne)"
|
||||
#: The modules Galena collects evidence from, as `user`. Nothing else.
|
||||
MODULES = ("parafa", "workflow", "agora", "arbiter")
|
||||
TOKEN_NAME = "Galena: archiwum"
|
||||
|
||||
|
||||
def reader_id():
|
||||
"""The fixed id every module fences (their `ARCHIVE_READER_ID`): change both together."""
|
||||
return get_settings().archive_reader_id
|
||||
|
||||
|
||||
def ensure(db: DbSession) -> AppUser:
|
||||
"""The account and its four grants, created when missing. No commit; nothing when it is there."""
|
||||
user = db.get(AppUser, reader_id())
|
||||
if user is None:
|
||||
user = AppUser(id=reader_id(), email=EMAIL, full_name=FULL_NAME, password_hash=None,
|
||||
is_admin=False, is_active=True)
|
||||
db.add(user)
|
||||
db.flush()
|
||||
audit.record(db, action="archive_reader.created", entity_type="user", entity_id=user.id,
|
||||
actor_id=None, detail=",".join(MODULES))
|
||||
if get_settings().shares_identity and user.is_active:
|
||||
held = moderation.module_roles(db, user.id)
|
||||
for slug in MODULES:
|
||||
if slug not in held:
|
||||
moderation.grant(db, None, module_slug=slug, user_id=user.id,
|
||||
role=moderation.USER)
|
||||
return user
|
||||
|
||||
|
||||
def mint(db: DbSession) -> tuple[Session, str]:
|
||||
"""A read-only app token for the account, with the longest idle window the policy allows (each
|
||||
use slides it forward). Returns (row, raw); the raw value exists only in the return."""
|
||||
user = ensure(db)
|
||||
row, raw = accounts.create_module_token(
|
||||
db, user, module_slug="galena", name=TOKEN_NAME, scope="read",
|
||||
idle_days=get_settings().app_token_max_idle_days)
|
||||
audit.record(db, action="archive_reader.token_minted", entity_type="session",
|
||||
entity_id=row.id, actor_id=None, detail=row.token_prefix)
|
||||
return row, raw
|
||||
|
||||
|
||||
__all__ = ["MODULES", "ensure", "mint", "reader_id"]
|
||||
@@ -0,0 +1,117 @@
|
||||
"""A file attached to a Home chat question: its text, and nothing kept.
|
||||
|
||||
The bytes arrive, the text goes back, and neither is stored: the console holds the text for the
|
||||
conversation and sends it to the model as one more source, the way it sends a contract or a matter.
|
||||
So the privacy of an attachment is the privacy of the question itself (the provider's policy decides
|
||||
where it may go), and there is no file anywhere to delete afterwards.
|
||||
|
||||
PDF through pypdf (BSD-3, pure Python), DOCX through the standard library (it is a ZIP of XML),
|
||||
plain text decoded as UTF-8 and, failing that, as Windows-1250, which is what Polish text files
|
||||
from older Office installations are. Every page of a PDF is marked `[strona N]` so the model can say
|
||||
where it read something.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import zipfile
|
||||
from xml.etree import ElementTree
|
||||
|
||||
from ..errors import ValidationError
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PAGES = 300
|
||||
MAX_CHARS = 400_000 # more than any model here reads; the console trims to the model's budget
|
||||
_MAX_XML = 50 * 1024 * 1024 # word/document.xml unpacked: a ZIP bomb stops here, not in memory
|
||||
TEXT_TYPES = (".txt", ".md", ".csv")
|
||||
_W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
|
||||
|
||||
|
||||
def _refuse(code: str, pl: str, en: str) -> ValidationError:
|
||||
return ValidationError(pl, {"code": code, "en": en})
|
||||
|
||||
|
||||
def _pdf(data: bytes) -> tuple[str, int]:
|
||||
from pypdf import PdfReader
|
||||
from pypdf.errors import PdfReadError
|
||||
try:
|
||||
reader = PdfReader(io.BytesIO(data))
|
||||
if reader.is_encrypted and not reader.decrypt(""):
|
||||
raise _refuse("attachment_encrypted", "Plik PDF jest zabezpieczony hasłem.",
|
||||
"The PDF is password-protected.")
|
||||
pages = reader.pages
|
||||
if len(pages) > MAX_PAGES:
|
||||
raise _refuse("attachment_too_long", f"Plik ma więcej niż {MAX_PAGES} stron.",
|
||||
f"The file has more than {MAX_PAGES} pages.")
|
||||
parts, total = [], 0
|
||||
for n, page in enumerate(pages, 1):
|
||||
text = (page.extract_text() or "").strip()
|
||||
parts.append(f"[strona {n}]\n{text}")
|
||||
total += len(text)
|
||||
if total > MAX_CHARS:
|
||||
break
|
||||
except PdfReadError as exc:
|
||||
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku PDF.",
|
||||
"This PDF cannot be read.") from exc
|
||||
if not total:
|
||||
raise _refuse("attachment_no_text",
|
||||
"Ten PDF nie ma warstwy tekstu (to skan). Potrzebne jest rozpoznanie tekstu (OCR).",
|
||||
"This PDF has no text layer (a scan). It needs OCR.")
|
||||
return "\n\n".join(parts), len(pages)
|
||||
|
||||
|
||||
def _docx(data: bytes) -> str:
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
||||
info = z.getinfo("word/document.xml")
|
||||
if info.file_size > _MAX_XML:
|
||||
raise _refuse("attachment_too_long", "Dokument jest za duży.", "The document is too large.")
|
||||
xml = z.read(info)
|
||||
# Word never writes a DTD; without one there are no entities to expand (XXE, billion laughs).
|
||||
if b"<!DOCTYPE" in xml or b"<!ENTITY" in xml:
|
||||
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku DOCX.",
|
||||
"This DOCX cannot be read.")
|
||||
root = ElementTree.fromstring(xml)
|
||||
except (zipfile.BadZipFile, KeyError, ElementTree.ParseError) as exc:
|
||||
raise _refuse("attachment_unreadable", "Nie da się odczytać tego pliku DOCX.",
|
||||
"This DOCX cannot be read.") from exc
|
||||
lines = []
|
||||
for p in root.iter(f"{_W}p"):
|
||||
bits = []
|
||||
for el in p.iter():
|
||||
if el.tag == f"{_W}t":
|
||||
bits.append(el.text or "")
|
||||
elif el.tag == f"{_W}tab":
|
||||
bits.append("\t")
|
||||
elif el.tag in (f"{_W}br", f"{_W}cr"):
|
||||
bits.append("\n")
|
||||
lines.append("".join(bits))
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
def _plain(data: bytes) -> str:
|
||||
try:
|
||||
return data.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
return data.decode("cp1250", errors="replace")
|
||||
|
||||
|
||||
def extract(name: str, data: bytes) -> dict:
|
||||
"""`{name, kind, pages, chars, text}` of one attached file, or a 422 saying why not."""
|
||||
if len(data) > MAX_BYTES:
|
||||
raise _refuse("attachment_too_large", "Plik jest większy niż 10 MB.", "The file is larger than 10 MB.")
|
||||
lower = name.lower()
|
||||
pages = None
|
||||
if lower.endswith(".pdf") and data.startswith(b"%PDF"):
|
||||
kind = "pdf"
|
||||
text, pages = _pdf(data)
|
||||
elif lower.endswith(".docx") and data.startswith(b"PK"):
|
||||
kind, text = "docx", _docx(data)
|
||||
elif lower.endswith(TEXT_TYPES) and b"\x00" not in data[:4096]:
|
||||
kind, text = "text", _plain(data)
|
||||
else:
|
||||
raise _refuse("attachment_type", "Ten rodzaj pliku nie jest obsługiwany. Dołącz PDF, DOCX, TXT, MD albo CSV.",
|
||||
"This kind of file is not supported. Attach a PDF, DOCX, TXT, MD or CSV.")
|
||||
text = text.strip()
|
||||
if not text:
|
||||
raise _refuse("attachment_empty", "W pliku nie ma tekstu.", "The file has no text.")
|
||||
return {"name": name, "kind": kind, "pages": pages, "chars": len(text), "text": text[:MAX_CHARS]}
|
||||
@@ -99,7 +99,7 @@ GLYPHS = ("galena", "sygna", "percent", "compass", "scale", "folder", "file", "u
|
||||
SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
||||
TEXT_LIMITS = {"name": 80, "tagline": 140, "description": 4000, "category": 40}
|
||||
EDITABLE = ("name", "tagline", "description", "category", "hue", "glyph", "url", "health_url",
|
||||
"status", "availability", "sort_order", "in_menu")
|
||||
"status", "availability", "sort_order")
|
||||
NOTE_LIMIT = 1000
|
||||
# Closed vocabularies a field must come from.
|
||||
_CHOICES = {"hue": HUES, "glyph": GLYPHS, "status": tuple(ModuleStatus),
|
||||
@@ -151,10 +151,6 @@ def _clean_field(field: str, value):
|
||||
if not isinstance(value, int) or isinstance(value, bool) or not 0 <= value <= 10000:
|
||||
raise ValidationError("sort_order must be a whole number from 0 to 10000.")
|
||||
return value
|
||||
if field == "in_menu":
|
||||
if not isinstance(value, bool):
|
||||
raise ValidationError("in_menu must be true or false.")
|
||||
return value
|
||||
raise ValidationError(f"{field} cannot be changed.")
|
||||
|
||||
|
||||
@@ -272,10 +268,7 @@ def _active_ids(db: DbSession) -> set[uuid.UUID]:
|
||||
every module they moderated. Their rows are frozen until they come back, and the thing that
|
||||
keeps them out meanwhile is that they cannot sign in at all.
|
||||
"""
|
||||
# The Archive's technical account (services/archive_reader.py) holds exactly the grants its
|
||||
# seed writes: no assignment, no `everyone` module admits it and no sweep revokes them.
|
||||
return set(db.scalars(select(AppUser.id).where(
|
||||
AppUser.is_active.is_(True), AppUser.id != app_settings.archive_reader_id)).all())
|
||||
return set(db.scalars(select(AppUser.id).where(AppUser.is_active.is_(True))).all())
|
||||
|
||||
|
||||
def _catalogue(db: DbSession) -> list[Module]:
|
||||
@@ -536,7 +529,6 @@ def _card(m: Module, user: AppUser, *, has_access: bool, pending: bool,
|
||||
out = {
|
||||
"slug": m.slug, "name": m.name, "tagline": m.tagline, "category": m.category,
|
||||
"hue": m.hue, "glyph": m.glyph, "status": m.status,
|
||||
"in_menu": m.in_menu,
|
||||
"configured": url is not None,
|
||||
"has_access": has_access, "launchable": launchable,
|
||||
# Withheld unless offered — which keeps an unoffered module out of the launcher, and does
|
||||
@@ -563,10 +555,7 @@ def launcher(db: DbSession, user: AppUser) -> list[dict]:
|
||||
|
||||
|
||||
def browse(db: DbSession, user: AppUser, *, q: str = "", category: str = "") -> dict:
|
||||
# A service module (`in_menu` false) is not something to pick from a catalogue: everyone who
|
||||
# should have it already does, and its screens open by link from the modules that use it.
|
||||
where = [] if user.is_admin else [Module.availability != Availability.off,
|
||||
Module.in_menu.is_(True)]
|
||||
where = [] if user.is_admin else [Module.availability != Availability.off]
|
||||
modules = _ordered(db, *where)
|
||||
categories = sorted({m.category for m in modules if m.category}, key=str.casefold)
|
||||
needle = q.strip().casefold()
|
||||
@@ -654,7 +643,7 @@ def _admin_out(m: Module) -> dict:
|
||||
"id": str(m.id), "slug": m.slug, "name": m.name, "tagline": m.tagline,
|
||||
"description": m.description, "category": m.category, "hue": m.hue, "glyph": m.glyph,
|
||||
"url": m.url, "health_url": m.health_url, "status": m.status,
|
||||
"availability": m.availability, "sort_order": m.sort_order, "in_menu": m.in_menu,
|
||||
"availability": m.availability, "sort_order": m.sort_order,
|
||||
"created_at": m.created_at.isoformat() if m.created_at else None,
|
||||
"updated_at": m.updated_at.isoformat() if m.updated_at else None,
|
||||
}
|
||||
|
||||
@@ -207,7 +207,6 @@ async def refresh(db: DbSession, actor: AppUser, provider_id: uuid.UUID, *, ip:
|
||||
# platform administrator as `is_admin`. Only `openai`-dialect models: Home speaks chat completions.
|
||||
|
||||
CHAT_DIALECT = "openai"
|
||||
KEY_UNREADABLE = "model_provider_key_unreadable"
|
||||
USER_KEY_MISSING = "model_provider_user_key_missing"
|
||||
USER_KEY_UNREADABLE = "model_provider_user_key_unreadable"
|
||||
|
||||
@@ -217,7 +216,7 @@ def usable_models(db: DbSession, user: AppUser) -> list[dict]:
|
||||
tells Home that a `user` provider needs the person's own key (Settings → My model keys)."""
|
||||
return [
|
||||
{"id": m["id"], "provider": p.name, "kind": p.kind, "stays_in_the_eu": core.stays_in_the_eu(p),
|
||||
"key_mode": p.key_mode}
|
||||
"key_mode": p.key_mode, "context_window": m.get("context_window")}
|
||||
for p in core.usable_providers(db, is_admin=bool(user.is_admin))
|
||||
for m in p.models or [] if m.get("dialect", CHAT_DIALECT) == CHAT_DIALECT
|
||||
]
|
||||
|
||||
+46
-195
@@ -11,28 +11,18 @@ business. An administrator gets no exception here: a personal skill is a lawyer'
|
||||
and an administrator sees one only inside a publish request (the publication path, not this one).
|
||||
|
||||
Who may CHANGE one (`can_edit`): the owner, and for a firm skill also an administrator. Everybody
|
||||
else may PROPOSE on an active firm skill (`can_propose`): a new version that waits for approval.
|
||||
A proposer reads the current version and the versions they wrote themselves, nothing more
|
||||
(`readable_version_ids`); only an editor reads every version. A proposer's publish is always a
|
||||
request, and so is anybody's publish of a version a non-editor wrote (`publish_skill`).
|
||||
|
||||
Who decides a publish request (`may_approve`): an administrator, or somebody holding `approver` or
|
||||
better on the firm's workspace node of the org tree. The existing grant screen hands that out, so
|
||||
there is no second permission table. A role on a group or folder is not the firm's. An approver who
|
||||
is not an editor reads one more version than a proposer: the one sitting in a PENDING request,
|
||||
because they cannot decide on what they cannot read (`_readable_version`). Once decided, the
|
||||
request grants nothing.
|
||||
else makes a personal copy.
|
||||
|
||||
Versions are frozen
|
||||
-------------------
|
||||
Changing content is a new `skill_version` (`n + 1`), never an edit; the runtime role holds no
|
||||
UPDATE or DELETE on the version tables (revision 0015). Every version is validated the way an
|
||||
UPDATE or DELETE on the version tables (revision 0010). Every version is validated the way an
|
||||
import is — it is packed with `skill_pack.build_pack` and read back with `skill_pack.read_pack` — so
|
||||
a skill typed in the console and one uploaded as a ZIP obey the same rules and hash the same way.
|
||||
|
||||
`current_version_id` of a PERSONAL skill follows its newest version. A FIRM skill's is the approved
|
||||
one, and only publication moves it — a new version of a firm skill is readable only by its editors
|
||||
and its author until then.
|
||||
one, and only publication moves it — a new version of a firm skill stays invisible to everybody but
|
||||
its editors until then.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -50,8 +40,6 @@ from sqlalchemy.orm import Session as DbSession
|
||||
from ..enums import (
|
||||
AgentKind,
|
||||
CatalogStatus,
|
||||
NodeKind,
|
||||
NodeRole,
|
||||
PublishKind,
|
||||
PublishRequestStatus,
|
||||
SkillOrigin,
|
||||
@@ -63,13 +51,12 @@ from ..models import (
|
||||
AgentVersion,
|
||||
AgentVersionSkill,
|
||||
AppUser,
|
||||
Node,
|
||||
PublishRequest,
|
||||
Skill,
|
||||
SkillFile,
|
||||
SkillVersion,
|
||||
)
|
||||
from . import audit, authz, settings, skill_pack
|
||||
from . import audit, settings, skill_pack
|
||||
from .marketplace import _clean_note
|
||||
from .skill_pack import PackRejected, SkillContent
|
||||
|
||||
@@ -97,13 +84,6 @@ def can_edit(user: AppUser, item) -> bool:
|
||||
return item.owner_id == user.id or (item.scope == SkillScope.firm and bool(user.is_admin))
|
||||
|
||||
|
||||
def can_propose(user: AppUser, item) -> bool:
|
||||
"""Whoever may edit, and anybody for an active firm skill: a new version is a proposal there
|
||||
(`_add_version` never moves a firm skill's current version; only an approval does)."""
|
||||
return can_edit(user, item) or (item.scope == SkillScope.firm
|
||||
and item.status == CatalogStatus.active)
|
||||
|
||||
|
||||
def visible_to(db: DbSession, user: AppUser) -> list[Skill]:
|
||||
"""Every skill `user` may see — `can_see` as SQL. Archived ones included: an agent may still pin
|
||||
one, and the console says so."""
|
||||
@@ -127,34 +107,11 @@ def _get_editable(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
|
||||
return skill
|
||||
|
||||
|
||||
def _get_proposable(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
|
||||
skill = _get(db, user, skill_id)
|
||||
if not can_propose(user, skill):
|
||||
raise AuthorizationError("Only the owner or an administrator may change this skill.")
|
||||
return skill
|
||||
|
||||
|
||||
def may_approve(db: DbSession, user: AppUser) -> bool:
|
||||
"""May `user` decide publish requests? An administrator, or `approver`+ on any workspace node.
|
||||
The workspace is the firm (the root of the org tree), and a grant there reaches everything
|
||||
below; a grant on a group or folder does not make anyone the firm's approver. The role is
|
||||
resolved by `authz.effective_role` and compared by dredd-core's rank, never by its string."""
|
||||
if user.is_admin:
|
||||
return True
|
||||
needed = NodeRole.rank(NodeRole.approver)
|
||||
return any(NodeRole.rank(authz.effective_role(db, user, node)) >= needed
|
||||
for node in db.scalars(select(Node).where(Node.kind == NodeKind.workspace)))
|
||||
|
||||
|
||||
def readable_version_ids(user: AppUser, skill: Skill, versions) -> set[uuid.UUID]:
|
||||
"""The ids among `versions` this person may read. An editor reads every version. Anybody else
|
||||
reads the current one (for a firm skill: approved) and the versions they wrote themselves, so a
|
||||
proposer sees their own proposal but not other people's, nor the owner's earlier personal
|
||||
drafts of a skill that later became the firm's."""
|
||||
def readable_version_ids(user: AppUser, skill: Skill, version_ids) -> set[uuid.UUID]:
|
||||
"""An editor reads every version; anybody else only the current (for a firm skill: approved)."""
|
||||
if can_edit(user, skill):
|
||||
return {v.id for v in versions}
|
||||
return {v.id for v in versions
|
||||
if v.id == skill.current_version_id or v.created_by == user.id}
|
||||
return set(version_ids)
|
||||
return {skill.current_version_id} & set(version_ids)
|
||||
|
||||
|
||||
# ---- content -----------------------------------------------------------------------------------
|
||||
@@ -243,8 +200,7 @@ def skill_out(user: AppUser, skill: Skill) -> dict[str, Any]:
|
||||
return {"id": skill.id, "slug": skill.slug, "name": skill.name, "owner_id": skill.owner_id,
|
||||
"scope": skill.scope, "status": skill.status, "origin": skill.origin,
|
||||
"current_version_id": skill.current_version_id, "mine": skill.owner_id == user.id,
|
||||
"editable": can_edit(user, skill),
|
||||
"proposable": can_propose(user, skill)}
|
||||
"editable": can_edit(user, skill)}
|
||||
|
||||
|
||||
def version_out(version: SkillVersion, files: list[SkillFile]) -> dict[str, Any]:
|
||||
@@ -269,7 +225,7 @@ def get_skill(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> dict:
|
||||
skill = _get(db, user, skill_id)
|
||||
versions = list(db.scalars(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc())))
|
||||
readable = readable_version_ids(user, skill, versions)
|
||||
readable = readable_version_ids(user, skill, (v.id for v in versions))
|
||||
current = next((v for v in versions if v.id == skill.current_version_id), None)
|
||||
return {**skill_out(user, skill),
|
||||
"versions": [{"n": v.n, "id": v.id, "created_at": v.created_at,
|
||||
@@ -279,55 +235,14 @@ def get_skill(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> dict:
|
||||
if current is not None and current.id in readable else None)}
|
||||
|
||||
|
||||
def _pending_for_approver(db: DbSession, user: AppUser, version: SkillVersion) -> bool:
|
||||
"""A version waiting in a publish request is readable by whoever may decide that request."""
|
||||
return bool(db.scalar(select(PublishRequest.id).where(
|
||||
PublishRequest.kind == PublishKind.skill, PublishRequest.version_id == version.id,
|
||||
PublishRequest.status == PublishRequestStatus.pending))) and may_approve(db, user)
|
||||
|
||||
|
||||
def _readable_version(db: DbSession, user: AppUser, skill_id: uuid.UUID,
|
||||
n: int) -> tuple[Skill, SkillVersion]:
|
||||
"""The skill and its version `n`, if this person may read it; an unapproved firm version is a
|
||||
404 to others. The one exception to `can_see`: an approver reads a version in a pending request
|
||||
even of somebody's personal skill, because the request is what puts it in front of them."""
|
||||
skill = db.get(Skill, skill_id)
|
||||
if skill is None:
|
||||
raise NotFoundError("Skill not found.")
|
||||
def get_version(db: DbSession, user: AppUser, skill_id: uuid.UUID, n: int) -> dict:
|
||||
"""Version `n`, if this person may read it — an unapproved firm version is a 404 to others."""
|
||||
skill = _get(db, user, skill_id)
|
||||
version = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.n == n))
|
||||
if version is not None:
|
||||
if can_see(user, skill) and readable_version_ids(user, skill, [version]):
|
||||
return skill, version
|
||||
if _pending_for_approver(db, user, version):
|
||||
return skill, version
|
||||
# A personal skill nobody may see stays "Skill not found", as `_get` says.
|
||||
raise NotFoundError("Version not found." if can_see(user, skill) else "Skill not found.")
|
||||
|
||||
|
||||
def get_version(db: DbSession, user: AppUser, skill_id: uuid.UUID, n: int) -> dict:
|
||||
"""Version `n`, if this person may read it. `approved_for_firm` tells the checking service
|
||||
whether this is the version the firm approved: an editor or the author can read a proposal, and a
|
||||
check run against one must not pass as the firm's own. An archived skill has no approved version:
|
||||
archiving is the firm's kill switch, and the checking service reads this flag fresh on every
|
||||
real-contract order, so it stops there at once."""
|
||||
skill, version = _readable_version(db, user, skill_id, n)
|
||||
return {**version_out(version, _files(db, version.id)), "skill_name": skill.name,
|
||||
"approved_for_firm": (skill.scope == SkillScope.firm
|
||||
and skill.status == CatalogStatus.active
|
||||
and skill.current_version_id == version.id)}
|
||||
|
||||
|
||||
def get_file(db: DbSession, user: AppUser, skill_id: uuid.UUID, n: int,
|
||||
path: str) -> tuple[str, bytes]:
|
||||
"""(media_type, bytes) of one file of a readable version; the same read rule as `get_version`.
|
||||
A read, so no audit entry."""
|
||||
_, version = _readable_version(db, user, skill_id, n)
|
||||
stored = db.scalar(select(SkillFile).where(SkillFile.skill_version_id == version.id,
|
||||
SkillFile.path == path))
|
||||
if stored is None:
|
||||
raise NotFoundError("File not found.")
|
||||
return stored.media_type, stored.content
|
||||
if version is None or not readable_version_ids(user, skill, [version.id]):
|
||||
raise NotFoundError("Version not found.")
|
||||
return version_out(version, _files(db, version.id))
|
||||
|
||||
|
||||
# ---- writes ------------------------------------------------------------------------------------
|
||||
@@ -349,75 +264,29 @@ def create_skill(db: DbSession, actor: AppUser, fields: Mapping, *, ip: str | No
|
||||
return skill_out(actor, skill)
|
||||
|
||||
|
||||
def _base_version(db: DbSession, actor: AppUser, skill: Skill) -> SkillVersion:
|
||||
"""What an unset field is carried over from. NOT the newest version overall: that may be a
|
||||
stranger's proposal, which an editor's next save would then inherit unseen. The base is the
|
||||
actor's own newest version when it is newer than the current one (or nothing is current yet),
|
||||
else the current version, else the newest one the owner wrote."""
|
||||
mine = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.created_by == actor.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
current = (db.get(SkillVersion, skill.current_version_id)
|
||||
if skill.current_version_id is not None else None)
|
||||
if mine is not None and (current is None or mine.n > current.n):
|
||||
return mine
|
||||
if current is not None:
|
||||
return current
|
||||
owners = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.created_by == skill.owner_id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
if owners is None:
|
||||
# Every skill starts with its owner's version 1, so this is not expected; failing beats
|
||||
# falling back to the newest version overall, which may be a stranger's proposal.
|
||||
raise ConflictError("This skill has no version to build on.")
|
||||
return owners
|
||||
|
||||
|
||||
def _named_base(db: DbSession, actor: AppUser, skill: Skill, n: int) -> SkillVersion:
|
||||
"""Version `n` as the base, when the caller names the one it was looking at (the console's
|
||||
editor always does): an explicit choice, so Ruling 9's worry (inheriting a stranger's proposal
|
||||
unseen) does not apply. It must still be a version this person may read, with the same 404."""
|
||||
version = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.n == n))
|
||||
if version is None or not readable_version_ids(actor, skill, [version]):
|
||||
raise NotFoundError("Version not found.")
|
||||
return version
|
||||
|
||||
|
||||
def new_version(db: DbSession, actor: AppUser, skill_id: uuid.UUID, fields: Mapping, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Version `n + 1`. A field that is None is carried over from the base version: `base_n` when
|
||||
given (`_named_base`), else `_base_version` (the actor's own newer one, else the current one —
|
||||
never a stranger's proposal); `files`
|
||||
included — `{}` is how to remove them all). `file_updates` (path -> bytes) instead replaces or
|
||||
adds just those files and carries every other one over byte for byte, so a caller that holds
|
||||
one file need not hold the rest. An imported licence is the author's: it stays. On a firm skill
|
||||
this is a proposal: it waits for publication like any other new version."""
|
||||
skill = _get_proposable(db, actor, skill_id)
|
||||
"""Version `n + 1`. A field that is None is carried over from the newest version (`files`
|
||||
included — `{}` is how to remove them all). An imported licence is the author's: it stays."""
|
||||
skill = _get_editable(db, actor, skill_id)
|
||||
if skill.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived skill takes no new versions.")
|
||||
if fields.get("files") is not None and fields.get("file_updates") is not None:
|
||||
raise ValidationError("Send files or file_updates, not both.")
|
||||
latest = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
base = (_named_base(db, actor, skill, fields["base_n"]) if fields.get("base_n") is not None
|
||||
else _base_version(db, actor, skill))
|
||||
license = fields.get("license") or base.license
|
||||
license = fields.get("license") or latest.license
|
||||
if skill.origin == SkillOrigin.imported:
|
||||
license = base.license
|
||||
license = latest.license
|
||||
files = fields.get("files")
|
||||
if files is None:
|
||||
files = {f.path: f.content for f in _files(db, base.id)}
|
||||
files.update(fields.get("file_updates") or {})
|
||||
# The name sits on the identity row, outside versioning: a proposal must not rename a firm skill.
|
||||
if fields.get("name") and can_edit(actor, skill):
|
||||
files = {f.path: f.content for f in _files(db, latest.id)}
|
||||
if fields.get("name"):
|
||||
skill.name = fields["name"]
|
||||
version = _add_version(
|
||||
db, actor, skill, next_n(latest.n),
|
||||
description=fields.get("description") or base.description,
|
||||
body=fields["body"] if fields.get("body") is not None else base.body_md,
|
||||
description=fields.get("description") or latest.description,
|
||||
body=fields["body"] if fields.get("body") is not None else latest.body_md,
|
||||
license=license,
|
||||
meta=fields["metadata"] if fields.get("metadata") is not None else base.meta,
|
||||
meta=fields["metadata"] if fields.get("metadata") is not None else latest.meta,
|
||||
files=files)
|
||||
_audit(db, actor, "skill.version", skill, version, ip=ip)
|
||||
return version_out(version, _files(db, version.id))
|
||||
@@ -443,17 +312,15 @@ def _make_current(item, version) -> None:
|
||||
|
||||
|
||||
def _publish(db: DbSession, actor: AppUser, kind: PublishKind, item, version, *,
|
||||
ip: str | None, request_only: bool = False) -> dict:
|
||||
ip: str | None) -> dict:
|
||||
"""`approval` -> a request for THIS version (every version, not only the first); `direct` ->
|
||||
published now. The item stays where it was until an administrator says yes. `request_only`:
|
||||
a proposer who may not edit never publishes on their own, and neither does an editor publishing
|
||||
a version a non-editor wrote: both file a request, whatever the setting says."""
|
||||
published now. The item stays where it was until an administrator says yes."""
|
||||
if item.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived item cannot be published.")
|
||||
if item.scope == SkillScope.firm and item.current_version_id == version.id:
|
||||
raise ConflictError("This version is already published.")
|
||||
target = f"{getattr(item, 'slug', item.name)} v{version.n}"
|
||||
if not request_only and settings.get(db, "skills_firm_publish") == "direct":
|
||||
if settings.get(db, "skills_firm_publish") == "direct":
|
||||
_make_current(item, version)
|
||||
db.flush()
|
||||
# No request and nobody else's yes: the setting is the approval, the detail says so.
|
||||
@@ -463,7 +330,7 @@ def _publish(db: DbSession, actor: AppUser, kind: PublishKind, item, version, *,
|
||||
if db.scalar(select(PublishRequest.id).where(
|
||||
PublishRequest.kind == kind, PublishRequest.version_id == version.id,
|
||||
PublishRequest.status == PublishRequestStatus.pending)):
|
||||
raise ConflictError("This version is already waiting for an approver.")
|
||||
raise ConflictError("This version is already waiting for an administrator.")
|
||||
req = PublishRequest(kind=kind.value, version_id=version.id, requested_by=actor.id,
|
||||
status=PublishRequestStatus.pending.value)
|
||||
db.add(req)
|
||||
@@ -476,30 +343,22 @@ def _publish(db: DbSession, actor: AppUser, kind: PublishKind, item, version, *,
|
||||
def publish_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Publish version `n` (default: the newest) to the firm — by the owner, or for a firm skill
|
||||
also by an administrator. Without `n` it is the actor's OWN newest version, never a stranger's.
|
||||
It goes live directly (setting `direct`) only when the actor may edit AND so could the version's
|
||||
author; anything else — a proposer's publish, or an editor publishing a proposal — is a request."""
|
||||
skill = _get_proposable(db, actor, skill_id)
|
||||
also by an administrator."""
|
||||
skill = _get_editable(db, actor, skill_id)
|
||||
query = select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
query = (query.where(SkillVersion.n == n) if n is not None
|
||||
else query.where(SkillVersion.created_by == actor.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
else query.order_by(SkillVersion.n.desc()).limit(1))
|
||||
version = db.scalar(query)
|
||||
# A non-editor publishes only what they wrote; anything else is as unreadable (and as 404) to
|
||||
# them as a read of it would be, so no number can be probed and no draft lands in the queue.
|
||||
if version is None or (not can_edit(actor, skill) and version.created_by != actor.id):
|
||||
if version is None:
|
||||
raise NotFoundError("Version not found.")
|
||||
author = db.get(AppUser, version.created_by)
|
||||
request_only = not (can_edit(actor, skill) and author is not None and can_edit(author, skill))
|
||||
return {**_publish(db, actor, PublishKind.skill, skill, version, ip=ip,
|
||||
request_only=request_only),
|
||||
return {**_publish(db, actor, PublishKind.skill, skill, version, ip=ip),
|
||||
"skill": skill_out(actor, skill)}
|
||||
|
||||
|
||||
def _require_approver(db: DbSession, actor: AppUser) -> None:
|
||||
def _require_administrator(actor: AppUser) -> None:
|
||||
# The router guards too; this is what keeps someone's personal skill out of other hands.
|
||||
if not may_approve(db, actor):
|
||||
raise AuthorizationError("Only an approver decides publish requests.")
|
||||
if not actor.is_admin:
|
||||
raise AuthorizationError("Only an administrator decides publish requests.")
|
||||
|
||||
|
||||
def _resolve(db: DbSession, req: PublishRequest):
|
||||
@@ -518,11 +377,8 @@ def refuses_older(item, current_n: int | None, version) -> bool:
|
||||
|
||||
def decide_publish(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, approve: bool,
|
||||
note: str | None = None, ip: str | None = None) -> dict:
|
||||
"""An approver's yes or no. Yes moves the firm's current version to the requested one. An
|
||||
approver who is not an administrator never decides a request they filed, nor one for a version
|
||||
they wrote (an owner's publish of an approver's proposal is a request, Ruling 10): that is the
|
||||
second pair of eyes. An administrator may, as before."""
|
||||
_require_approver(db, actor)
|
||||
"""An administrator's yes or no. Yes moves the firm's current version to the requested one."""
|
||||
_require_administrator(actor)
|
||||
# Row lock: two administrators deciding the same request at once must not both "win".
|
||||
req = db.scalar(select(PublishRequest).where(PublishRequest.id == request_id)
|
||||
.with_for_update())
|
||||
@@ -530,12 +386,7 @@ def decide_publish(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, appr
|
||||
raise NotFoundError("Request not found.")
|
||||
if req.status != PublishRequestStatus.pending:
|
||||
raise ConflictError("This request has already been decided.")
|
||||
own = "You cannot decide your own request."
|
||||
if req.requested_by == actor.id and not actor.is_admin:
|
||||
raise AuthorizationError(own)
|
||||
item, version = _resolve(db, req)
|
||||
if version.created_by == actor.id and not actor.is_admin:
|
||||
raise AuthorizationError(own)
|
||||
if approve:
|
||||
if item.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived item cannot be published.")
|
||||
@@ -580,9 +431,9 @@ def _full_version(db: DbSession, kind: str, version) -> dict:
|
||||
|
||||
|
||||
def pending_publish_requests(db: DbSession, actor: AppUser) -> list[dict]:
|
||||
"""Every pending request, oldest first: the one place an approver sees somebody else's personal
|
||||
skill, and only the version put forward (which `_readable_version` lets them read as well)."""
|
||||
_require_approver(db, actor)
|
||||
"""Every pending request, oldest first — the one place an administrator sees somebody else's
|
||||
personal skill, and only the version put forward."""
|
||||
_require_administrator(actor)
|
||||
rows = db.scalars(select(PublishRequest).where(
|
||||
PublishRequest.status == PublishRequestStatus.pending).order_by(PublishRequest.created_at))
|
||||
return [_request_out(db, r) for r in rows]
|
||||
@@ -701,7 +552,7 @@ def export_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | No
|
||||
query = (query.where(SkillVersion.n == n) if n is not None
|
||||
else query.where(SkillVersion.id == skill.current_version_id))
|
||||
version = db.scalar(query)
|
||||
if version is None or not readable_version_ids(actor, skill, [version]):
|
||||
if version is None or not readable_version_ids(actor, skill, [version.id]):
|
||||
raise NotFoundError("Version not found.")
|
||||
data = skill_pack.build_pack([version_content(skill, version, _files(db, version.id))])
|
||||
audit.record(db, action="skill.export", entity_type="skill", entity_id=skill.id,
|
||||
@@ -726,7 +577,7 @@ def may_pin(user: AppUser, agent_scope: str, skill: Skill | None, version: Skill
|
||||
# ponytail: only the CURRENT published version — an older approved one is refused too;
|
||||
# remembering which versions were approved would lift that, if repinning annoys.
|
||||
return skill.scope == SkillScope.firm and version.id == skill.current_version_id
|
||||
return can_see(user, skill) and bool(readable_version_ids(user, skill, [version]))
|
||||
return can_see(user, skill) and bool(readable_version_ids(user, skill, [version.id]))
|
||||
|
||||
|
||||
def _check_pins(db: DbSession, user: AppUser, agent_scope: str, ids) -> list[SkillVersion]:
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
"""History and trends on the home page: aggregates over the platform's event log (`module_event`).
|
||||
|
||||
Current numbers still come from each module's own stats, which the console asks directly; history
|
||||
and trends come from the event log, which carries identifiers and numbers only - never a title, a
|
||||
name or a sentence (`dredd_core.events.check_payload`). Nothing here returns an id or a list of
|
||||
documents: events per day and kind, and how long documents took between two kinds of event.
|
||||
|
||||
**Where the log is.** Atrium is the hub: on the platform the log is its own (`dredd.module_event`,
|
||||
revision 0011), reached through the `search_path`. Standalone nobody writes events into this schema,
|
||||
so the charts say there is no log; nothing fails. A lightweight `table()` construct reads it, so this
|
||||
file adds nothing to the metadata.
|
||||
|
||||
Events are not filtered per person (the log has no notion of who may read the subject), so the route
|
||||
keeps these charts to platform administrators (`routers/marketplace.home_trends`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import statistics
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import DateTime, Text, column, func, literal_column, select, table, text
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
#: The platform's working day: a day on a chart is a day in Poland.
|
||||
ZONE = "Europe/Warsaw"
|
||||
#: The history the activity chart shows, today included.
|
||||
DAYS = 30
|
||||
#: How far back the durations look for the events that start a measurement.
|
||||
DURATION_YEARS = 2
|
||||
|
||||
_EVENT = table(
|
||||
"module_event",
|
||||
column("kind", Text),
|
||||
column("source_module", Text),
|
||||
column("payload", JSONB),
|
||||
column("created_at", DateTime(timezone=True)),
|
||||
)
|
||||
|
||||
#: The kinds the platform emits today (`dredd_core.events.FIRST_EVENTS`) in the console's words.
|
||||
#: A kind not listed is still counted, under its own code.
|
||||
KIND_LABELS: dict[str, str] = {
|
||||
"document.version_added": "Nowe wersje dokumentów",
|
||||
"workflow.approved": "Zatwierdzone obiegi",
|
||||
"document.signed": "Podpisane dokumenty",
|
||||
"negotiation.round_received": "Rundy negocjacji",
|
||||
"analysis.accepted": "Zaakceptowane analizy",
|
||||
}
|
||||
|
||||
#: The milestones a document passes, each the FIRST event of its kind naming that document
|
||||
#: (`payload.document_id`), in order. A new event kind adds a milestone here, not a table.
|
||||
MILESTONES: tuple[tuple[str, str], ...] = (
|
||||
("created", "document.version_added"),
|
||||
("approved", "workflow.approved"),
|
||||
("signed", "document.signed"),
|
||||
)
|
||||
#: The stages a duration spans: from the first milestone to the last.
|
||||
SEGMENTS = ("przygotowanie", "podpisanie")
|
||||
#: The distribution's bands in days, both ends included; `None` = no upper end.
|
||||
BANDS = ((0, 7), (8, 30), (31, 90), (91, None))
|
||||
|
||||
|
||||
def log_status(db: DbSession) -> str:
|
||||
"""`ok` when the event log is reachable and readable by this role, `absent` when this database
|
||||
has none (standalone), `no_grant` when it exists but this role may not read it. Catalog reads
|
||||
only, so a missing grant is a status rather than a failed statement."""
|
||||
row = db.execute(text(
|
||||
"SELECT to_regclass('module_event') IS NOT NULL AS present, "
|
||||
"CASE WHEN to_regclass('module_event') IS NULL THEN false "
|
||||
"ELSE has_table_privilege(to_regclass('module_event'), 'SELECT') END AS readable"
|
||||
)).one()
|
||||
if not row.present:
|
||||
return "absent"
|
||||
return "ok" if row.readable else "no_grant"
|
||||
|
||||
|
||||
def _day(column_):
|
||||
# The zone as a literal, not a bind parameter: each bind is its own placeholder, so the GROUP BY
|
||||
# expression would not be the select-list one and PostgreSQL refuses the query.
|
||||
return func.date(func.timezone(literal_column(f"'{ZONE}'"), column_))
|
||||
|
||||
|
||||
def activity(db: DbSession, status: str, *, today: dt.date | None = None) -> dict[str, Any]:
|
||||
"""Events per day and kind over the last DAYS days (today included, the oldest first), every
|
||||
day present with zeros, and the kinds ordered by their total."""
|
||||
if status != "ok":
|
||||
return {"status": status, "days": [], "kinds": [], "total": 0}
|
||||
today = today or dt.datetime.now(dt.timezone.utc).date()
|
||||
first = today - dt.timedelta(days=DAYS - 1)
|
||||
rows = db.execute(activity_statement(first, today)).all()
|
||||
per_day: dict[dt.date, dict[str, int]] = defaultdict(dict)
|
||||
totals: dict[str, int] = defaultdict(int)
|
||||
for when, kind, n in rows:
|
||||
per_day[when][kind] = n
|
||||
totals[kind] += n
|
||||
kinds = sorted(totals, key=lambda k: (-totals[k], k))
|
||||
return {
|
||||
"status": "ok",
|
||||
"days": [{"date": (first + dt.timedelta(days=i)).isoformat(),
|
||||
"counts": per_day.get(first + dt.timedelta(days=i), {})} for i in range(DAYS)],
|
||||
"kinds": [{"kind": k, "label": KIND_LABELS.get(k, k), "total": totals[k]} for k in kinds],
|
||||
"total": sum(totals.values()),
|
||||
}
|
||||
|
||||
|
||||
def activity_statement(first: dt.date, today: dt.date):
|
||||
day = _day(_EVENT.c.created_at)
|
||||
return (select(day.label("day"), _EVENT.c.kind, func.count().label("n"))
|
||||
.where(day >= first, day <= today)
|
||||
.group_by(day, _EVENT.c.kind))
|
||||
|
||||
|
||||
# -- durations ------------------------------------------------------------------
|
||||
|
||||
|
||||
def measure(m: dict[str, dt.date | None]) -> int | str:
|
||||
"""One document's days from its first milestone to its last, or why it has none: `missing` when
|
||||
an end is unknown, `order` when it ends before it starts. Pure."""
|
||||
start, end = m.get(MILESTONES[0][0]), m.get(MILESTONES[-1][0])
|
||||
if start is None or end is None:
|
||||
return "missing"
|
||||
if end < start:
|
||||
return "order"
|
||||
return (end - start).days
|
||||
|
||||
|
||||
def milestones_statement(since: dt.date):
|
||||
# `->>` with a literal key, for the GROUP BY reason `_day` gives.
|
||||
doc = _EVENT.c.payload.op("->>")(literal_column("'document_id'"))
|
||||
kinds = [kind for _, kind in MILESTONES]
|
||||
return (select(doc.label("doc"), _EVENT.c.kind, func.min(_day(_EVENT.c.created_at)).label("day"))
|
||||
.where(_EVENT.c.kind.in_(kinds), doc.isnot(None),
|
||||
_EVENT.c.created_at >= dt.datetime.combine(since, dt.time(), dt.timezone.utc))
|
||||
.group_by(doc, _EVENT.c.kind))
|
||||
|
||||
|
||||
def milestones(db: DbSession, *, today: dt.date | None = None) -> list[dict[str, dt.date | None]]:
|
||||
"""Each document's milestone days, from the first event of each milestone kind that names it.
|
||||
Only documents whose first milestone falls in the last DURATION_YEARS years are measured, and
|
||||
older events are never read."""
|
||||
today = today or dt.datetime.now(dt.timezone.utc).date()
|
||||
since = today - dt.timedelta(days=365 * DURATION_YEARS)
|
||||
by_doc: dict[str, dict[str, dt.date]] = defaultdict(dict)
|
||||
name_of = {kind: name for name, kind in MILESTONES}
|
||||
for document, kind, day in db.execute(milestones_statement(since)).all():
|
||||
by_doc[document][name_of[kind]] = day
|
||||
first = MILESTONES[0][0]
|
||||
return [m for m in by_doc.values() if m.get(first) and m[first] >= since]
|
||||
|
||||
|
||||
def durations(db: DbSession, status: str, *, today: dt.date | None = None) -> dict[str, Any]:
|
||||
"""How long documents took from their first version to signature: how many were measured, the
|
||||
median, the bands, and how many were left out and why. Aggregates only, no document is named."""
|
||||
measured, skipped = [], {"missing": 0, "order": 0}
|
||||
if status == "ok":
|
||||
for m in milestones(db, today=today):
|
||||
days = measure(m)
|
||||
if isinstance(days, str):
|
||||
skipped[days] += 1
|
||||
else:
|
||||
measured.append(days)
|
||||
return {"status": status, "segments": list(SEGMENTS), "measured": len(measured),
|
||||
"median_days": statistics.median(measured) if measured else None,
|
||||
"bands": [{"from": lo, "to": hi,
|
||||
"count": sum(lo <= d and (hi is None or d <= hi) for d in measured)}
|
||||
for lo, hi in BANDS],
|
||||
"skipped": skipped}
|
||||
|
||||
|
||||
def home(db: DbSession) -> dict[str, Any]:
|
||||
"""Both charts, with the log's status read once."""
|
||||
status = log_status(db)
|
||||
return {"activity": activity(db, status), "durations": durations(db, status)}
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
pytest==8.3.4
|
||||
pytest-cov==6.0.0
|
||||
pytest-xdist==3.8.0 # MIT — the deploy kit's tests over every core (ci.yml deploy-kit-tests)
|
||||
httpx==0.28.1 # the TestClient transport (the probe uses stdlib http.client)
|
||||
pip-licenses==5.0.0 # the license gate reads this
|
||||
ruff==0.8.4
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
# alembic revision for whatever tables or columns the bump brings (never edit 0001).
|
||||
#
|
||||
# The repo is PRIVATE, so pip needs credentials to fetch it:
|
||||
# local — a read-only Gitea access token in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the Haski org secret DREDD_CORE_TOKEN; see the workflow-level `env:` in .github/workflows/
|
||||
# local — a GitHub PAT in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the DREDD_CORE_TOKEN repo secret; see the auth step in .github/workflows/ci.yml
|
||||
#
|
||||
# v0.10.0 is what makes ONE ACCOUNT possible: the shared identity schema (`ModuleModerator`,
|
||||
# `SHARED_IDENTITY_TABLES`, `shared_identity_grants_sql`, `create_identity_tables`,
|
||||
@@ -56,7 +56,7 @@
|
||||
# v0.21.0 adds the counterparty register: the three shared tables the hub creates and grants in its
|
||||
# identity schema (`alembic/versions/0012_counterparties.py`, re-applied by `app.identity_grants`),
|
||||
# and the import door modules move their own counterparties in through. The hub holds no tier on them.
|
||||
dredd-core @ git+http://77.216.148.202:3000/Haski/dredd-core.git@v0.26.1
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.23.1
|
||||
|
||||
# Web framework
|
||||
fastapi==0.115.6
|
||||
@@ -92,3 +92,4 @@ opentelemetry-sdk==1.42.1
|
||||
opentelemetry-exporter-otlp-proto-grpc==1.42.1
|
||||
opentelemetry-instrumentation-fastapi==0.63b1
|
||||
opentelemetry-instrumentation-sqlalchemy==0.63b1
|
||||
pypdf==6.21.4 # text of a PDF attached to a chat question (BSD-3-Clause, pure Python)
|
||||
|
||||
@@ -120,8 +120,8 @@ check("USER app" in dockerfile, "container runs as root",
|
||||
|
||||
# ── the image can install the private core ────────────────────────────────────
|
||||
requirements = read("backend/requirements.txt")
|
||||
if "dredd-core @ git+" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names git in its URL rewrite, so that could never fail.
|
||||
if "git+https://github.com/Alpaq92/dredd-core" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names github.com, so that could never fail.
|
||||
# Look for git as a package of an apt/apk install (comments dropped, `\` continuations joined as
|
||||
# BuildKit joins them: whitespace may follow the backslash, and blank lines inside are skipped).
|
||||
run_text = re.sub(r"\\[ \t]*\n(?:[ \t]*\n)*", " ", re.sub(r"(?m)^\s*#.*\n", "", dockerfile))
|
||||
|
||||
@@ -173,7 +173,7 @@ test('module prefixes match only at a segment boundary', () => {
|
||||
test('a malformed module hash shows "not found" instead of throwing', async () => {
|
||||
const calls = [];
|
||||
const env = { state: { user: {}, stale: false }, location: { hash: '#/m/%zz/x' },
|
||||
closeWaffle() {}, refreshShared() {}, leavingDraft: () => false, showFrame: (...a) => calls.push(a) };
|
||||
closeWaffle() {}, refreshShared() {}, showFrame: (...a) => calls.push(a) };
|
||||
const router = new Function(...Object.keys(env), fnBody('async function router() {') + '\nreturn router;')(...Object.values(env));
|
||||
await router();
|
||||
assert.deepEqual(calls, [['', 'x']]);
|
||||
|
||||
@@ -1,198 +0,0 @@
|
||||
// Run by test_skills_console.py: `node trial_loop.mjs <app.js>`. It lifts the Próba tab's section out
|
||||
// of the console and drives `runVersionLoop` against a scripted `arbiter()`, so the rule "after a 504,
|
||||
// never a POST beside the step still running" is asserted by behaviour, not by grepping for strings.
|
||||
// Time is faked: `setTimeout` fires at once and `Date.now()` is a clock the script moves.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const SRC = readFileSync(process.argv[2], 'utf8');
|
||||
const START = "/* ── a skill version's trial and standards check (Próba) ──";
|
||||
const i = SRC.indexOf(START);
|
||||
assert.ok(i >= 0, 'the Próba section is not in app.js');
|
||||
const SECTION = SRC.slice(i, SRC.indexOf('/* ── import ──', i));
|
||||
|
||||
const http = (status, detail) => Object.assign(new Error(detail), { status, problem: { detail } });
|
||||
const trialState = (contracts, extra = {}) => ({
|
||||
version_n: 2, ran_at: 'r' + contracts, contracts, of: 15, complete: contracts === 15,
|
||||
rules: contracts * 4, agree: contracts * 4, differ: 0,
|
||||
results: Array.from({ length: contracts }, (_, k) => ({ contract: 'c' + k, status: 'answered' })),
|
||||
...extra,
|
||||
});
|
||||
const agentWith = (st) => ({ id: 'A', skill_trials: { AV: st } });
|
||||
|
||||
/* One run of the loop over `script`: a list of [expected call, reply]. A call off the script is
|
||||
recorded and refused, so the run ends with it in `calls` and in `t.runErr`. */
|
||||
async function run(script, { clock = { now: 0 }, onGet = () => {}, start = trialState(3) } = {}) {
|
||||
const calls = [];
|
||||
const t = { version: 'V1', loading: false, status: { trial: start }, err: null, running: null, stop: false, runErr: null };
|
||||
const state = { _skillView: { s: { id: 'S' }, shown: { id: 'V1', n: 2 } }, _trials: { V1: t }, _trial: t };
|
||||
const arbiter = async (method, path) => {
|
||||
const call = method + ' ' + path;
|
||||
calls.push(call);
|
||||
const next = script.shift();
|
||||
if (!next || next[0] !== call) throw new Error('unexpected call: ' + call);
|
||||
if (method === 'GET') { clock.now += 16 * 60 * 1000; onGet(t, calls, state); }
|
||||
if (next[1] instanceof Error) throw next[1];
|
||||
return next[1];
|
||||
};
|
||||
const env = {
|
||||
state, arbiter, enc: encodeURIComponent, _tr: (x) => x,
|
||||
renderSkillBody() {}, setTimeout: (fn) => fn(), Date: { now: () => clock.now },
|
||||
};
|
||||
const fns = new Function(...Object.keys(env), SECTION + '\nreturn { runVersionLoop };')(...Object.values(env));
|
||||
await fns.runVersionLoop('trial');
|
||||
return { calls, t, script };
|
||||
}
|
||||
|
||||
const SYNC = ['POST skills/S/versions/2/sync', { agent_id: 'A', agent_version_id: 'AV', n: 2, approved_for_firm: false }];
|
||||
const STEP = 'POST agents/A/trial?agent_version_id=AV';
|
||||
const READ = 'GET agents/A';
|
||||
|
||||
const tests = [];
|
||||
const test = (name, fn) => tests.push([name, fn]);
|
||||
|
||||
test('after a 504 the next step waits until a re-read shows the cut-off step landed', async () => {
|
||||
const { calls, t, script } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3))], // the cut-off step still running: nothing new yet
|
||||
[READ, agentWith(trialState(4))], // it landed
|
||||
[STEP, agentWith(trialState(15))],
|
||||
], { clock: { now: 0 } });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, READ, STEP]);
|
||||
assert.equal(script.length, 0);
|
||||
assert.equal(t.runErr, null, 'no error is shown');
|
||||
assert.equal(t.running, null);
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('a contract judged again (no new row, a new ran_at) counts as landed', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3, { ran_at: 'later' }))],
|
||||
[STEP, agentWith(trialState(15))],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, STEP]);
|
||||
assert.equal(t.runErr, null);
|
||||
});
|
||||
|
||||
test('"Zatrzymaj" during the wait still waits for the step, then posts nothing more', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3))],
|
||||
[READ, agentWith(trialState(4))],
|
||||
], { onGet: (tr, cs) => { if (cs.length === 3) tr.stop = true; } });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, READ]);
|
||||
assert.equal(t.runErr, null);
|
||||
assert.equal(t.running, null);
|
||||
assert.equal(t.status.trial.contracts, 4);
|
||||
});
|
||||
|
||||
test('a step that never lands is waited for at most the cap, then one POST shows the refusal', async () => {
|
||||
// Each read moves the clock 16 minutes; the cap is 125, so the eighth read is past it.
|
||||
const reads = Array.from({ length: 8 }, () => [READ, agentWith(trialState(3))]);
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, http(409, 'The model is busy with another step.')],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP]);
|
||||
assert.equal(t.runErr.status, 409);
|
||||
assert.equal(t.running, null);
|
||||
});
|
||||
|
||||
test('signing out during the wait ends the loop without another POST', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3))],
|
||||
], { onGet: (tr, cs, st) => { st._trials = {}; } }); // what showLogin() does
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ]);
|
||||
assert.equal(t.runErr, null);
|
||||
});
|
||||
|
||||
test('a retry that is cut off again and never lands stops with a message, not a third POST', async () => {
|
||||
// Each wait runs out the cap (8 reads of 16 minutes); a model server that never answers would
|
||||
// otherwise get a paid call every 125 minutes for ever.
|
||||
const reads = Array.from({ length: 8 }, () => [READ, agentWith(trialState(3))]);
|
||||
const running = [];
|
||||
const { calls, t, script } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads.map((r) => [...r]),
|
||||
], { onGet: (tr) => running.push(tr.running) });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP, ...reads.map((r) => r[0])]);
|
||||
assert.equal(script.length, 0);
|
||||
assert.ok(t.runErr && t.runErr.slow, 'the "taking too long" message is shown');
|
||||
assert.equal(t.runErr.message, 'Ten krok trwa zbyt długo. Sprawdź serwer modelu i spróbuj ponownie.');
|
||||
assert.ok(running.every((r) => r === 'trial'), 'the button stays disabled through both waits');
|
||||
assert.equal(t.running, null);
|
||||
});
|
||||
|
||||
test('a capped retry that lands carries on as usual', async () => {
|
||||
const reads = Array.from({ length: 8 }, () => [READ, agentWith(trialState(3))]);
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(4))],
|
||||
[STEP, agentWith(trialState(15))],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP, READ, STEP]);
|
||||
assert.equal(t.runErr, null);
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('a read that fails during the wait (502, network) keeps waiting, the button disabled', async () => {
|
||||
const running = [];
|
||||
const { calls, t, script } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, http(502, 'Bad Gateway')],
|
||||
[READ, new TypeError('Failed to fetch')],
|
||||
[READ, agentWith(trialState(3))],
|
||||
[READ, agentWith(trialState(4))],
|
||||
[STEP, agentWith(trialState(15))],
|
||||
], { clock: { now: 0 }, onGet: (tr) => running.push(tr.running) });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, READ, READ, READ, STEP]);
|
||||
assert.equal(script.length, 0);
|
||||
assert.equal(t.runErr, null, 'a failed read is not the run\'s error');
|
||||
assert.ok(running.every((r) => r === 'trial'));
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('reads that keep failing still end at the cap, then one POST', async () => {
|
||||
const reads = Array.from({ length: 8 }, () => [READ, http(502, 'Bad Gateway')]);
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, agentWith(trialState(15))],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP]);
|
||||
assert.equal(t.runErr, null);
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('a 4xx during the wait ends the run: the next POST would be refused just the same', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, http(401, 'Not authenticated.')],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ]);
|
||||
assert.equal(t.runErr.status, 401);
|
||||
assert.equal(t.running, null);
|
||||
});
|
||||
|
||||
let failed = 0;
|
||||
for (const [name, fn] of tests) {
|
||||
try { await fn(); console.log('ok ' + name); } catch (e) { failed++; console.log('FAIL ' + name + '\n' + e.stack); }
|
||||
}
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -1,88 +0,0 @@
|
||||
"""DB-free tests of the Archive's technical account (Atrium#53, step 4)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.config import get_settings
|
||||
from app.services import accounts, archive_reader, audit, moderation
|
||||
|
||||
|
||||
class _Db:
|
||||
def __init__(self, user=None):
|
||||
self.user, self.added = user, []
|
||||
|
||||
def get(self, model, key):
|
||||
return self.user
|
||||
|
||||
def add(self, row):
|
||||
self.added.append(row)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def platform(monkeypatch):
|
||||
grants, audited = [], []
|
||||
monkeypatch.setattr(type(get_settings()), "shares_identity", property(lambda s: True))
|
||||
monkeypatch.setattr(moderation, "module_roles", lambda db, uid: {"parafa": "user"})
|
||||
monkeypatch.setattr(moderation, "grant",
|
||||
lambda db, actor, **kw: grants.append(kw) or {})
|
||||
monkeypatch.setattr(audit, "record", lambda db, **kw: audited.append(kw))
|
||||
return grants, audited
|
||||
|
||||
|
||||
def test_creates_a_passwordless_account_under_the_fixed_id(platform):
|
||||
grants, audited = platform
|
||||
db = _Db()
|
||||
user = archive_reader.ensure(db)
|
||||
assert db.added == [user]
|
||||
assert user.id == get_settings().archive_reader_id and user.password_hash is None
|
||||
assert not user.is_admin
|
||||
assert audited[0]["action"] == "archive_reader.created"
|
||||
# Only the modules it does not hold yet, and only as `user`.
|
||||
assert sorted(g["module_slug"] for g in grants) == ["agora", "arbiter", "workflow"]
|
||||
assert {g["role"] for g in grants} == {moderation.USER}
|
||||
|
||||
|
||||
def test_idempotent_when_it_exists(platform, monkeypatch):
|
||||
grants, audited = platform
|
||||
monkeypatch.setattr(moderation, "module_roles",
|
||||
lambda db, uid: dict.fromkeys(archive_reader.MODULES, "user"))
|
||||
db = _Db(SimpleNamespace(id=get_settings().archive_reader_id, is_active=True))
|
||||
archive_reader.ensure(db)
|
||||
assert db.added == [] and grants == [] and audited == []
|
||||
|
||||
|
||||
def test_a_deactivated_account_gets_no_grants_back(platform):
|
||||
grants, _ = platform
|
||||
archive_reader.ensure(_Db(SimpleNamespace(id=get_settings().archive_reader_id,
|
||||
is_active=False)))
|
||||
assert grants == []
|
||||
|
||||
|
||||
def test_mint_is_read_only(platform, monkeypatch):
|
||||
seen = {}
|
||||
|
||||
def create(db, user, **kw):
|
||||
seen.update(kw)
|
||||
return SimpleNamespace(id="s", token_prefix="galena_pat_ab"), "galena_pat_secret"
|
||||
|
||||
monkeypatch.setattr(accounts, "create_module_token", create)
|
||||
user = SimpleNamespace(id=get_settings().archive_reader_id, is_active=True)
|
||||
monkeypatch.setattr(moderation, "module_roles",
|
||||
lambda db, uid: dict.fromkeys(archive_reader.MODULES, "user"))
|
||||
_row, raw = archive_reader.mint(_Db(user))
|
||||
assert raw == "galena_pat_secret"
|
||||
assert seen["scope"] == "read" and seen["module_slug"] == "galena"
|
||||
assert seen["idle_days"] == get_settings().app_token_max_idle_days
|
||||
|
||||
|
||||
def test_the_reconciliation_leaves_it_out():
|
||||
"""`_active_ids` excludes it, so `everyone` never admits it and no sweep revokes its grants."""
|
||||
import inspect
|
||||
|
||||
from app.services import marketplace
|
||||
assert "archive_reader_id" in inspect.getsource(marketplace._active_ids)
|
||||
@@ -0,0 +1,114 @@
|
||||
"""A file attached to a Home chat question: its text back, nothing stored, and the refusals by code."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import types
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
from fastapi import Request
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import deps
|
||||
from app.db import get_db
|
||||
from app.errors import ValidationError
|
||||
from app.services import attachments, audit
|
||||
|
||||
|
||||
def _pdf(*pages: str) -> bytes:
|
||||
"""A real PDF with one text line per page (Helvetica, WinAnsi), xref offsets computed."""
|
||||
objs = ["<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [" + " ".join(f"{4 + 2 * i} 0 R" for i in range(len(pages)))
|
||||
+ f"] /Count {len(pages)} >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"]
|
||||
for i, text in enumerate(pages):
|
||||
stream = f"BT /F1 12 Tf 72 720 Td ({text}) Tj ET" if text else ""
|
||||
objs.append(f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> "
|
||||
f"/Contents {5 + 2 * i} 0 R >>")
|
||||
objs.append(f"<< /Length {len(stream)} >>\nstream\n{stream}\nendstream")
|
||||
out, offsets = io.BytesIO(), []
|
||||
out.write(b"%PDF-1.4\n")
|
||||
for n, body in enumerate(objs, 1):
|
||||
offsets.append(out.tell())
|
||||
out.write(f"{n} 0 obj\n{body}\nendobj\n".encode("latin-1"))
|
||||
xref = out.tell()
|
||||
out.write(f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode())
|
||||
for o in offsets:
|
||||
out.write(f"{o:010d} 00000 n \n".encode())
|
||||
out.write(f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode())
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def _docx(xml: str) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w") as z:
|
||||
z.writestr("word/document.xml", xml)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
|
||||
|
||||
|
||||
def test_a_pdf_comes_back_page_by_page():
|
||||
out = attachments.extract("Umowa.PDF", _pdf("Okres wypowiedzenia 3 miesiace", "Kara umowna 10 procent"))
|
||||
assert out["kind"] == "pdf" and out["pages"] == 2
|
||||
assert "[strona 1]\nOkres wypowiedzenia 3 miesiace" in out["text"]
|
||||
assert "[strona 2]\nKara umowna 10 procent" in out["text"]
|
||||
|
||||
|
||||
def test_a_scan_is_refused_with_its_reason():
|
||||
with pytest.raises(ValidationError) as refused:
|
||||
attachments.extract("skan.pdf", _pdf("", ""))
|
||||
assert refused.value.extra["code"] == "attachment_no_text"
|
||||
|
||||
|
||||
def test_a_docx_keeps_its_paragraphs_tabs_and_breaks():
|
||||
xml = (f'<w:document {W}><w:body><w:p><w:r><w:t>§ 1. Strony</w:t></w:r></w:p>'
|
||||
'<w:p><w:r><w:t>Najemca</w:t><w:tab/><w:t>ABC</w:t><w:br/><w:t>sp. z o.o.</w:t></w:r></w:p></w:body></w:document>')
|
||||
out = attachments.extract("najem.docx", _docx(xml))
|
||||
assert out["kind"] == "docx" and out["text"] == "§ 1. Strony\nNajemca\tABC\nsp. z o.o."
|
||||
|
||||
|
||||
def test_a_docx_with_a_dtd_is_refused_before_parsing():
|
||||
bomb = f'<!DOCTYPE w [<!ENTITY a "aaaa">]><w:document {W}><w:body><w:p><w:r><w:t>&a;</w:t></w:r></w:p></w:body></w:document>'
|
||||
with pytest.raises(ValidationError) as refused:
|
||||
attachments.extract("bomba.docx", _docx(bomb))
|
||||
assert refused.value.extra["code"] == "attachment_unreadable"
|
||||
|
||||
|
||||
def test_plain_text_falls_back_to_windows_1250():
|
||||
assert attachments.extract("notatka.txt", "Zażółć gęślą jaźń".encode("cp1250"))["text"] == "Zażółć gęślą jaźń"
|
||||
assert attachments.extract("a.md", "# Tytuł".encode("utf-8"))["text"] == "# Tytuł"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("name", "data", "code"), [
|
||||
("obraz.png", b"\x89PNG\r\n", "attachment_type"),
|
||||
("udaje.pdf", b"PK\x03\x04 not a pdf", "attachment_type"), # the name says PDF, the bytes do not
|
||||
("binarny.txt", b"MZ\x00\x00", "attachment_type"),
|
||||
("pusty.txt", b" \n", "attachment_empty"),
|
||||
("duzy.txt", b"a" * (attachments.MAX_BYTES + 1), "attachment_too_large"),
|
||||
])
|
||||
def test_refusals_carry_a_code(name, data, code):
|
||||
with pytest.raises(ValidationError) as refused:
|
||||
attachments.extract(name, data)
|
||||
assert refused.value.extra["code"] == code and refused.value.extra["en"]
|
||||
|
||||
|
||||
def test_the_route_returns_the_text_and_audits_only_the_name(monkeypatch):
|
||||
from app.main import app
|
||||
audited = []
|
||||
monkeypatch.setattr(audit, "record", lambda *a, **k: audited.append(k))
|
||||
|
||||
def signed_in(request: Request):
|
||||
request.state.credential_id, request.state.credential_kind = uuid.uuid4(), "session"
|
||||
return types.SimpleNamespace(id=uuid.uuid4(), is_admin=False)
|
||||
|
||||
app.dependency_overrides[deps.get_current_user] = signed_in
|
||||
app.dependency_overrides[get_db] = lambda: types.SimpleNamespace(commit=lambda: None)
|
||||
try:
|
||||
r = TestClient(app).post("/api/v1/chat/attachments?name=tajne.txt", content="Treść poufna".encode())
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
assert r.status_code == 200 and r.json()["text"] == "Treść poufna"
|
||||
assert audited[0]["detail"] == "tajne.txt" and "Treść" not in repr(audited)
|
||||
@@ -1,89 +0,0 @@
|
||||
"""What a named contract says: `chatClauses` reads the contract's text from
|
||||
Galena and picks the paragraphs that share the question's words. Run under Node with the module
|
||||
calls stubbed; skipped where no `node`."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _between(start: str, end: str) -> str:
|
||||
i = SRC.index(start)
|
||||
return SRC[i:SRC.index(end, i)]
|
||||
|
||||
|
||||
BLOCK = "\n".join([
|
||||
_between("const chatStems = ", "\n") + "\n",
|
||||
_between("const reviewFiles = ", "const reviewWords"),
|
||||
_between("const CHAT_CLAUSE = ", "/* The panel beside the chat"),
|
||||
])
|
||||
C = {"id": "c1", "project_id": "p1", "number": "UM-2026-0017", "name": "Najem biura"}
|
||||
PARAS = ["§ 1. Przedmiotem umowy jest najem lokalu.",
|
||||
"§ 2. Czynsz płatny do 10. dnia miesiąca.",
|
||||
"§ 5. Za zwłokę najemca zapłaci karę umowną 0,5% czynszu dziennie.",
|
||||
"§ 6. Umowę można wypowiedzieć z trzymiesięcznym okresem wypowiedzenia."]
|
||||
|
||||
|
||||
def _run(question: str, files=("umowa.docx",), named=True) -> list:
|
||||
case = {"question": question, "named": [{"contract": C}] if named else [],
|
||||
"tree": {"entries": [{"type": "file", "path": f} for f in files]}, "paras": PARAS}
|
||||
script = f"""
|
||||
const CASE = {json.dumps(case)};
|
||||
const chat = {{}};
|
||||
const askerGet = async (slug, path) => path.includes('/tree') ? CASE.tree : {{ paragraphs: CASE.paras }};
|
||||
{BLOCK}
|
||||
chatClauses(CASE.question, CASE.named).then((out) => console.log(JSON.stringify(out)))
|
||||
.catch((e) => {{ console.error(e); process.exit(1); }});
|
||||
"""
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
|
||||
encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_content_question_gets_the_matching_paragraphs_in_document_order() -> None:
|
||||
out = _run("Jaka kara umowna za zwłokę jest w UM-2026-0017?")
|
||||
assert out and out[0]["key"] == "galena:zapis:c1:2"
|
||||
assert "karę umowną" in out[0]["text"] and "UM-2026-0017" in out[0]["text"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
@pytest.mark.parametrize("question, kw", [
|
||||
("Kiedy kończy się UM-2026-0017?", {}), # not about content
|
||||
("Jaka kara umowna w UM-2026-0017?", {"named": False}), # no contract named
|
||||
("Jaka kara umowna w UM-2026-0017?", {"files": ("a.docx", "b.pdf")}), # which file?
|
||||
])
|
||||
def test_otherwise_nothing_is_read(question, kw) -> None:
|
||||
assert _run(question, **kw) == []
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_follow_up_reuses_the_text_read_earlier_in_the_conversation() -> None:
|
||||
case = {"named": [{"contract": C}], "paras": PARAS,
|
||||
"tree": {"entries": [{"type": "file", "path": "umowa.docx"}]}}
|
||||
script = f"""
|
||||
const CASE = {json.dumps(case)};
|
||||
const chat = {{}};
|
||||
const reads = [];
|
||||
const askerGet = async (slug, path) => {{ reads.push(path); return path.includes('/tree') ? CASE.tree : {{ paragraphs: CASE.paras }}; }};
|
||||
{BLOCK}
|
||||
(async () => {{
|
||||
const a = await chatClauses('Jaka kara umowna w UM-2026-0017?', CASE.named);
|
||||
const b = await chatClauses('A jak wypowiedzieć UM-2026-0017?', CASE.named);
|
||||
console.log(JSON.stringify({{ reads: reads.length, a: a.length, b: b.length }}));
|
||||
}})().catch((e) => {{ console.error(e); process.exit(1); }});
|
||||
"""
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
|
||||
encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
out = json.loads(r.stdout)
|
||||
assert out["reads"] == 2 and out["a"] and out["b"]
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Home chat's attached file longer than the model's room: the passages that match the question, said out loud.
|
||||
|
||||
`chatFileSources` and its helpers are lifted out of `frontend/app.js` and run under Node, so the behaviour is asserted,
|
||||
not the source text. DB-free; skipped only where no `node` binary exists.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _fn(head: str) -> str:
|
||||
i = SRC.index(head)
|
||||
return SRC[i:SRC.index("\n}\n", i) + 3]
|
||||
|
||||
|
||||
def _line(head: str) -> str:
|
||||
i = SRC.index(head)
|
||||
return SRC[i:SRC.index(";\n", i) + 2]
|
||||
|
||||
|
||||
def _run(expr: str) -> object:
|
||||
script = "\n".join(["const state = {};", _fn("function chatFileBudget("), _line("const CHAT_FILE_STOP = "),
|
||||
_line("const CHAT_FILE_SYN = "), _line("const chatStem = "), _fn("function chatFilePassages("),
|
||||
_line("const chatPageRanges = "), _fn("function chatFileSources("), _line("const CHAT_FILE_NONE = "),
|
||||
f"console.log(JSON.stringify({expr}));"])
|
||||
# On stdin: a 60 kB contract on the command line is past Windows' limit (WinError 206).
|
||||
r = subprocess.run([NODE, "-"], input=script, capture_output=True, text=True, timeout=60, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
def _contract() -> dict:
|
||||
filler = "".join(f"{n}. Wykonawca wykona prace zgodnie z harmonogramem, z należytą starannością i wiedzą techniczną. " * 6
|
||||
+ "\n" for n in range(1, 9))
|
||||
pages = ["§ 1\nPrzedmiot umowy\n1. Przedmiotem umowy jest dostawa systemu kancelaryjnego.\n"]
|
||||
pages += [f"§ {p}\nRealizacja\n{filler}" for p in range(2, 40)]
|
||||
pages += ["§ 40\nKary umowne\n1. Za każdy dzień zwłoki Wykonawca zapłaci karę umowną 0,5% wynagrodzenia.\n"
|
||||
"2. Łączna wysokość kar nie przekroczy 20% wynagrodzenia.\n",
|
||||
"§ 41\nPostanowienia końcowe\n1. Spory rozstrzyga sąd właściwy dla siedziby Zamawiającego.\n"]
|
||||
text = "".join(f"[strona {i}]\n{p}\n" for i, p in enumerate(pages, 1))
|
||||
return {"name": "umowa.pdf", "pages": len(pages), "text": text}
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_long_file_gives_the_passages_the_question_asks_about() -> None:
|
||||
f = _contract()
|
||||
assert len(f["text"]) > 56920 # longer than a 32k model's room, or the test proves nothing
|
||||
court, penalty = _run(f"[{json.dumps(f)}].flatMap((f) => ['Który sąd rozstrzyga spory?', 'Ile wynosi kara za zwłokę?']"
|
||||
".map((q) => chatFileSources([f], 'm', q)[0]))")
|
||||
assert "sąd właściwy dla siedziby" in court["text"]
|
||||
assert "0,5% wynagrodzenia" in penalty["text"] and "nie przekroczy 20%" in penalty["text"]
|
||||
for s in (court, penalty):
|
||||
# The opening always goes in, the skipped text is marked, and the model is told it read a part.
|
||||
assert "Przedmiotem umowy jest dostawa" in s["text"] and "[…]" in s["text"]
|
||||
assert s["read"].startswith("fragmenty: strony 1") and s["read"].endswith(" z 41")
|
||||
assert "nie znalazłem jej w przeczytanych fragmentach" in s["text"]
|
||||
assert re.search(r"\b41\b", court["read"].split(" z ")[0])
|
||||
assert len(court["text"]) <= 56920 + 400
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_file_that_fits_is_read_whole_and_the_chip_names_no_pages_before_a_question() -> None:
|
||||
f = _contract()
|
||||
short = {**f, "text": f["text"][:5000]}
|
||||
whole, chip = _run(f"[chatFileSources([{json.dumps(short)}], 'm', 'Który sąd?')[0], chatFileSources([{json.dumps(f)}], 'm')[0]]")
|
||||
assert whole["read"] == "" and whole["text"] == short["text"]
|
||||
assert chip["read"].startswith("fragmenty pasujące do pytania, ok. ")
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_not_found_answers_the_models_gave_are_recognised() -> None:
|
||||
said = ["W dostarczonym tekście nie ma szczegółowych informacji na temat konkretnych kwot kar umownych.",
|
||||
"W dostarczonym fragmencie umowy nie ma bezpośrednich zapisów dotyczących ochrony danych osobowych.",
|
||||
"Na podstawie dostarczonego fragmentu umowy (strony 1–17) **nie ma informacji o łącznym limicie kar umownych**.",
|
||||
"Umowa nie reguluje odstąpienia."]
|
||||
answered = ["Spory rozstrzyga sąd właściwy dla siedziby Zamawiającego [1].",
|
||||
"Kara wynosi 0,5% wynagrodzenia za każdy dzień zwłoki [1]."]
|
||||
assert _run(f"{json.dumps(said + answered)}.map((t) => CHAT_FILE_NONE.test(t))") == [True] * 4 + [False] * 2
|
||||
@@ -1,159 +0,0 @@
|
||||
"""Contract review from the chat: `chatReview` decides by code what to order in
|
||||
Arbiter, or what to ask back. Lifted out of `frontend/app.js` and run under Node with the modules'
|
||||
APIs stubbed, so the behaviour is asserted, not the source text. DB-free; skipped where no `node`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
CSS = (ROOT / "frontend" / "app.css").read_text(encoding="utf-8")
|
||||
|
||||
BLOCK = SRC[SRC.index("const CHAT_REVIEW = "):SRC.index("/* The panel beside the chat")]
|
||||
|
||||
C1 = {"id": "c1", "project_id": "p1", "number": "UM-2026-0017", "name": "Najem biura"}
|
||||
C2 = {"id": "c2", "project_id": "p2", "number": "UM-2026-0018", "name": "Dostawa"}
|
||||
SKILL = {"id": "s1", "name": "Umowy najmu", "scope": "firm", "status": "published",
|
||||
"current_version_id": "v3"}
|
||||
|
||||
|
||||
def _run(case: dict) -> dict:
|
||||
"""One `chatReview` call; returns its [text, extra] and every call it made to Arbiter."""
|
||||
stubs = f"""
|
||||
const CASE = {json.dumps(case)};
|
||||
const calls = [];
|
||||
const askerGet = async (slug, path) => (CASE.trees || {{}})[path] ?? null;
|
||||
const api = async (method, path) => path === '/skills' ? CASE.skills : {{ versions: [{{ id: 'v3', n: 3 }}] }};
|
||||
const arbiter = async (method, path, body) => {{
|
||||
calls.push([method, path, body]);
|
||||
if (CASE.refuse) {{ const e = new Error('nope'); e.status = CASE.refuse; throw e; }}
|
||||
return path === 'subjects/document' ? {{ id: 'sub1' }} : {{ id: 'run1' }};
|
||||
}};
|
||||
let opened = null;
|
||||
const reviewOpen = (a) => {{ opened = a; }};
|
||||
"""
|
||||
named = [{"contract": c} for c in case.get("named", [])]
|
||||
prev = {"mentioned": [f"galena:umowa:{c['id']}" for c in case.get("prev", [])]}
|
||||
index = "{ byKey: new Map(" + json.dumps(
|
||||
[[f"galena:umowa:{c['id']}", {"contract": c}] for c in case.get("prev", [])]) + ") }"
|
||||
script = stubs + BLOCK + f"""
|
||||
chatReview({{ question: CASE.question, named: {json.dumps(named)}, prev: {json.dumps(prev)},
|
||||
index: {index}, en: false }})
|
||||
.then((out) => console.log(JSON.stringify({{ out, calls, opened }})))
|
||||
.catch((e) => {{ console.error(e); process.exit(1); }});
|
||||
"""
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
|
||||
encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
def _case(**kw) -> dict:
|
||||
base = {"question": "Sprawdź umowę UM-2026-0017", "skills": [SKILL], "named": [C1],
|
||||
"trees": {"projects/p1/tree?recursive=true": {"entries": [
|
||||
{"type": "dir", "path": "podpisane"},
|
||||
{"type": "file", "path": "podpisane/skan.pdf"},
|
||||
{"type": "file", "path": ".galena/meta"},
|
||||
{"type": "file", "path": "umowa.docx"}]}}}
|
||||
base.update(kw)
|
||||
return base
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_named_contract_is_ordered_by_the_only_skill_and_the_panel_opens() -> None:
|
||||
r = _run(_case())
|
||||
text, extra = r["out"]
|
||||
assert r["calls"] == [
|
||||
["POST", "subjects/document", {"document_id": "p1", "path": "umowa.docx",
|
||||
"title": "UM-2026-0017 Najem biura"}],
|
||||
["POST", "analyses", {"subject_id": "sub1", "mode": "agent", "skill_id": "s1", "skill_n": 3}]]
|
||||
assert extra["analysis"] == {"id": "run1", "number": "UM-2026-0017", "name": "Najem biura",
|
||||
"skill": "Umowy najmu", "n": 3}
|
||||
assert r["opened"] == extra["analysis"]
|
||||
assert "UM-2026-0017" in text and "umowa.docx" in text and "zaakceptować" in text
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_contract_of_the_last_answer_is_this_one() -> None:
|
||||
r = _run(_case(question="Sprawdź tę umowę", named=[], prev=[C1]))
|
||||
assert r["out"][1]["analysis"]["number"] == "UM-2026-0017"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
@pytest.mark.parametrize("kw, words", [
|
||||
({"named": [C1, C2]}, "Którą umowę"),
|
||||
({"named": []}, "Którą umowę"),
|
||||
({"trees": {}}, "nie ma w Galenie pliku"),
|
||||
({"trees": {"projects/p1/tree?recursive=true": [{"type": "file", "path": "a.docx"},
|
||||
{"type": "file", "path": "b.pdf"}]}}, "2 plików"),
|
||||
({"skills": []}, "Nie ma jeszcze opublikowanego skilla"),
|
||||
({"skills": [SKILL, {**SKILL, "id": "s2", "name": "Umowy dostawy"}]}, "Według którego skilla"),
|
||||
])
|
||||
def test_anything_missing_is_asked_back_and_nothing_is_ordered(kw, words) -> None:
|
||||
r = _run(_case(**kw))
|
||||
assert words in r["out"][0]
|
||||
assert r["calls"] == [] and r["opened"] is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_skill_named_in_the_question_is_the_one() -> None:
|
||||
other = {**SKILL, "id": "s2", "name": "Umowy dostawy"}
|
||||
r = _run(_case(question="Sprawdź umowę UM-2026-0017 skillem dostawy", skills=[SKILL, other]))
|
||||
assert r["calls"][1][2]["skill_id"] == "s2"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_refused_order_is_a_sentence_not_a_throw() -> None:
|
||||
r = _run(_case(refuse=422))
|
||||
text, extra = r["out"]
|
||||
assert text.startswith("Arbiter nie przyjął zlecenia") and extra["failed"] is True
|
||||
assert r["opened"] is None
|
||||
|
||||
|
||||
def test_the_trigger_wants_a_verb_and_a_contract() -> None:
|
||||
pattern = re.search(r"const CHAT_REVIEW = /(.*)/iu;", SRC).group(1)
|
||||
assert "sprawdź" in pattern and "umow" in pattern
|
||||
# The route also wants a register contract (named, or "tę umowę"): a law question stays the law's.
|
||||
assert "named.some((r) => r && r.contract) || chatAnaphora(question).demonstrative" in SRC
|
||||
|
||||
|
||||
def test_the_report_is_framed_with_no_rights_and_the_panel_never_transitions_visibility() -> None:
|
||||
assert 'class="rp-report" sandbox=""' in SRC
|
||||
assert "/acceptance'" in SRC
|
||||
panel = CSS[CSS.index(".review-panel {"):]
|
||||
assert "transition: transform" in panel and "transition: visibility" not in panel
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_no_access_is_arbiters_answer_not_the_catalogues() -> None:
|
||||
"""A service module is missing from `/marketplace` for a non-administrator: the catalogue says
|
||||
nothing about access, so the order is tried and Arbiter's 403 is the refusal."""
|
||||
r = _run(_case(refuse=403))
|
||||
assert "nie masz do niego dostępu" in r["out"][0] and r["opened"] is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_only_a_verb_taking_the_contract_as_its_object_is_an_order() -> None:
|
||||
line = SRC[SRC.index("const CHAT_REVIEW = "):SRC.index("\n", SRC.index("const CHAT_REVIEW = "))]
|
||||
asks = ["Sprawdź umowę UM-2026-0017", "przeanalizuj tę umowę", "Check the contract UM-2026-0017",
|
||||
"Sprawdź, kiedy kończy się umowa UM-2026-0017", "Sprawdź czy umowa UM-2026-0017 ma kontrahenta",
|
||||
"Kiedy kończy się umowa UM-2026-0017?"]
|
||||
script = line + f"\nconsole.log(JSON.stringify({json.dumps(asks)}.map((q) => CHAT_REVIEW.test(q))));"
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert json.loads(r.stdout) == [True, True, True, False, False, False]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_personal_skill_is_never_ordered() -> None:
|
||||
"""A personal skill's current version follows its newest, unapproved one: only firm skills judge."""
|
||||
r = _run(_case(skills=[{**SKILL, "scope": "personal"}]))
|
||||
assert "Nie ma jeszcze opublikowanego skilla" in r["out"][0] and r["calls"] == []
|
||||
@@ -1,120 +0,0 @@
|
||||
"""Scribe and Lexicon lost their consoles (Atrium#53): the chat reads their templates, drafts,
|
||||
sources and library, and creates a draft in Scribe by code. Lifted out of `frontend/app.js` and run
|
||||
under Node with the modules' APIs stubbed. DB-free; skipped where no `node`."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _between(start: str, end: str) -> str:
|
||||
i = SRC.index(start)
|
||||
return SRC[i:SRC.index(end, i)]
|
||||
|
||||
|
||||
BLOCK = "\n".join([
|
||||
_between("const chatStems = ", "\n") + "\n",
|
||||
_between("const reviewWords = ", "\n") + "\n",
|
||||
_between("const CHAT_CLAUSE_TOP = ", "async function chatClauses"),
|
||||
_between("const chatWho = ", "// The calendar week"),
|
||||
_between("/* Scribe and Lexicon have no console", "// What Insider's resolve takes"),
|
||||
])
|
||||
TPL = [{"id": "t1", "name": "Najem lokalu", "description": "Umowa najmu", "field_count": 3, "slot_count": 1},
|
||||
{"id": "t2", "name": "Dostawa towaru", "description": None, "field_count": 2, "slot_count": 0}]
|
||||
DRAFTS = [{"id": "d1", "title": "Najem Kraków", "template_id": "t1", "template_name": "Najem lokalu",
|
||||
"from_scratch": False, "status": "draft", "owner_id": "u1", "created_at": "2026-11-20T10:00:00"}]
|
||||
SOURCES = [{"id": "s1", "title": "Wzór NDA", "kind": "file", "name": "nda.docx", "shared": True,
|
||||
"note": None, "library": {"count": 7}}]
|
||||
|
||||
|
||||
def _run(call: str, case: dict) -> dict:
|
||||
script = f"""
|
||||
const CASE = {json.dumps(case)};
|
||||
const gets = [], posts = [];
|
||||
const askerGet = async (slug, path) => {{ gets.push(slug + ':' + path); return (CASE.gets || {{}})[slug + ':' + path] ?? null; }};
|
||||
const jsonOf = (t) => JSON.parse(t);
|
||||
const httpError = (r, d) => Object.assign(new Error('HTTP ' + r.status), {{ status: r.status, problem: d }});
|
||||
const document = {{ baseURI: 'http://x/atrium/' }};
|
||||
const fetch = async (url, opt) => {{ posts.push([String(url), opt.method, JSON.parse(opt.body)]);
|
||||
const st = CASE.refuse || 201; return {{ ok: st < 300, status: st, text: async () => JSON.stringify({{ id: 'd9', title: JSON.parse(opt.body).title, detail: 'nie' }}) }}; }};
|
||||
{BLOCK}
|
||||
({call}).then((out) => console.log(JSON.stringify({{ out, gets, posts }})))
|
||||
.catch((e) => {{ console.error(e); process.exit(1); }});
|
||||
"""
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
|
||||
encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
GETS = {"scribe:templates": TPL, "scribe:drafts": DRAFTS, "lexicon:sources?status=active": SOURCES,
|
||||
"lexicon:library/shelves": [{"type": "poufnosc", "label": "Poufność", "count": 4},
|
||||
{"type": None, "label": None, "count": 0}]}
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_scribe_templates_and_drafts_become_records() -> None:
|
||||
out = _run("chatScribe({ u1: 'Anna Nowak' })", {"gets": GETS})["out"]
|
||||
keys = [r["key"] for r in out]
|
||||
assert keys == ["scribe:szablon:t1", "scribe:szablon:t2", "scribe:szkic:d1"]
|
||||
assert "Najem lokalu" in out[2]["text"] and "Anna Nowak" in out[2]["text"]
|
||||
assert out[2]["members"] == ["scribe:szablon:t1"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
@pytest.mark.parametrize("call", ["chatScribe({})", "chatLexicon()"])
|
||||
def test_no_access_is_null(call) -> None:
|
||||
assert _run(call, {"gets": {}})["out"] is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_lexicon_sources_and_shelves() -> None:
|
||||
out = _run("chatLexicon()", {"gets": GETS})["out"]
|
||||
assert out[0]["key"] == "lexicon:zrodlo:s1" and "7" in out[0]["text"]
|
||||
assert out[1]["key"] == "lexicon:polki" and "Poufność 4" in out[1]["text"]
|
||||
assert "bez typu" not in out[1]["text"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_library_clauses_are_searched_only_for_a_library_question() -> None:
|
||||
path = "lexicon:library/clauses?q=poufn"
|
||||
hit = [{"source_id": "s1", "source_title": "Wzór NDA", "position": 2, "label": "§ 3",
|
||||
"numbering": "§ 3", "text": "Strony zachowają poufność.", "types": ["poufnosc"]}]
|
||||
got = _run("chatLibrary('Jaką klauzulę poufności mamy w bibliotece?')", {"gets": {path: hit}})
|
||||
assert got["gets"] == [path]
|
||||
assert got["out"][0]["key"] == "lexicon:klauzula:s1:2" and "poufność" in got["out"][0]["text"]
|
||||
assert _run("chatLibrary('Jaka kara umowna w UM-1?')", {"gets": {}})["out"] == []
|
||||
|
||||
|
||||
def _index() -> str:
|
||||
return "{ records: " + json.dumps([{"kind": "szablon", "key": "scribe:szablon:" + t["id"],
|
||||
"template": t} for t in TPL]) + " }"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_draft_is_created_from_the_one_named_template() -> None:
|
||||
got = _run(f"chatDraft({{ question: 'Utwórz projekt pisma z szablonu najem „Najem Gdańsk”', index: {_index()}, en: false }})", {})
|
||||
assert got["posts"] == [["http://x/scribe/api/v1/drafts", "POST", {"template_id": "t1", "title": "Najem Gdańsk"}]]
|
||||
assert got["out"][1]["mentioned"] == ["scribe:szkic:d9"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_from_scratch_and_unclear_template() -> None:
|
||||
got = _run(f"chatDraft({{ question: 'Załóż szkic od zera', index: {_index()}, en: false }})", {})
|
||||
assert got["posts"][0][2] == {"template_id": None, "title": ""}
|
||||
asked = _run(f"chatDraft({{ question: 'Utwórz szkic', index: {_index()}, en: false }})", {})
|
||||
assert asked["posts"] == [] and asked["out"][1]["coded"] == "ask"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_refusal_is_a_sentence() -> None:
|
||||
got = _run(f"chatDraft({{ question: 'Załóż szkic od zera', index: {_index()}, en: false }})", {"refuse": 404})
|
||||
assert "nie masz do niego dostępu" in got["out"][0]
|
||||
@@ -230,16 +230,6 @@ def test_p7_a_second_of_one_is_asked_and_a_bare_citation_is_no_reference() -> No
|
||||
assert got["mentioned"] == []
|
||||
|
||||
|
||||
def test_p7_an_english_follow_up_is_asked_back_in_english() -> None:
|
||||
# The questions back are said by code; asked in English they were Polish (i18n pass, 20.11).
|
||||
got = _run("""const s = session([(b) => `W ciągu 30 dni kończy się jedna umowa: UM-2026-0006 Ochrona obiektu [${nOf(b, 'okno 30 dni')}].`]);
|
||||
await s.ask('Które umowy wygasają w ciągu 30 dni?');
|
||||
const a = await s.ask('the second contract?');
|
||||
return { coded: a.coded, content: a.content };""")
|
||||
assert got["coded"] == "ask", got
|
||||
assert got["content"].startswith("The previous answer had only one item") and "UM-2026-0006" in got["content"], got
|
||||
|
||||
|
||||
def test_p8_a_broken_stream_is_retried_and_the_code_table_is_marked() -> None:
|
||||
# A connection cut before the first word ended the turn as a failure (2 turns, 9.11); "przed 2026-11-12" on
|
||||
# that very day read as too late; the harness could not tell a turn with code's table from a plain one.
|
||||
@@ -357,3 +347,37 @@ def test_review_today_is_exempt_only_as_a_frame_and_en_refs_have_no_polish() ->
|
||||
return { framed: bad('Stan na 2026-11-12: najpilniejsza jest Apelacja [1].'), wrong: bad('Apelacja ma termin 2026-11-12 [1].'), row };""")
|
||||
assert got["framed"] == [] and "2026-11-12" in got["wrong"]
|
||||
assert got["row"][5] == "contract UM-2026-0006, counterparty not entered"
|
||||
|
||||
|
||||
def test_a_file_read_in_part_gets_codes_warning_under_a_not_found_answer() -> None:
|
||||
# 45 numbered pages, the court on the last one: past a 32k model's room from the beginning.
|
||||
got = _run("""const NL = String.fromCharCode(10); const page = (n) => `[strona ${n}]${NL}§ ${n}${NL}Realizacja${NL}` + '1. Wykonawca wykona prace z należytą starannością. '.repeat(60) + NL;
|
||||
const long = { name: 'umowa.pdf', pages: 45, text: [...Array(45).keys()].map((i) => page(i + 1)).join('') };
|
||||
const short = { name: 'krotka.pdf', pages: 1, text: '[strona 1]' + NL + '§ 1' + NL + 'Umowa najmu lokalu.' + NL };
|
||||
const run = async (files, reply) => { const s = session([reply]);
|
||||
const a = await s.ask('Który sąd rozstrzyga spory?', { files });
|
||||
return { content: a.content, failed: !!a.failed, partial: !!a.filePartial, sent: lastUser(s.asked[0]) }; };
|
||||
return { part: await run([long], 'W dostarczonym tekście nie ma informacji o sądzie właściwym.'),
|
||||
whole: await run([short], 'Umowa nie reguluje właściwości sądu.'),
|
||||
cited: await run([long], 'Spory rozstrzyga sąd właściwy dla siedziby Zamawiającego [1].'),
|
||||
// A question that reads like one about the law goes to the file, not to Insider's topic search.
|
||||
law: await (async () => { const s = session(['Kara wynosi 0,5% [1].']);
|
||||
const a = await s.ask('Jakie są kary umowne za zwłokę wykonawcy?', { files: [long] });
|
||||
return { coded: a.coded || null, sent: s.asked.length ? lastUser(s.asked[0]) : '' }; })(),
|
||||
// The models' own wording (czat-pliki, 18.11): the file cited by its paragraph, the point as "ust.".
|
||||
para: await (async () => { const s = session(['Zgodnie z § 10 ust. 11 łączny limit kar wynosi 25% wynagrodzenia [10].']);
|
||||
const kary = '[strona 1]' + NL + '§ 10' + NL + 'Kary umowne' + NL + '11. Łączna wysokość kar umownych nie przekroczy 25% wynagrodzenia.' + NL;
|
||||
const a = await s.ask('Jaki jest łączny limit kar umownych?', { files: [{ name: 'u.pdf', pages: 1, text: kary }] });
|
||||
return { content: a.content, failed: !!a.failed, retried: a.retried || null,
|
||||
wrongPoint: s.f.chatVerify('Limit jest w § 10 ust. 12 [1].', [{ text: kary }]).issues.filter((x) => x.level === 'bad').map((x) => x.raw) }; })() };""")
|
||||
# Uncited, yet accepted: "the file says nothing about it" is an answer, and code adds that the file was read in part.
|
||||
assert not got["part"]["failed"] and got["part"]["partial"], got["part"]
|
||||
assert "Uwaga: plik „umowa.pdf” jest za długi" in got["part"]["content"] and "z 45" in got["part"]["content"]
|
||||
assert "[…]" in got["part"]["sent"] and "wybrane po słowach pytania" in got["part"]["sent"]
|
||||
# A file read whole needs no warning; an answer that cites the file gets none either.
|
||||
assert not got["whole"]["failed"] and not got["whole"]["partial"] and "Uwaga" not in got["whole"]["content"], got["whole"]
|
||||
assert not got["cited"]["partial"] and "Uwaga" not in got["cited"]["content"], got["cited"]
|
||||
assert got["law"]["coded"] != "topic" and "(załącznik, plik)" in got["law"]["sent"], got["law"]
|
||||
# A right answer citing the file as "[10]" and its point as "§ 10 ust. 11" is kept, its mark put on the file.
|
||||
assert not got["para"]["failed"] and not got["para"]["retried"] and got["para"]["content"].endswith("[1]."), got["para"]
|
||||
assert got["para"]["wrongPoint"] == ["§ 10 ust. 12"], got["para"]
|
||||
|
||||
@@ -149,13 +149,6 @@ class TestAFreshInitIsOneAccount:
|
||||
for app in ("galena", "sygna", "counsel"):
|
||||
assert "MODEL_PROVIDER_SECRET" not in _values(fresh / "env" / f"{app}.env"), app
|
||||
|
||||
def test_arbiter_reads_skills_from_the_hubs_public_address(self, fresh):
|
||||
"""A skill version is read through Atrium's API (the same hairpin as Galena's): the example's
|
||||
`<site>` placeholder must never reach a fresh env file."""
|
||||
arbiter = _values(fresh / "env" / "arbiter.env")
|
||||
assert arbiter["ATRIUM_BASE_URL"] == arbiter["GALENA_BASE_URL"].removesuffix("/galena") + "/atrium"
|
||||
assert "<site>" not in arbiter["ATRIUM_BASE_URL"]
|
||||
|
||||
def test_one_first_administrator_for_the_platform(self, fresh):
|
||||
"""The modules' seeds look the hub's account up by this address, so all five must agree."""
|
||||
emails = {app: _values(fresh / "env" / f"{app}.migrate.env")["BOOTSTRAP_ADMIN_EMAIL"] for app in FAMILY}
|
||||
@@ -168,12 +161,6 @@ class TestAFreshInitIsOneAccount:
|
||||
hub = _values(tmp_path / "env" / "atrium.env")
|
||||
assert hub["IDENTITY_READER_ROLES"] == "t1_galena_app,t1_sygna_app,t1_counsel_app"
|
||||
assert hub["IDENTITY_MIGRATOR_ROLES"] == "t1_galena_migrator,t1_sygna_migrator,t1_counsel_migrator"
|
||||
# Galena trusts the event senders by their REAL role names too, or it refuses every event.
|
||||
galena = _values(tmp_path / "env" / "galena.env")
|
||||
assert (galena["WORKFLOW_EVENT_ROLES"], galena["SIGNING_EVENT_ROLES"],
|
||||
galena["NEGOTIATION_EVENT_ROLES"], galena["ANALYSIS_EVENT_ROLES"]) == (
|
||||
"t1_workflow_app", "t1_parafa_app", "t1_agora_app", "t1_arbiter_app")
|
||||
assert _values(tmp_path / "env" / "agora.env")["WORKFLOW_EVENT_ROLES"] == "t1_workflow_app"
|
||||
|
||||
def test_standalone_is_the_whole_opt_out_at_once(self, tmp_path):
|
||||
"""Never half: the push refuses every half-done combination, so the opt-out writes all of it.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""deploy/push.sh checks Lexicon and Agora (the split plan's M2-M3) with exactly the lists each
|
||||
"""deploy/push.sh checks Lexicon, Agora and Panorama (the split plan's M2-M4) with exactly the lists each
|
||||
declares, and with the platform tier each is granted.
|
||||
|
||||
Each module's evidence lists are `app.models.APPEND_ONLY_TABLES` / `NO_DELETE_TABLES`, which its 0002
|
||||
@@ -6,8 +6,8 @@ grants from and its CI's managed check passes, so push.sh's CHECK_EXTRA is compa
|
||||
the submodule is checked out: an evidence table a module adds later must not deploy unchecked.
|
||||
|
||||
The tiers: Lexicon calls the models (a model-provider KEY reader), Agora writes the event log (an
|
||||
EMITTER). The hub's template and init.sh list each in exactly its own tier. Panorama (M4), the one
|
||||
module of the READER tier, left the platform: the tier stays, and nothing is listed in it.
|
||||
EMITTER), Panorama reads it and writes nothing (dredd-core 0.23.0's READER tier). The hub's template
|
||||
and init.sh list each in exactly its own tier.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -20,7 +20,7 @@ ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
PUSH = ROOT / "deploy" / "push.sh"
|
||||
INIT = ROOT / "deploy" / "init.sh"
|
||||
ATRIUM_ENV = ROOT / "deploy" / "env" / "atrium.env.example"
|
||||
MODULES = ("lexicon", "agora")
|
||||
MODULES = ("lexicon", "agora", "panorama")
|
||||
|
||||
|
||||
def _tuple(src: str, name: str) -> list[str]:
|
||||
@@ -57,8 +57,8 @@ def test_push_checks_each_module_with_its_own_lists(slug):
|
||||
def test_each_module_is_checked_in_its_own_tier():
|
||||
push = PUSH.read_text(encoding="utf-8")
|
||||
assert 'case $slug in lexicon) IDENTITY_CHECK_ARGS="$IDENTITY_CHECK_ARGS --model-provider-keys" ;; esac' in push
|
||||
assert "case $slug in galena|agora|parafa|workflow|arbiter)" in push
|
||||
assert "case $slug in panorama)" not in push and "--events-reader\" ;;" not in push
|
||||
assert "case $slug in galena|agora|parafa)" in push
|
||||
assert 'case $slug in panorama) IDENTITY_CHECK_ARGS="$IDENTITY_CHECK_ARGS --events-reader" ;; esac' in push
|
||||
|
||||
|
||||
def test_the_hub_template_lists_each_in_exactly_its_tier():
|
||||
@@ -66,13 +66,14 @@ def test_the_hub_template_lists_each_in_exactly_its_tier():
|
||||
_list("MODULE_EVENT_READER_ROLES"))
|
||||
assert "lexicon_app" in keys and "lexicon_migrator" not in _list("MODEL_PROVIDER_MIGRATOR_ROLES")
|
||||
assert "agora_app" in emitters and "agora_app" not in readers
|
||||
assert readers == [] and "panorama_app" not in emitters
|
||||
assert readers == ["panorama_app"] and "panorama_app" not in emitters
|
||||
assert _list("MODEL_PROVIDER_MIGRATOR_ROLES") == ["arbiter_migrator"]
|
||||
|
||||
|
||||
def test_init_add_puts_each_module_in_its_tier():
|
||||
init = INIT.read_text(encoding="utf-8")
|
||||
assert "case $ADD in galena|agora|parafa|workflow|arbiter)" in init
|
||||
assert "case $ADD in galena|agora|parafa)" in init
|
||||
assert 'add_to_list "$OUT/env/atrium.env" MODULE_EVENT_READER_ROLES "$ROLE_PREFIX${ADD}_app"' in init
|
||||
assert '"env/atrium.env:MODULE_EVENT_READER_ROLES"' in init
|
||||
|
||||
|
||||
|
||||
@@ -66,8 +66,8 @@ def test_the_evidence_lists_as_shipped():
|
||||
|
||||
def test_parafa_is_an_emitter_and_scribe_is_in_no_tier():
|
||||
push, init = PUSH.read_text(encoding="utf-8"), INIT.read_text(encoding="utf-8")
|
||||
assert "case $slug in galena|agora|parafa|workflow|arbiter)" in push
|
||||
assert "case $ADD in galena|agora|parafa|workflow|arbiter)" in init
|
||||
assert "case $slug in galena|agora|parafa)" in push
|
||||
assert "case $ADD in galena|agora|parafa)" in init
|
||||
assert "parafa_app" in _list("MODULE_EVENT_EMITTER_ROLES")
|
||||
assert "parafa_app" not in _list("MODULE_EVENT_READER_ROLES")
|
||||
for key in OPT_INS:
|
||||
|
||||
@@ -41,7 +41,7 @@ PUSH = DEPLOY / "push.sh"
|
||||
PREFLIGHT = DEPLOY / "preflight.sh"
|
||||
ENVFILE_LIB = DEPLOY / "lib" / "envfile.sh"
|
||||
FAMILY = ("atrium", "galena", "sygna", "counsel", "insider", "arbiter", "lexicon", "agora",
|
||||
"parafa", "scribe", "workflow")
|
||||
"panorama", "parafa", "scribe")
|
||||
#: Where an app's tree sits inside its checkout — push.sh's SUBDIR and preflight.sh's. Arbiter's
|
||||
#: repository also carries the analysis engine and holds the application in a subdirectory; every other
|
||||
#: app's repository is the application. The fixture has to lay the scratch tree out the same way, or
|
||||
@@ -144,7 +144,7 @@ def rig(tmp_path_factory):
|
||||
base_env = f"MODULES_DIR={root / 'modules'}\nDEPLOY_ENV_DIR={root / 'env'}\n"
|
||||
# The rig is a box with every module deployed, the switched-off ones included, so the tests above mean
|
||||
# "all of them" without each having to say so. .env.off is the same box before either was switched on.
|
||||
_write(root / ".env", base_env + "COMPOSE_PROFILES=insider,arbiter,lexicon,agora,parafa,scribe,workflow\n")
|
||||
_write(root / ".env", base_env + "COMPOSE_PROFILES=insider,arbiter,lexicon,agora,panorama,parafa,scribe\n")
|
||||
_write(root / ".env.off", base_env)
|
||||
# Records the command line and succeeds, so the push walks all five steps without a database.
|
||||
_write(root / "recorder.sh", '#!/usr/bin/env bash\nprintf \'%s\\n\' "$*" >> "$PUSH_TRACE"\nexit 0\n')
|
||||
@@ -160,16 +160,15 @@ HUB_ON_THE_PLATFORM = {
|
||||
"IDENTITY_READER_ROLES": ",".join(f"{app}_app" for app in FAMILY[1:]),
|
||||
"IDENTITY_MIGRATOR_ROLES": ",".join(f"{app}_migrator" for app in FAMILY[1:]),
|
||||
# The modules taking part in the shared event log (dredd-core 0.20.0), init.sh's default.
|
||||
"MODULE_EVENT_EMITTER_ROLES": "galena_app,agora_app,parafa_app,workflow_app,arbiter_app",
|
||||
# The event log's reader tier (dredd-core 0.23.0; empty since Panorama left) and the key readers.
|
||||
"MODULE_EVENT_READER_ROLES": "",
|
||||
"MODULE_EVENT_EMITTER_ROLES": "galena_app,agora_app,parafa_app",
|
||||
# The event log's reader tier (dredd-core 0.23.0) and the model-provider key readers.
|
||||
"MODULE_EVENT_READER_ROLES": "panorama_app",
|
||||
"MODEL_PROVIDER_KEY_READER_ROLES": "arbiter_app,lexicon_app",
|
||||
# The shared counterparty register (dredd-core 0.21.0), init.sh's default: Sygna writes and its
|
||||
# migrator moves its own rows in through the hub's import door; Galena writes too, Agora and
|
||||
# Parafa read, and every one's migrator holds REFERENCES (spec 2026-11-25 part A).
|
||||
"COUNTERPARTY_WRITER_ROLES": "sygna_app,galena_app",
|
||||
"COUNTERPARTY_READER_ROLES": "agora_app,parafa_app",
|
||||
"COUNTERPARTY_MIGRATOR_ROLES": "sygna_migrator,galena_migrator,agora_migrator,parafa_migrator",
|
||||
# migrator moves its own rows in through the hub's import door; nobody reads since Workflow left.
|
||||
"COUNTERPARTY_WRITER_ROLES": "sygna_app",
|
||||
"COUNTERPARTY_READER_ROLES": "",
|
||||
"COUNTERPARTY_MIGRATOR_ROLES": "sygna_migrator",
|
||||
}
|
||||
|
||||
|
||||
@@ -331,8 +330,7 @@ class TestTheHalfDoneShapesOfOneAccountAreRefused:
|
||||
"""Sygna (on dredd-core 0.21.0+) moves its counterparties into the shared register: a hub
|
||||
that lists neither tier for it, or not its migrator, is refused up front."""
|
||||
done, trace = _push(rig, platform=True, trace="no-counterparties", settings={"atrium": {
|
||||
"COUNTERPARTY_WRITER_ROLES": "galena_app",
|
||||
"COUNTERPARTY_MIGRATOR_ROLES": "galena_migrator,agora_migrator,parafa_migrator"}})
|
||||
"COUNTERPARTY_WRITER_ROLES": None, "COUNTERPARTY_MIGRATOR_ROLES": None}})
|
||||
assert done.returncode == 2, done.stdout + done.stderr
|
||||
assert ("lists sygna_app in neither COUNTERPARTY_WRITER_ROLES nor "
|
||||
"COUNTERPARTY_READER_ROLES") in done.stderr
|
||||
@@ -341,10 +339,7 @@ class TestTheHalfDoneShapesOfOneAccountAreRefused:
|
||||
|
||||
def test_each_module_is_checked_with_the_counterparty_tier_the_hub_grants_it(self, rig):
|
||||
done, trace = _push(rig, platform=True, trace="cp-tiers", settings={"atrium": {
|
||||
# Galena, Agora and Parafa point foreign keys at the register (CP_NEEDED), so the hub has to
|
||||
# list all three; Galena as a reader here, to prove the check follows the listed tier.
|
||||
"COUNTERPARTY_WRITER_ROLES": "sygna_app",
|
||||
"COUNTERPARTY_READER_ROLES": "galena_app,agora_app,parafa_app"}})
|
||||
"COUNTERPARTY_READER_ROLES": "galena_app"}})
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
checks = {app: [line for line in trace.splitlines()
|
||||
if "managed check" in line and f"--app-role {app}_app" in line]
|
||||
@@ -359,12 +354,11 @@ class TestTheHalfDoneShapesOfOneAccountAreRefused:
|
||||
"""A module held on an older dredd-core (here Sygna on 0.18.1): its `managed check` has no
|
||||
--counterparties flag, and its revisions move nothing, so the preflight asks nothing of it."""
|
||||
reqs = rig / "modules" / "sygna" / "backend" / "requirements.txt"
|
||||
reqs.write_text("dredd-core @ git+http://77.216.148.202:3000/Haski/dredd-core.git@v0.18.1\n",
|
||||
reqs.write_text("dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.18.1\n",
|
||||
encoding="utf-8")
|
||||
try:
|
||||
done, trace = _push(rig, platform=True, trace="cp-old", settings={"atrium": {
|
||||
"COUNTERPARTY_WRITER_ROLES": "galena_app",
|
||||
"COUNTERPARTY_MIGRATOR_ROLES": "galena_migrator,agora_migrator,parafa_migrator"}})
|
||||
"COUNTERPARTY_WRITER_ROLES": None, "COUNTERPARTY_MIGRATOR_ROLES": None}})
|
||||
finally:
|
||||
reqs.unlink()
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
@@ -377,8 +371,7 @@ class TestTheHalfDoneShapesOfOneAccountAreRefused:
|
||||
and must not be a refusal here."""
|
||||
done, _ = _push(rig, platform=True, trace="spaces", settings={"atrium": {
|
||||
"IDENTITY_READER_ROLES": "galena_app, sygna_app, counsel_app, insider_app, arbiter_app, "
|
||||
"lexicon_app, agora_app, parafa_app, scribe_app, "
|
||||
"workflow_app"}})
|
||||
"lexicon_app, agora_app, panorama_app, parafa_app, scribe_app"}})
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
|
||||
@pytest.mark.parametrize("cookie, shown", [("galena_session", "galena_session"),
|
||||
@@ -669,7 +662,7 @@ class TestEveryAppIsProvisionedBeforeAnyMigrates:
|
||||
def test_the_budget_counts_a_module_only_when_it_runs(self, rig):
|
||||
on, _ = _push(rig, "--dry-run", platform=False, trace="budget-on")
|
||||
off, _ = _push(rig, "--dry-run", platform=False, trace="budget-off", compose_env=".env.off")
|
||||
assert re.search(r"budget\s+11 apps x", on.stdout), on.stdout # Panorama left
|
||||
assert re.search(r"budget\s+11 apps x", on.stdout), on.stdout
|
||||
assert re.search(r"budget\s+4 apps x", off.stdout), off.stdout
|
||||
|
||||
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
"""deploy/push.sh checks Workflow with exactly the lists it declares, and with the platform tier it is granted.
|
||||
|
||||
Its evidence lists are `app.models.APPEND_ONLY_TABLES` / `NO_DELETE_TABLES`, which its revisions grant
|
||||
from, so push.sh's CHECK_EXTRA is compared with them wherever the submodule is checked out (skipped
|
||||
where it is not).
|
||||
|
||||
The tier: every step of a run writes the event log (dredd_core.workflow_contract), so Workflow is an
|
||||
EMITTER, like Agora and Parafa; it calls no model and keeps no counterparties.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
|
||||
from test_deploy_m6_m7_check_args import OPT_INS, _check_extra, _list, _tuple
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
SHIPPED = ("--append-only audit_log module_event module_event_receipt workflow_event "
|
||||
"--no-delete workflow_run request workflow_template request_type approver_group")
|
||||
|
||||
|
||||
def test_push_checks_workflow_with_its_own_lists():
|
||||
models = ROOT / "deploy" / "modules" / "workflow" / "backend" / "app" / "models" / "__init__.py"
|
||||
if not models.exists():
|
||||
pytest.skip("deploy/modules/workflow is not checked out")
|
||||
src = models.read_text(encoding="utf-8")
|
||||
expected = (f"--append-only {' '.join(_tuple(src, 'APPEND_ONLY_TABLES'))} "
|
||||
f"--no-delete {' '.join(_tuple(src, 'NO_DELETE_TABLES'))}")
|
||||
assert _check_extra("workflow") == expected
|
||||
|
||||
|
||||
def test_the_evidence_lists_as_shipped():
|
||||
"""Without the submodule (CI), at least the lists Workflow shipped with at its first pin."""
|
||||
assert _check_extra("workflow") == SHIPPED
|
||||
|
||||
|
||||
def test_workflow_is_an_emitter_and_in_no_other_tier():
|
||||
assert "workflow_app" in _list("MODULE_EVENT_EMITTER_ROLES")
|
||||
for key in OPT_INS:
|
||||
if key != "MODULE_EVENT_EMITTER_ROLES":
|
||||
assert not any(r.startswith("workflow_") for r in _list(key)), key
|
||||
|
||||
|
||||
def test_workflow_is_offered_to_an_instance_seeded_before_it():
|
||||
from app import frontdoor
|
||||
from app.seed import ADDED_AFTER_FIRST_SEED, FAMILY
|
||||
|
||||
entry = next(e for e in FAMILY if e["slug"] == "workflow")
|
||||
assert "workflow" in ADDED_AFTER_FIRST_SEED and "workflow" in frontdoor.MODULES
|
||||
assert (entry["hue"], entry["glyph"]) == ("gray", "clock")
|
||||
@@ -1,69 +0,0 @@
|
||||
"""Trends on Atrium's home. DB-free: the pure parts, the compiled SQL, and the guard."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import types
|
||||
import uuid
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
from app import deps
|
||||
from app.db import get_db
|
||||
from app.services import trends
|
||||
|
||||
D = dt.date(2026, 11, 1)
|
||||
|
||||
|
||||
def _sql(stmt) -> str:
|
||||
return str(stmt.compile(dialect=postgresql.dialect()))
|
||||
|
||||
|
||||
def test_a_document_is_measured_from_its_first_version_to_its_signature():
|
||||
m = {"created": D, "approved": D + dt.timedelta(days=3), "signed": D + dt.timedelta(days=10)}
|
||||
assert trends.measure(m) == 10
|
||||
|
||||
|
||||
def test_a_document_without_a_milestone_or_out_of_order_is_left_out():
|
||||
assert trends.measure({"created": D, "approved": D, "signed": None}) == "missing"
|
||||
assert trends.measure({"created": None, "approved": D, "signed": D}) == "missing"
|
||||
assert trends.measure({"created": D, "signed": D - dt.timedelta(days=1)}) == "order"
|
||||
|
||||
|
||||
def test_the_new_kinds_have_labels():
|
||||
assert {"analysis.accepted", "negotiation.round_received"} <= set(trends.KIND_LABELS)
|
||||
|
||||
|
||||
def test_the_activity_groups_by_the_very_day_expression_it_selects():
|
||||
sql = _sql(trends.activity_statement(D - dt.timedelta(days=29), D))
|
||||
day = "date(timezone('Europe/Warsaw', module_event.created_at))"
|
||||
select_part, group_part = sql.split("GROUP BY")
|
||||
assert select_part.startswith(f"SELECT {day} AS day")
|
||||
assert group_part.strip().startswith(day)
|
||||
assert group_part.count(day) == 1
|
||||
|
||||
|
||||
def test_milestones_read_only_the_recent_events():
|
||||
sql = _sql(trends.milestones_statement(D))
|
||||
where = sql.split("WHERE")[1].split("GROUP BY")[0]
|
||||
assert "module_event.created_at >= %(created_at_1)s" in where
|
||||
|
||||
|
||||
def test_without_a_log_nothing_is_read():
|
||||
db = types.SimpleNamespace(execute=lambda *a, **k: (_ for _ in ()).throw(AssertionError))
|
||||
assert trends.activity(db, "absent")["days"] == []
|
||||
assert trends.durations(db, "no_grant")["measured"] == 0
|
||||
|
||||
|
||||
def test_trends_are_refused_to_a_non_administrator():
|
||||
from app.main import app
|
||||
|
||||
person = types.SimpleNamespace(id=uuid.uuid4(), is_admin=False, is_active=True)
|
||||
app.dependency_overrides[deps.get_current_user] = lambda: person
|
||||
app.dependency_overrides[get_db] = lambda: types.SimpleNamespace(
|
||||
execute=lambda *a, **k: (_ for _ in ()).throw(AssertionError("no query for a refusal")))
|
||||
try:
|
||||
r = TestClient(app).get("/api/v1/home/trends")
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
assert r.status_code == 403, r.text
|
||||
@@ -313,29 +313,28 @@ class TestEventEmitters:
|
||||
assert tiers == {"emitters": ["atrium_app"], "readers": [], "pending": []}
|
||||
|
||||
def test_the_reader_tier_once_joined(self):
|
||||
"""dredd-core 0.23.0: MODULE_EVENT_READER_ROLES is SELECT only, joined like an
|
||||
emitter, and never added to the emitters. No module uses it since Panorama
|
||||
left the platform, so the role here is a stand-in."""
|
||||
"""dredd-core 0.23.0: MODULE_EVENT_READER_ROLES (Panorama) is SELECT only, joined like an
|
||||
emitter, and never added to the emitters."""
|
||||
tiers = identity_grants.event_emitters(_platform(
|
||||
identity_reader_roles="galena_app,agora_app,reporter_app",
|
||||
identity_reader_roles="galena_app,agora_app,panorama_app",
|
||||
module_event_emitter_roles="galena_app,agora_app",
|
||||
module_event_reader_roles="reporter_app, lexicon_app"))
|
||||
module_event_reader_roles="panorama_app, lexicon_app"))
|
||||
assert tiers == {"emitters": ["atrium_app", "galena_app", "agora_app"],
|
||||
"readers": ["reporter_app"], "pending": ["lexicon_app"]}
|
||||
"readers": ["panorama_app"], "pending": ["lexicon_app"]}
|
||||
|
||||
def test_the_readers_reach_the_grant_block(self, monkeypatch):
|
||||
monkeypatch.setattr(identity_grants, "event_table_exists", lambda conn, s: True)
|
||||
sql = identity_grants.event_statements(_platform(
|
||||
identity_reader_roles="reporter_app", module_event_reader_roles="reporter_app"),
|
||||
identity_reader_roles="panorama_app", module_event_reader_roles="panorama_app"),
|
||||
"atrium_migrator", object())
|
||||
assert len(sql) == 2 and "reporter_app" in sql[1]
|
||||
assert len(sql) == 2 and "panorama_app" in sql[1]
|
||||
|
||||
def test_a_role_in_both_tiers_is_refused(self, monkeypatch):
|
||||
monkeypatch.setattr(identity_grants, "event_table_exists", lambda conn, s: True)
|
||||
with pytest.raises(identity_grants.GrantsRefused, match="MODULE_EVENT_READER_ROLES"):
|
||||
identity_grants.event_statements(_platform(
|
||||
identity_reader_roles="reporter_app", module_event_emitter_roles="reporter_app",
|
||||
module_event_reader_roles="reporter_app"), "atrium_migrator", object())
|
||||
identity_reader_roles="panorama_app", module_event_emitter_roles="panorama_app",
|
||||
module_event_reader_roles="panorama_app"), "atrium_migrator", object())
|
||||
|
||||
def test_standalone_renders_nothing(self):
|
||||
assert identity_grants.event_statements(_settings(), "atrium_migrator", None) == []
|
||||
|
||||
@@ -390,31 +390,6 @@ class TestTheTwoTiers:
|
||||
out = UserOut(id="x", email="a@b.test", full_name="A", is_admin=False, is_active=True)
|
||||
assert out.modules == {} # always a mapping, never absent
|
||||
|
||||
def test_only_an_administrator_is_told_who_holds_which_tier(self):
|
||||
"""`GET /users` answers any credential, a read-only app token included, and the tiers are
|
||||
the map of whose account is worth taking over. Everybody else gets a row with no tier in
|
||||
it at all: absent, never `false` or empty, which would be a lie about an administrator."""
|
||||
from pydantic import TypeAdapter
|
||||
|
||||
from app.schemas import UserBriefOut, UserOut
|
||||
|
||||
assert set(UserBriefOut.model_fields) == {"id", "email", "full_name", "is_active"}
|
||||
# The route's own response type, fed what the handler returns for somebody who is not an
|
||||
# administrator: nothing in the reply may put a tier back.
|
||||
reply = TypeAdapter(list[UserOut] | list[UserBriefOut])
|
||||
brief = UserBriefOut(id="x", email="a@b.test", full_name="A", is_active=True)
|
||||
assert reply.dump_python(reply.validate_python([brief])) == [
|
||||
{"id": "x", "email": "a@b.test", "full_name": "A", "is_active": True}]
|
||||
full = UserOut(id="x", email="a@b.test", full_name="A", is_admin=True, is_active=True,
|
||||
modules={"galena": "moderator"})
|
||||
assert reply.dump_python(reply.validate_python([full]))[0]["modules"] == {
|
||||
"galena": "moderator"}
|
||||
|
||||
source = (BACKEND / "app" / "routers" / "users.py").read_text(encoding="utf-8")
|
||||
body = source.split("def list_users", 1)[1].split("@router.post", 1)[0]
|
||||
assert "response_model=list[UserOut] | list[UserBriefOut]" in source
|
||||
assert body.index("if not user.is_admin") < body.index("module_roles_by_user")
|
||||
|
||||
def test_a_new_account_gets_no_tier_and_no_module_by_default(self):
|
||||
"""The default is an account that can sign in and open nothing. Before `module_permission`
|
||||
there was no way to express that: everybody could open everything."""
|
||||
@@ -503,20 +478,6 @@ class TestTheLastAdministratorGuard:
|
||||
body = source.split("def count_administrators", 1)[1].split("def _assert", 1)[0]
|
||||
assert "is_active.is_(True)" in body
|
||||
|
||||
def test_the_count_is_taken_under_a_lock_on_the_administrators(self):
|
||||
"""A check followed by a write, with nothing in between, is passed by two requests at once:
|
||||
"demote A" and "demote B" each count the other and both go through. So the guard locks the
|
||||
administrators' rows first and counts after — FOR NO KEY UPDATE (a plain FOR UPDATE would
|
||||
make every foreign-key insert that names an administrator wait), in a fixed order."""
|
||||
source = (BACKEND / "app" / "services" / "accounts.py").read_text(encoding="utf-8")
|
||||
lock = source.split("def _lock_administrators", 1)[1].split("def _assert", 1)[0]
|
||||
assert "with_for_update(key_share=True)" in lock
|
||||
assert "order_by(AppUser.id)" in lock
|
||||
assert "is_admin.is_(True)" in lock and "is_active.is_(True)" in lock
|
||||
guard = source.split("def _assert_not_last_administrator", 1)[1].split(
|
||||
"def set_administrator", 1)[0]
|
||||
assert guard.index("_lock_administrators(db)") < guard.index("count_administrators(db")
|
||||
|
||||
def test_the_routers_do_not_reimplement_it(self):
|
||||
"""Layering: routers never build SQL, and a second copy of a guard is a guard that will
|
||||
disagree with the first one."""
|
||||
|
||||
@@ -98,23 +98,6 @@ def test_admin_endpoints_refuse_ordinary_users(client, make_user):
|
||||
assert r.status_code == 403, (path, r.status_code)
|
||||
|
||||
|
||||
def test_the_user_list_tells_only_an_administrator_who_holds_which_tier(admin_client, client,
|
||||
make_user):
|
||||
"""Anybody signed in may list people (a picker needs names). Who is an administrator and who
|
||||
may open which module is told to an administrator only: for everybody else those fields are
|
||||
absent, on every row, their own and the administrators' included."""
|
||||
alice = make_user("brief")
|
||||
rows = client.get("/api/v1/users", headers=bearer(alice["token"]))
|
||||
assert rows.status_code == 200, rows.text
|
||||
assert rows.json() and all(set(row) == {"id", "email", "full_name", "is_active"}
|
||||
for row in rows.json())
|
||||
assert any(row["id"] == alice["id"] for row in rows.json())
|
||||
|
||||
full = admin_client.get("/api/v1/users").json()
|
||||
assert all({"is_admin", "modules"} <= set(row) for row in full)
|
||||
assert any(row["is_admin"] for row in full)
|
||||
|
||||
|
||||
# ── people: the way back in ───────────────────────────────────────────────────
|
||||
# A forgotten password had no answer on this platform: `POST /me/password` needs the password that
|
||||
# is missing, a module's own reset 409s because no module may write `app_user`, and there is no
|
||||
|
||||
@@ -215,46 +215,6 @@ class TestFields:
|
||||
with pytest.raises(ValidationError):
|
||||
marketplace._clean_field("category", "x" * 41)
|
||||
|
||||
def test_in_menu_is_a_real_bool(self):
|
||||
assert marketplace._clean_field("in_menu", False) is False
|
||||
assert marketplace._clean_field("in_menu", True) is True
|
||||
for bad in ("false", 0, 1, "no"):
|
||||
with pytest.raises(ValidationError):
|
||||
marketplace._clean_field("in_menu", bad)
|
||||
|
||||
|
||||
class TestServiceModules:
|
||||
"""A service module (`in_menu` false, as Galena) loses its menu entry and its
|
||||
catalogue card, and nothing else: launcher, deep links, stats tiles and access stay."""
|
||||
|
||||
def test_galena_is_seeded_as_a_service(self):
|
||||
from app.seed import FAMILY
|
||||
flags = {e["slug"]: e.get("in_menu", True) for e in FAMILY}
|
||||
assert flags["galena"] is False and flags["arbiter"] is False
|
||||
# Issue #53: the three contract modules are services, shown as one „Umowy” entry.
|
||||
assert flags["lexicon"] is False and flags["scribe"] is False
|
||||
# Panorama left the platform: no longer seeded; 0018 hides an existing row.
|
||||
assert "panorama" not in flags
|
||||
assert all(flags[s] for s in flags if s not in ("galena", "arbiter", "lexicon", "scribe"))
|
||||
|
||||
def test_the_catalogue_hides_it_from_people_not_administrators(self):
|
||||
body = inspect.getsource(marketplace.browse)
|
||||
assert "Module.in_menu.is_(True)" in body
|
||||
assert body.index("user.is_admin") < body.index("Module.in_menu")
|
||||
|
||||
def test_the_launcher_keeps_it(self):
|
||||
# Hiding it here would break every "open in Galena" link, the frame and the Home tiles.
|
||||
assert "in_menu" not in inspect.getsource(marketplace.launcher)
|
||||
|
||||
def test_the_console_drops_only_the_menu_entry(self):
|
||||
console = (FRONTEND / "app.js").read_text(encoding="utf-8")
|
||||
nav = re.search(r"const navModules = \(\) =>.*?;\n", console, re.S).group(0)
|
||||
assert "inMenu(m)" in nav and "m.slug === frame.slug" in nav
|
||||
prefs = console.split("function openNavPrefs()", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "inMenu(m)" in prefs
|
||||
stats = console.split("async function loadModuleStats()", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "inMenu" not in stats
|
||||
|
||||
|
||||
class TestMembership:
|
||||
"""An assignment on a unit reaches its members and the members of every unit below it — and
|
||||
|
||||
@@ -169,9 +169,10 @@ def test_a_server_without_lm_studios_listing_is_never_loaded_by_hand(monkeypatch
|
||||
class _LmStudio:
|
||||
"""The two listings and the two writes of LM Studio, recording the writes."""
|
||||
|
||||
def __init__(self, loaded):
|
||||
def __init__(self, loaded, cold_max=None):
|
||||
self.loaded = dict(loaded) # {id: type}
|
||||
self.writes = []
|
||||
self.cold = {"max_context_length": cold_max} if cold_max else {}
|
||||
|
||||
async def __call__(self, _client, method, url, _key, body=None):
|
||||
if method == "POST":
|
||||
@@ -183,7 +184,7 @@ class _LmStudio:
|
||||
return {}
|
||||
if "/api/v0/" in url:
|
||||
return {"data": [{"id": m, "type": t, "state": "loaded"} for m, t in self.loaded.items()]
|
||||
+ [{"id": "cold", "type": "llm", "state": "not-loaded"}]}
|
||||
+ [{"id": "cold", "type": "llm", "state": "not-loaded", **self.cold}]}
|
||||
return {"models": [{"key": m, "loaded_instances": [{"id": m}]} for m in self.loaded]}
|
||||
|
||||
|
||||
@@ -254,6 +255,17 @@ def test_an_administrator_switches_and_the_embeddings_survive(asker):
|
||||
assert server.writes[-1] == ("load", {"model": "cold", "context_length": model_server.DEFAULT_CONTEXT})
|
||||
|
||||
|
||||
def test_a_model_is_loaded_with_no_more_context_than_it_was_trained_on(monkeypatch):
|
||||
server = _LmStudio({}, cold_max=32768)
|
||||
monkeypatch.setattr(model_server, "_json", server)
|
||||
asyncio.run(model_server.ensure_loaded("http://h", None, "cold", may_switch=False))
|
||||
assert server.writes == [("load", {"model": "cold", "context_length": 32768})]
|
||||
roomy = _LmStudio({}, cold_max=262144)
|
||||
monkeypatch.setattr(model_server, "_json", roomy)
|
||||
asyncio.run(model_server.ensure_loaded("http://h", None, "cold", may_switch=False))
|
||||
assert roomy.writes == [("load", {"model": "cold", "context_length": model_server.DEFAULT_CONTEXT})]
|
||||
|
||||
|
||||
def test_the_lock_decides_again_when_someone_ahead_loaded_another_model(monkeypatch):
|
||||
server = _LmStudio({"qwen": "llm"})
|
||||
monkeypatch.setattr(model_server, "_json", server)
|
||||
|
||||
@@ -158,33 +158,11 @@ def test_cores_english_sentence_is_used_in_english(console):
|
||||
"""Core's refusals carry `detail` in Polish and `en` in English next to a stable `code`; the
|
||||
console's source language is Polish, so EN readers get core's own sentence."""
|
||||
api = console.split("async function api(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "throw httpError(res, data)" in api # the refusal is worded in one place for api() and arbiter()
|
||||
refused = console.split("function httpError(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "coreRefusal(data)" in refused
|
||||
assert "coreRefusal(data)" in api
|
||||
body = console.split("function coreRefusal(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "problem.en" in body and "LANG === SRC_LANG" in body
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", [
|
||||
"provider_key_refused", "provider_unreachable", "provider_no_models", "provider_unknown_key",
|
||||
])
|
||||
def test_discover_refusals_carry_their_english(code):
|
||||
"""These refusals are worded by `coreRefusal` from the Problem Details `code` + `en`, not by a
|
||||
dictionary entry: `provider_unreachable` carries the reason inside its sentence."""
|
||||
backend = ROOT / "backend" / "app"
|
||||
src = ((backend / "integrations" / "model_server.py").read_text(encoding="utf-8")
|
||||
+ (backend / "services" / "providers.py").read_text(encoding="utf-8"))
|
||||
assert "def _refusal(code: str, pl: str, en: str)" in src and '{"code": code, "en": en}' in src
|
||||
assert re.search(rf'_refusal\(\s*"{code}"|"code": "{code}",\s*"en": ', src), code
|
||||
|
||||
|
||||
def test_a_provider_the_eu_only_policy_hides_says_so_in_the_list() -> None:
|
||||
# Core drops a non-EU provider from every model list while `eu_only` is on; the list must not
|
||||
# call it plainly "aktywny" then, or its models vanish from the chat with no visible reason.
|
||||
src = (pathlib.Path(__file__).resolve().parents[2] / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
assert "policy.eu_only && !p.stays_in_the_eu" in src and "ukryty: tylko UE" in src
|
||||
|
||||
|
||||
# ── whose key (dredd-core 0.18.0) ────────────────────────────────────────────
|
||||
@pytest.fixture(scope="module")
|
||||
def my_keys(console) -> str:
|
||||
@@ -239,3 +217,23 @@ def test_home_points_at_my_keys_when_a_personal_key_is_missing(console):
|
||||
assert 'href="#/my-keys"' in hint and "esc(p.name)" in hint
|
||||
# The chat says where to add the key instead of a bare "Nie udało się".
|
||||
assert "'model_provider_user_key_missing'" in console.split("const CHAT_REFUSALS", 1)[1].split(";", 1)[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", [
|
||||
"provider_key_refused", "provider_unreachable", "provider_no_models", "provider_unknown_key",
|
||||
])
|
||||
def test_discover_refusals_carry_their_english(code):
|
||||
"""These refusals are worded by `coreRefusal` from the Problem Details `code` + `en`, not by a
|
||||
dictionary entry: `provider_unreachable` carries the reason inside its sentence."""
|
||||
backend = ROOT / "backend" / "app"
|
||||
src = ((backend / "integrations" / "model_server.py").read_text(encoding="utf-8")
|
||||
+ (backend / "services" / "providers.py").read_text(encoding="utf-8"))
|
||||
assert "def _refusal(code: str, pl: str, en: str)" in src and '{"code": code, "en": en}' in src
|
||||
assert re.search(rf'_refusal\(\s*"{code}"|"code": "{code}",\s*"en": ', src), code
|
||||
|
||||
|
||||
def test_a_provider_the_eu_only_policy_hides_says_so_in_the_list() -> None:
|
||||
# Core drops a non-EU provider from every model list while `eu_only` is on; the list must not
|
||||
# call it plainly "aktywny" then, or its models vanish from the chat with no visible reason.
|
||||
src = (pathlib.Path(__file__).resolve().parents[2] / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
assert "policy.eu_only && !p.stays_in_the_eu" in src and "ukryty: tylko UE" in src
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
"""The review panel's polling and acceptance, and the home page's ways into Galena, run under Node
|
||||
with the DOM and the modules stubbed. DB-free; skipped where no `node`."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _between(start: str, end: str) -> str:
|
||||
i = SRC.index(start)
|
||||
return SRC[i:SRC.index(end, i)]
|
||||
|
||||
|
||||
CONSTS = _between("const CHAT_REVIEW_POLL_MS = ", "// A Galena project's document file")
|
||||
PANEL = _between("const reviewPanel = ", "/* An Atrium GET answered as text")
|
||||
LINKS = _between("function homeGalenaLinks()", "async function loadHomeStats()")
|
||||
|
||||
DOM = """
|
||||
const els = {};
|
||||
const mk = (id) => ({ id, innerHTML: '', textContent: '', value: '', attrs: {},
|
||||
classList: { add() {}, remove() {} }, setAttribute(k, v) { this.attrs[k] = v; } });
|
||||
const $ = (id) => els[id] || null;
|
||||
const document = { baseURI: 'http://x/atrium/', body: { appendChild(el) { els[el.id] = el; } },
|
||||
createElement: () => mk(null) };
|
||||
const esc = (s) => String(s); const svg = () => ''; const ICN = { x: 'x', check: 'c' };
|
||||
const _tr = (s) => s; const localize = () => {}; const toasts = []; const toast = (t) => toasts.push(t);
|
||||
const timers = []; const setTimeout = (f, ms) => { timers.push(ms); return timers.length; };
|
||||
const clearTimeout = () => {};
|
||||
const pending = [];
|
||||
const arbiter = (method, path, body) => new Promise((ok, no) => pending.push({ method, path, ok, no }));
|
||||
const tick = () => new Promise((r) => setImmediate(r));
|
||||
"""
|
||||
|
||||
|
||||
def _node(body: str) -> dict:
|
||||
script = DOM + CONSTS + PANEL + "\n(async () => {\n" + body + "\n})().catch((e) => { console.error(e); process.exit(1); });"
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
A = "{ id: 'a1', number: 'UM-1', name: 'Najem', skill: 'S', n: 1 }"
|
||||
B = "{ id: 'b2', number: 'UM-2', name: 'Dostawa', skill: 'S', n: 1 }"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_late_answer_for_a_replaced_run_draws_nothing() -> None:
|
||||
out = _node(f"""
|
||||
reviewOpen({A});
|
||||
reviewOpen({B});
|
||||
pending[0].ok({{ status: 'running' }}); // the first run's answer comes last
|
||||
await tick();
|
||||
pending[1].ok({{ status: 'running' }});
|
||||
await tick();
|
||||
console.log(JSON.stringify({{ html: els.reviewPanel.innerHTML, timers }}));
|
||||
""")
|
||||
assert "UM-2" in out["html"] and "UM-1" not in out["html"]
|
||||
assert out["timers"] == [3000]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_polling_backs_off_and_gives_up() -> None:
|
||||
out = _node(f"""
|
||||
reviewOpen({A});
|
||||
for (let i = 0; i < 6; i++) {{ pending[i].ok({{ status: 'running' }}); await tick(); reviewPoll(); }}
|
||||
reviewPanel.analysis.since -= CHAT_REVIEW_GIVE_UP_MS + 1;
|
||||
const before = timers.length;
|
||||
pending[6].ok({{ status: 'running' }}); await tick();
|
||||
console.log(JSON.stringify({{ timers, stopped: timers.length === before, html: els.reviewPanel.innerHTML }}));
|
||||
""")
|
||||
assert out["timers"][:6] == [3000, 6000, 12000, 24000, 30000, 30000]
|
||||
assert out["stopped"] and "dłużej niż zwykle" in out["html"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_an_acceptance_answered_after_the_panel_closed_touches_nothing() -> None:
|
||||
out = _node(f"""
|
||||
reviewOpen({A});
|
||||
pending[0].ok({{ status: 'done' }}); await tick();
|
||||
els.rpErr = mk('rpErr');
|
||||
reviewAccept();
|
||||
reviewClose();
|
||||
pending[1].no(new Error('late refusal')); await tick();
|
||||
console.log(JSON.stringify({{ err: els.rpErr.textContent, accepted: pending[1].path, polls: pending.length }}));
|
||||
""")
|
||||
assert out["accepted"] == "analyses/a1/acceptance"
|
||||
assert out["err"] == "" and out["polls"] == 2
|
||||
|
||||
|
||||
def _links(launcher) -> str:
|
||||
script = (f"const state = {{ launcher: {json.dumps(launcher)} }};\n"
|
||||
"const esc = (s) => String(s); const moduleIcon = () => '<i></i>';\n"
|
||||
"const frameHash = (slug, inner) => '#/m/' + slug + '/' + inner;\n"
|
||||
+ LINKS + "\nconsole.log(JSON.stringify(homeGalenaLinks()));")
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_ways_into_galena_are_shown_only_with_access() -> None:
|
||||
html = _links([{"slug": "galena", "has_access": True}])
|
||||
assert 'href="#/m/galena/"' in html and 'href="#/m/galena/cards"' in html
|
||||
assert _links([{"slug": "galena", "has_access": False}]) == ""
|
||||
assert _links([{"slug": "sygna", "has_access": True}]) == ""
|
||||
@@ -1,116 +0,0 @@
|
||||
"""Revision 0016: `module.in_menu`, and Galena becomes a service module (DB-free)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def revision():
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"revision_0016", BACKEND / "alembic" / "versions" / "0016_service_modules.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class _Recorder:
|
||||
def __init__(self) -> None:
|
||||
self.sql: list[str] = []
|
||||
|
||||
def execute(self, stmt):
|
||||
self.sql.append(stmt if isinstance(stmt, str) else str(stmt.compile(
|
||||
dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True})))
|
||||
|
||||
def get_bind(self):
|
||||
return self
|
||||
|
||||
|
||||
def _run(revision, monkeypatch, fn: str) -> list[str]:
|
||||
rec = _Recorder()
|
||||
monkeypatch.setattr(revision, "op", rec)
|
||||
getattr(revision, fn)()
|
||||
return rec.sql
|
||||
|
||||
|
||||
def test_it_follows_the_skills_revision(revision):
|
||||
assert (revision.revision, revision.down_revision) == ("0016", "0015")
|
||||
|
||||
|
||||
def test_upgrade_is_idempotent_and_touches_only_galena(revision, monkeypatch):
|
||||
add, switch = _run(revision, monkeypatch, "upgrade")
|
||||
# 0001 builds `module` from the live metadata on a fresh database, so the column may exist.
|
||||
assert "ADD COLUMN IF NOT EXISTS in_menu boolean NOT NULL DEFAULT true" in add
|
||||
assert switch.startswith("UPDATE module SET in_menu=false")
|
||||
assert "WHERE module.slug = 'galena'" in switch
|
||||
|
||||
|
||||
def test_downgrade_drops_only_the_column(revision, monkeypatch):
|
||||
assert _run(revision, monkeypatch, "downgrade") == [
|
||||
"ALTER TABLE module DROP COLUMN IF EXISTS in_menu"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def arbiter_revision():
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"revision_0017", BACKEND / "alembic" / "versions" / "0017_arbiter_service.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_0017_makes_only_arbiter_a_service_and_back(arbiter_revision, monkeypatch):
|
||||
"""Contracts are checked from the chat, Arbiter has no console of its own."""
|
||||
assert (arbiter_revision.revision, arbiter_revision.down_revision) == ("0017", "0016")
|
||||
up, = _run(arbiter_revision, monkeypatch, "upgrade")
|
||||
assert up.startswith("UPDATE module SET in_menu=false") and "module.slug = 'arbiter'" in up
|
||||
down, = _run(arbiter_revision, monkeypatch, "downgrade")
|
||||
assert down.startswith("UPDATE module SET in_menu=true") and "module.slug = 'arbiter'" in down
|
||||
|
||||
|
||||
def test_0018_retires_only_panorama_from_the_menu(monkeypatch):
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"revision_0018", BACKEND / "alembic" / "versions" / "0018_panorama_retired.py")
|
||||
rev = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(rev)
|
||||
assert (rev.revision, rev.down_revision) == ("0018", "0017")
|
||||
up, = _run(rev, monkeypatch, "upgrade")
|
||||
assert up.startswith("UPDATE module SET in_menu=false") and "module.slug = 'panorama'" in up
|
||||
|
||||
|
||||
def test_panorama_is_off_the_platform():
|
||||
"""The seed no longer offers Panorama and the front door no longer routes it; an
|
||||
existing row stays, hidden from the menu by 0018 (above)."""
|
||||
from app import frontdoor
|
||||
from app.seed import ADDED_AFTER_FIRST_SEED, FAMILY
|
||||
|
||||
assert "panorama" not in {e["slug"] for e in FAMILY}
|
||||
assert "panorama" not in ADDED_AFTER_FIRST_SEED
|
||||
assert "panorama" not in frontdoor.MODULES
|
||||
assert b"/panorama" not in frontdoor.NOT_FOUND
|
||||
|
||||
|
||||
def test_0019_makes_lexicon_and_scribe_services_and_back(monkeypatch):
|
||||
"""Issue #53: no console of their own; the catalogue shows one „Umowy” entry for the three."""
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"revision_0019", BACKEND / "alembic" / "versions" / "0019_contracts_one_entry.py")
|
||||
rev = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(rev)
|
||||
assert (rev.revision, rev.down_revision) == ("0019", "0018")
|
||||
up, = _run(rev, monkeypatch, "upgrade")
|
||||
assert up.startswith("UPDATE module SET in_menu=false")
|
||||
assert "module.slug IN ('lexicon', 'scribe')" in up
|
||||
down, = _run(rev, monkeypatch, "downgrade")
|
||||
assert down.startswith("UPDATE module SET in_menu=true") and "('lexicon', 'scribe')" in down
|
||||
|
||||
|
||||
def test_the_console_shows_one_contracts_entry():
|
||||
console = (BACKEND.parent / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
assert "const CONTRACTS = ['arbiter', 'lexicon', 'scribe'];" in console
|
||||
assert "contractsNavItem(cur) + mods.map(modItem)" in console
|
||||
assert "d.modules.filter((m) => !CONTRACTS.includes(m.slug))" in console
|
||||
@@ -27,7 +27,6 @@ def test_every_skills_route_is_registered_under_the_api_prefix():
|
||||
for method, path in [
|
||||
("GET", "/skills"), ("POST", "/skills"), ("GET", "/skills/{skill_id}"),
|
||||
("POST", "/skills/{skill_id}/versions"), ("GET", "/skills/{skill_id}/versions/{n}"),
|
||||
("GET", "/skills/{skill_id}/versions/{n}/files/{path:path}"),
|
||||
("POST", "/skills/{skill_id}/archive"), ("POST", "/skills/{skill_id}/publish"),
|
||||
("GET", "/skills/{skill_id}/export"), ("POST", "/skills/import"),
|
||||
]:
|
||||
@@ -127,16 +126,6 @@ def test_a_new_version_decodes_files_and_leaves_absent_fields_none(api):
|
||||
assert fields["description"] is None and fields["metadata"] is None # None = carry over
|
||||
|
||||
|
||||
def test_a_new_version_passes_base_n_and_refuses_one_below_1(api):
|
||||
r = api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"base_n": 3})
|
||||
assert r.status_code == 201, r.text
|
||||
(_, fields), _ = api.calls["new_version"]
|
||||
assert fields["base_n"] == 3
|
||||
del api.calls["new_version"]
|
||||
assert api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"base_n": 0}).status_code == 422
|
||||
assert "new_version" not in api.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("files", [
|
||||
{"a.txt": "not base64!"},
|
||||
["a.txt"],
|
||||
@@ -163,8 +152,7 @@ def test_every_agent_and_publish_request_route_is_registered_under_the_api_prefi
|
||||
("GET", "/agents"), ("POST", "/agents"), ("GET", "/agents/{agent_id}"),
|
||||
("POST", "/agents/{agent_id}/versions"), ("POST", "/agents/{agent_id}/archive"),
|
||||
("POST", "/agents/{agent_id}/publish"), ("GET", "/agents/{agent_id}/export"),
|
||||
("POST", "/agents/import"), ("GET", "/skills/permissions"),
|
||||
("GET", "/admin/publish-requests"),
|
||||
("POST", "/agents/import"), ("GET", "/admin/publish-requests"),
|
||||
("POST", "/admin/publish-requests/{request_id}/approve"),
|
||||
("POST", "/admin/publish-requests/{request_id}/decline"),
|
||||
]:
|
||||
@@ -177,17 +165,15 @@ def _calls(dependant):
|
||||
yield from _calls(d)
|
||||
|
||||
|
||||
def test_every_publish_request_route_depends_on_require_skill_approver():
|
||||
def test_every_publish_request_route_depends_on_require_administrator():
|
||||
routes = [r for r in app.routes
|
||||
if isinstance(r, APIRoute) and r.path.startswith(API + "/admin/publish-requests")]
|
||||
assert len(routes) == 3
|
||||
for r in routes:
|
||||
assert deps.require_skill_approver in set(_calls(r.dependant)), r.path
|
||||
assert deps.require_administrator not in set(_calls(r.dependant)), r.path
|
||||
assert deps.require_administrator in set(_calls(r.dependant)), r.path
|
||||
|
||||
|
||||
def test_somebody_who_may_not_approve_is_refused_the_publish_queue(api, monkeypatch):
|
||||
monkeypatch.setattr(service, "may_approve", lambda _db, _user: False)
|
||||
def test_a_non_administrator_is_refused_the_publish_queue(api):
|
||||
r = api.client.get(f"{API}/admin/publish-requests")
|
||||
assert r.status_code == 403
|
||||
|
||||
@@ -200,16 +186,3 @@ def test_a_new_agent_version_passes_pins_and_leaves_absent_fields_none(api, monk
|
||||
r = api.client.post(f"{API}/agents/{SKILL_ID}/versions", json={"skill_version_ids": [str(pin)]})
|
||||
assert r.status_code == 201, r.text
|
||||
assert seen["skill_version_ids"] == [pin] and seen["instructions"] is None
|
||||
|
||||
|
||||
def test_an_approver_who_is_not_an_administrator_reaches_the_publish_queue(api, monkeypatch):
|
||||
monkeypatch.setattr(service, "may_approve", lambda _db, _user: True)
|
||||
monkeypatch.setattr(service, "pending_publish_requests", lambda _db, _actor: [])
|
||||
r = api.client.get(f"{API}/admin/publish-requests")
|
||||
assert r.status_code == 200 and r.json() == []
|
||||
|
||||
|
||||
def test_permissions_route_is_not_swallowed_by_skill_id(api, monkeypatch):
|
||||
monkeypatch.setattr(service, "may_approve", lambda _db, _user: True)
|
||||
r = api.client.get(f"{API}/skills/permissions")
|
||||
assert r.status_code == 200 and r.json() == {"approve": True}
|
||||
|
||||
@@ -8,16 +8,12 @@ address. That the routes behave is `test_skills_integration.py`'s job.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -175,17 +171,12 @@ def _text_builders(screen: str) -> str:
|
||||
|
||||
def test_dynamic_values_are_escaped(screen):
|
||||
"""No field of a response reaches markup bare: every `${x.field}` sits inside esc()/dat()/enc().
|
||||
Counts (`.length`) are numbers; the api()/mutate()/arbiter() lines build URLs, where enc() is the rule."""
|
||||
Counts (`.length`) are numbers; the api()/mutate() lines build URLs, where enc() is the rule."""
|
||||
code = _text_builders(screen)
|
||||
assert "versionText = " not in code and "infoLines = " not in code
|
||||
assert len(_interpolations(code)) > 50
|
||||
assert not _bare(code), _bare(code)
|
||||
|
||||
|
||||
def _bare(code: str) -> list[str]:
|
||||
"""The interpolations in `code` that render a response field without esc()/dat()/enc()."""
|
||||
code = "\n".join(line for line in code.splitlines() if not re.search(r"\b(?:api|mutate|arbiter)[(]'", line))
|
||||
code = "\n".join(line for line in code.splitlines() if not re.search(r"\b(?:api|mutate)[(]'", line))
|
||||
exprs = _interpolations(code)
|
||||
assert len(exprs) > 50, len(exprs)
|
||||
bare = []
|
||||
for e in exprs:
|
||||
if _wrapped(e):
|
||||
@@ -199,7 +190,7 @@ def _bare(code: str) -> list[str]:
|
||||
part = part.strip()
|
||||
if op not in ("?", "&&") and re.fullmatch(r"[a-z]\w*(?:\.\w+|\[\d+\])+", part) and not part.endswith(".length"):
|
||||
bare.append(e)
|
||||
return bare
|
||||
assert not bare, bare
|
||||
|
||||
|
||||
def _wrapped(e: str) -> bool:
|
||||
@@ -245,299 +236,3 @@ def test_it_is_in_both_languages(console, screen, phrase):
|
||||
assert phrase in screen
|
||||
block = console.split("const I18N = {", 1)[1].split("\n};", 1)[0]
|
||||
assert re.search(rf"""^ ['"]{re.escape(phrase)}['"]: """, block, re.M), f"no English for {phrase!r}"
|
||||
|
||||
|
||||
# ── the checking procedure's editor (Mapa / Standardy) ──────────────────────────────────────────
|
||||
# Arbiter is a sibling module on the same origin: the console reaches it through `arbiter()` only,
|
||||
# so these are the routes it may ask for (Task 6's trial and standards check included).
|
||||
ARBITER_ROUTES = {
|
||||
("POST", "skill-check/normalize"), ("GET", "skill-check/clause-types"),
|
||||
("POST", "skills/{}/versions/{}/sync"), ("GET", "skills/{}/versions/{}"),
|
||||
("POST", "agents/{}/trial"), ("POST", "agents/{}/standards-check"), ("GET", "agents/{}"),
|
||||
# The chat's contract check (chatReview, the report panel): a subject on a Galena document, an
|
||||
# order by skill, the run polled, its acceptance. A path built by concatenation reads as its
|
||||
# literal head ("analyses/" + id).
|
||||
("POST", "subjects/document"), ("POST", "analyses"), ("GET", "analyses/"), ("POST", "analyses/"),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def plan_editor(console) -> str:
|
||||
return _section(console, "/* ── checking procedure", "/* ── import ──")
|
||||
|
||||
|
||||
def test_arbiter_calls_hit_only_known_routes(console, screen):
|
||||
calls = {(m.group(1), _path(_first_arg(console, m.end())))
|
||||
for m in re.finditer(r"\barbiter[(]'([A-Z]+)', ", console)}
|
||||
assert {("POST", "skill-check/normalize"), ("GET", "skill-check/clause-types")} <= calls, calls
|
||||
assert calls <= ARBITER_ROUTES, calls - ARBITER_ROUTES
|
||||
# One helper, same origin, the session cookie; never api()/mutate(), which are Atrium's own.
|
||||
helper = _section(console, "async function arbiter(", "\n}\n")
|
||||
assert "new URL('../arbiter/api/v1/' + path, document.baseURI)" in helper
|
||||
assert "credentials: 'same-origin'" in helper
|
||||
assert "async function arbiter(" not in screen # its '/api/v1' literal stays out of the screen
|
||||
assert not re.search(r"\b(?:api|mutate)[(]'[A-Z]+', '/?(?:skill-check|\.\./arbiter)", console)
|
||||
|
||||
|
||||
def test_the_editor_saves_with_file_updates_not_files(console, plan_editor):
|
||||
save = _section(console, "function savePlan(", "\n}\n")
|
||||
# Normalized by Arbiter first (its parser is the one that knows the format), then stored as ONE
|
||||
# file of a new version: the other files carry over on the server, the console never holds them.
|
||||
assert save.index("arbiter('POST', 'skill-check/normalize'") < save.index("/versions'")
|
||||
assert "file_updates: { 'sprawdzanie.yaml': utf8Base64(" in save
|
||||
assert not re.search(r"\bfiles:", save)
|
||||
assert "JSON.stringify({ wersja_formatu: 1, kroki: " in save
|
||||
# Ruling 15: the new version is made on the version the draft was loaded from, not on the
|
||||
# server's default base, which may be a newer proposal the draft never saw.
|
||||
assert "base_n: state._planBase.n, file_updates:" in save
|
||||
# The bytes are UTF-8 (TextEncoder), base64'd in slices: fromCharCode(...all) overflows the stack.
|
||||
enc_fn = _section(console, "function utf8Base64(", "\n}\n")
|
||||
assert "new TextEncoder().encode(" in enc_fn
|
||||
base = _section(console, "function bytesBase64(", "\n}\n")
|
||||
assert "0x8000" in base
|
||||
|
||||
|
||||
def test_the_draft_is_kept_until_saved_or_left_on_purpose(console, plan_editor):
|
||||
assert "state._plan" in plan_editor and "state._planDirty" in plan_editor
|
||||
route = _section(console, "async function router(", "\n}\n")
|
||||
assert "if (leavingDraft()) return;" in route
|
||||
assert "beforeunload" in console
|
||||
|
||||
|
||||
def test_the_draft_is_keyed_to_the_version_it_was_loaded_from(console, plan_editor):
|
||||
"""A draft belongs to one version (`state._planBase`), set where it is loaded and where a new
|
||||
procedure is started, and a re-render never shows it under another version."""
|
||||
load = _section(console, "async function loadPlan(", "\n}\n")
|
||||
assert "state._planBase = { id: shown.id, n: shown.n };" in load
|
||||
start = _section(console, "function startPlan(", "\n}\n")
|
||||
assert "state._planBase = { id: shown.id, n: shown.n };" in start
|
||||
view = _section(console, "async function viewSkill(", "\n}\n")
|
||||
assert "state._planBase.id !== shown.id" in view
|
||||
# "Nowa wersja" asks before it could leave a dirty draft behind.
|
||||
editor = _section(console, "function openSkillEditor(", "\n}\n")
|
||||
assert "if (id && state._planDirty) { askLeavingDraft(() => openSkillEditor(id)); return; }" in editor
|
||||
|
||||
|
||||
def test_plan_values_are_escaped(screen, plan_editor):
|
||||
"""`test_dynamic_values_are_escaped` reads the whole screen, the editor's lines included."""
|
||||
assert plan_editor in screen
|
||||
for fn in ("function planMapHtml(", "function planStandardsHtml(", "function openStepEditor(",
|
||||
"function openStandardEditor("):
|
||||
assert fn in plan_editor
|
||||
assert len(_interpolations(plan_editor)) > 20
|
||||
assert not _bare(plan_editor), _bare(plan_editor)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phrase", [
|
||||
"Opis", "Mapa", "Standardy", "Dodaj procedurę sprawdzania", "Niezapisane zmiany",
|
||||
"Zapisz jako nową wersję", "Odrzuć zmiany",
|
||||
"Nie masz dostępu do usługi sprawdzania. Poproś administratora o moduł Arbiter.",
|
||||
"Zapisano wersję {n} jako propozycję. Firma sprawdza wersją {m}, dopóki zatwierdzający jej nie zatwierdzi.",
|
||||
"Dodaj krok", "Edytuj krok", "Nowy krok", "Nazwa kroku", "Krok", "W górę", "W dół",
|
||||
"Dodaj standard", "Edytuj standard", "Nowy standard", "Zasada", "Brzmienie", "Odstępstwo", "Waga",
|
||||
"Typ klauzuli", "Przykłady testowe", "Dodaj przykład", "blokująca", "istotna", "informacyjna",
|
||||
"spełnia", "narusza", "Ten krok nie ma jeszcze standardów.", "Wczytywanie procedury…",
|
||||
"Masz niezapisane zmiany w procedurze sprawdzania.", "Wyjdź bez zapisywania", "Zostań",
|
||||
"Procedura sprawdzania w tej wersji ma błąd, więc formularze jej nie otworzą:",
|
||||
"Podaj nazwę kroku.", "Podaj zasadę.",
|
||||
# Task 6: the trial, the standards check and the approver's queue
|
||||
"Próba", "Zatwierdzona dla firmy", "Propozycja",
|
||||
"Próba sprawdza, czy wybrany model trafnie ocenia 15 umów wzorcowych. Test standardów sprawdza "
|
||||
"przykłady przypięte do Twoich standardów. Prawdziwe umowy sprawdza tylko wersja zatwierdzona dla "
|
||||
"firmy z ukończoną próbą.",
|
||||
"Próby jeszcze nie uruchomiono", "Uruchom próbę", "Zatrzymaj", "Sprawdź standardy", "Test standardów",
|
||||
"{k} z {of} umów, zgodność {a}/{r}", "Testu standardów jeszcze nie uruchomiono",
|
||||
"Sprawdzono przykładów: {k}", "Model ocenił wszystkie przykłady tak, jak oczekiwano.",
|
||||
"Model ocenił przykład inaczej, niż oczekiwano", "Model nie był pewny", "Brak przykładów testowych",
|
||||
"To podpowiedź. Nie blokuje zatwierdzenia.", "Do zatwierdzenia", "Próba: {k} z {of}, zgodność {a}/{r}",
|
||||
"Próby nie uruchomiono", "Brak danych o próbie", "Twój wniosek. Decyduje inny zatwierdzający.",
|
||||
# The final fix wave: the publish action on the version shown, an approver (not an
|
||||
# administrator) decides, and a trial step that never answers.
|
||||
"Wyślij do zatwierdzenia", "Wysłano do zatwierdzenia.", "Ta wersja czeka na zgodę zatwierdzającego.",
|
||||
"Ten krok trwa zbyt długo. Sprawdź serwer modelu i spróbuj ponownie.",
|
||||
])
|
||||
def test_new_phrases_are_in_both_languages(console, screen, phrase):
|
||||
assert phrase in screen
|
||||
block = console.split("const I18N = {", 1)[1].split("\n};", 1)[0]
|
||||
assert re.search(rf"""^ ['"]{re.escape(phrase)}['"]: """, block, re.M), f"no English for {phrase!r}"
|
||||
|
||||
|
||||
# ── a version's trial and standards check (Próba), and the approver's queue ─────────────────────
|
||||
def test_trial_loop_rereads_the_agent_on_504(console):
|
||||
"""Atrium's front door cuts a proxied request at 300 s with its own 504 while Arbiter finishes the
|
||||
step: the loop reads the agent until that step has landed, and only then asks for the next one,
|
||||
so no POST ever goes out beside a step still running. The behaviour is `trial_loop.mjs`'s."""
|
||||
loop = _section(console, "async function runVersionLoop(", "\n}\n")
|
||||
assert "if (ex.status !== 504) throw ex;" in loop
|
||||
assert "const cut = await awaitCutStep(t, sync.agent_id, (a) => stepLanded(before, stored(a), count));" in loop
|
||||
# One capped retry, not a POST every 125 minutes for ever (behaviour: trial_loop.mjs).
|
||||
assert "if (capped) throw Object.assign(new Error(TRIAL_SLOW), { slow: true });" in loop
|
||||
assert "while (state._trials[t.version] === t && !t.stop)" in loop
|
||||
assert "Promise.all" not in loop
|
||||
# One loop at a time: a second press while one runs does nothing.
|
||||
assert "if (!t || t.running || t.loading) return;" in loop
|
||||
wait = _section(console, "async function awaitCutStep(", "\n}\n")
|
||||
assert "await arbiter('GET', 'agents/' + enc(agentId));" in wait
|
||||
assert "await sleep(TRIAL_POLL_MS);" in wait
|
||||
assert "Date.now() >= until" in wait
|
||||
assert "const TRIAL_WAIT_MS = 125 * 60 * 1000;" in console
|
||||
# Arbiter's "slot busy" carries no code; nothing here reads a refusal's words.
|
||||
assert "409" not in loop + wait and "busy" not in loop + wait
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_trial_loop_waits_for_the_cut_off_step_by_behaviour():
|
||||
"""`runVersionLoop` under a scripted arbiter(): a 504, a re-read with no progress, a re-read with
|
||||
progress, and only then the next POST, with no error; plus the cap, "Zatrzymaj" and sign-out,
|
||||
one capped retry at most, and a failed read during the wait that keeps the wait going."""
|
||||
r = subprocess.run(
|
||||
[NODE, str(ROOT / "backend" / "tests" / "js" / "trial_loop.mjs"), str(ROOT / "frontend" / "app.js")],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
assert r.returncode == 0, r.stdout + r.stderr
|
||||
|
||||
|
||||
def test_the_run_state_is_kept_per_version(console):
|
||||
"""A loop goes on while another version is shown; coming back finds its button still disabled,
|
||||
so a second press cannot post beside the step still running."""
|
||||
assert not re.search(r"state\._trial\b(?!s)", console)
|
||||
assert "_trials: {}," in _section(console, "const state = {", "\n};")
|
||||
assert "_trials" not in _section(console, "async function viewSkill(", "\n}\n")
|
||||
load = _section(console, "async function loadTrial(", "\n}\n")
|
||||
assert "if (state._trials[shown.id]) return;" in load
|
||||
assert "const t = state._trials[shown.id];" in _section(console, "async function runVersionLoop(", "\n}\n")
|
||||
assert "const t = state._trials[shown.id] || { loading: true };" in _section(console, "function trialPanelHtml(", "\n}\n")
|
||||
assert "state._trials = {};" in _section(console, "function showLogin(", "\n}\n")
|
||||
|
||||
|
||||
def test_the_approval_chip_reads_the_version_as_get_version_read_it(console):
|
||||
"""get_skill's `current` has no `approved_for_firm`; the default view shows the current version as
|
||||
get_version read it, so the firm's approved version is not labelled a proposal."""
|
||||
view = _section(console, "async function viewSkill(", "\n}\n")
|
||||
assert "|| (s.current && vs.find((v) => v.id === s.current.id)) || vs[0];" in view
|
||||
assert "|| s.current ||" not in view
|
||||
assert "shown.approved_for_firm" in _section(console, "function trialPanelHtml(", "\n}\n")
|
||||
|
||||
|
||||
def test_trial_and_check_pass_agent_version_id(console):
|
||||
"""A skill's agent names the version to try: the sync freezes it first and gives its id."""
|
||||
steps = _section(console, "const VERSION_STEPS = {", "\n};")
|
||||
assert "arbiter('POST', `agents/${enc(agent)}/trial?agent_version_id=${enc(vid)}`)" in steps
|
||||
assert "arbiter('POST', `agents/${enc(agent)}/standards-check?agent_version_id=${enc(vid)}`)" in steps
|
||||
loop = _section(console, "async function runVersionLoop(", "\n}\n")
|
||||
sync = loop.index("arbiter('POST', `skills/${enc(s.id)}/versions/${shown.n}/sync`)")
|
||||
assert sync < loop.index("VERSION_STEPS[kind](sync.agent_id, vid)")
|
||||
assert "const vid = sync.agent_version_id;" in loop
|
||||
load = _section(console, "async function loadTrial(", "\n}\n")
|
||||
assert "arbiter('GET', `skills/${enc(s.id)}/versions/${shown.n}`)" in load
|
||||
assert "ex.problem.code === 'not_synced'" in load
|
||||
|
||||
|
||||
def test_the_run_button_is_disabled_while_running(console):
|
||||
panel = _section(console, "function trialPanelHtml(", "\n}\n")
|
||||
assert "const busy = !!(t.running || t.loading);" in panel
|
||||
assert "onclick=\"runVersionLoop('trial')\"${busy ? ' disabled' : ''}" in panel
|
||||
assert "onclick=\"runVersionLoop('check')\"${busy ? ' disabled' : ''}" in panel
|
||||
# "Zatrzymaj" ends the loop after the step under way: a flag the loop reads, not an abort.
|
||||
stop = _section(console, "function stopVersionLoop(", "\n}\n")
|
||||
assert "t.stop = true;" in stop
|
||||
assert "abort" not in stop
|
||||
|
||||
|
||||
def test_approver_tab_shows_only_with_permission(console):
|
||||
"""The approver's queue under Skille i agenci follows `/skills/permissions`, not is_admin."""
|
||||
tabs = _section(console, "function skillTabs(", "\n}\n")
|
||||
assert "(state._skillPerms || {}).approve ? tab('requests', '#/skills/requests', 'Do zatwierdzenia') : ''" in tabs
|
||||
assert "isAdmin" not in tabs
|
||||
assert "api('GET', '/skills/permissions')" in _section(console, "async function viewSkills(", "\n}\n")
|
||||
view = _section(console, "async function viewSkillRequests(", "\n}\n")
|
||||
assert "state._skillPerms = await api('GET', '/skills/permissions');" in view
|
||||
assert view.index("if (!state._skillPerms.approve)") < view.index("api('GET', '/admin/publish-requests')")
|
||||
assert "isAdmin" not in view
|
||||
route = _section(console, "async function router(", "\n}\n")
|
||||
here = route.index("else if (seg[0] === 'skills' && seg[1] === 'requests') await viewSkillRequests(C);")
|
||||
assert here < route.index("else if (seg[0] === 'skills') await viewSkills(")
|
||||
# One card renderer for both queues; the administrator's route stays.
|
||||
assert "publishRequestCards(rows, { trials })" in view
|
||||
assert "publishRequestCards(rows)" in _section(console, "async function viewAdminPublishRequests(", "\n}\n")
|
||||
# A trial line only for a checking skill, from Arbiter's read; any refusal is "no data".
|
||||
line = _section(console, "async function requestTrialLine(", "\n}\n")
|
||||
assert "arbiter('GET', `skills/${enc(r.item.id)}/versions/${r.version.n}`)" in line
|
||||
assert "'Brak danych o próbie'" in line
|
||||
|
||||
|
||||
|
||||
# ── the final fix wave: publish and save act on the version shown; four eyes on the author ──────
|
||||
def test_the_publish_action_names_the_version_shown(console):
|
||||
"""The button publishes the version on screen (`?n=`): without `n` the server takes the actor's
|
||||
own newest version, so a proposer had no way to put a proposal forward and an editor published
|
||||
something other than what they were looking at."""
|
||||
view = _section(console, "async function viewSkill(", "\n}\n")
|
||||
assert "const publishing = publishAction(s, shown);" in view
|
||||
assert "onclick=\"publishSkill('${esc(s.id)}', ${esc(String(shown.n))})\"><span>${esc(publishing)}</span>" in view
|
||||
assert "publishable" not in view
|
||||
publish = _section(console, "function publishSkill(", "\n}\n")
|
||||
assert "mutate('POST', `/skills/${enc(id)}/publish?n=${enc(String(n))}`, undefined, {" in publish
|
||||
assert "'Wysłano do zatwierdzenia.'" in publish
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_publish_action_follows_who_may_put_the_version_forward(console):
|
||||
"""Ruling 12: an editor may publish any version newer than the firm's current one; anybody else
|
||||
only a version they wrote, and theirs goes to the approvers. Nothing on an archived skill."""
|
||||
fn = "function publishAction(" + _section(console, "function publishAction(", "\n}\n") + "\n}\n"
|
||||
cur = {"id": "cur", "n": 3, "created_by": "me"}
|
||||
firm = {"scope": "firm", "status": "active", "current_version_id": "cur", "current": cur}
|
||||
editor = {**firm, "proposable": True, "editable": True}
|
||||
proposer = {**firm, "proposable": True, "editable": False}
|
||||
newer = {"id": "p", "n": 4}
|
||||
cases = [
|
||||
(editor, {**newer, "created_by": "x"}, "Opublikuj w firmie"),
|
||||
(editor, cur, None),
|
||||
# An older version would roll the firm back; an approver is refused it anyway.
|
||||
(editor, {"id": "old", "n": 2, "created_by": "me"}, None),
|
||||
(proposer, {**newer, "created_by": "me"}, "Wyślij do zatwierdzenia"),
|
||||
(proposer, cur, None),
|
||||
(proposer, {**newer, "created_by": "x"}, None),
|
||||
({**editor, "status": "archived"}, {**newer, "created_by": "me"}, None),
|
||||
({**firm, "proposable": False, "editable": False}, {**newer, "created_by": "me"}, None),
|
||||
# A personal skill's current version is what its owner puts forward to the firm, and a
|
||||
# firm skill whose first publication still waits has no current one to measure against.
|
||||
({"scope": "personal", "status": "active", "current_version_id": "cur", "current": cur,
|
||||
"proposable": True, "editable": True}, cur, "Opublikuj w firmie"),
|
||||
({**editor, "current_version_id": None, "current": None}, {**newer, "created_by": "me"},
|
||||
"Opublikuj w firmie"),
|
||||
(editor, None, None),
|
||||
]
|
||||
script = (fn + "const state = { user: { id: 'me' } };\n"
|
||||
+ f"process.stdout.write(JSON.stringify({json.dumps([[s, v] for s, v, _ in cases])}"
|
||||
+ ".map(([s, v]) => publishAction(s, v))));")
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60)
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert json.loads(r.stdout) == [want for _, _, want in cases]
|
||||
|
||||
|
||||
def test_a_new_version_is_made_on_the_version_shown(console):
|
||||
"""Ruling 15 for "Nowa wersja" too: the form shows the version on screen and the save names it as
|
||||
`base_n`, so its text and the files the server carries over come from one version."""
|
||||
editor = _section(console, "function openSkillEditor(", "\n}\n")
|
||||
assert "const v = id ? state._skillView.shown : null;" in editor
|
||||
assert "const save = id ? `'${esc(id)}', ${v ? esc(String(v.n)) : 'null'}` : '';" in editor
|
||||
assert "onclick=\"saveSkill(${save})\"" in editor
|
||||
save = _section(console, "function saveSkill(", "\n}\n")
|
||||
assert "function saveSkill(id, baseN) {" in console
|
||||
assert "if (baseN) body.base_n = baseN;" in save
|
||||
assert "_skillLatest" not in console
|
||||
|
||||
|
||||
def test_an_approver_gets_no_buttons_on_a_version_they_wrote(console):
|
||||
"""The server refuses a non-administrator who filed the request or wrote the version; the card
|
||||
says so instead of offering buttons that would fail."""
|
||||
cards = _section(console, "function publishRequestCards(", "\n}\n")
|
||||
assert ("!isAdmin() && (r.requested_by.id === state.user.id || r.version.created_by === state.user.id)"
|
||||
in cards)
|
||||
|
||||
|
||||
def test_the_approver_not_the_administrator_decides_in_the_copy(screen):
|
||||
assert "Wysłano do zatwierdzenia przez administratora." not in screen
|
||||
assert "czeka na zgodę administratora" not in screen
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Opt in with ATRIUM_RUN_INTEGRATION=1, like `test_integration.py`. Who sees what is decided in
|
||||
`services/skills.py` (skills are not org-tree nodes), so this suite pins that rule end to end: the
|
||||
visibility matrix, a firm skill's next version not becoming current until an approver approves
|
||||
visibility matrix, a firm skill's next version staying invisible until an administrator approves
|
||||
it, the `skills_firm_publish` switch, and the audit rows every write leaves. Then agents (a firm
|
||||
agent never pins a personal skill), T2 on export (`skills_firm_export`, for a skill and for an agent
|
||||
with everything it pins), import round trips keeping one content sum, a malicious pack answered as
|
||||
@@ -109,78 +109,21 @@ def test_a_firm_skill_is_everybodys_to_read(admin_client, client, owner, other,
|
||||
assert r.json()["current"]["n"] == 1
|
||||
assert any(s["id"] == sid for s in api.get(SKILLS, headers=who).json())
|
||||
|
||||
# Archiving stays with the editors; a new version from anybody else is a proposal (below).
|
||||
# Reading is not changing: anybody else may not touch it.
|
||||
r = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Hijacked\n"},
|
||||
headers=bearer(other["token"]))
|
||||
assert r.status_code == 403, r.text
|
||||
assert client.post(f"{SKILLS}/{sid}/archive",
|
||||
headers=bearer(other["token"])).status_code == 403
|
||||
|
||||
|
||||
def test_other_user_proposes_on_a_firm_skill(admin_client, client, owner, other, firm_skill):
|
||||
"""A proposal is a new version; it never moves the firm's current one, and a proposer's own
|
||||
publish is a request even where the firm publishes directly."""
|
||||
sid, me = firm_skill["id"], bearer(other["token"])
|
||||
with settings_set(admin_client, skills_firm_publish="direct"):
|
||||
r = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Proposal\n"}, headers=me)
|
||||
assert r.status_code == 201, r.text
|
||||
n = r.json()["n"]
|
||||
seen = client.get(f"{SKILLS}/{sid}", headers=me).json()
|
||||
assert seen["current"]["n"] == n - 1 and n in [v["n"] for v in seen["versions"]]
|
||||
assert (seen["editable"], seen["proposable"]) == (False, True)
|
||||
both = client.post(f"{SKILLS}/{sid}/versions", headers=me,
|
||||
json={"files": {}, "file_updates": {"a.md": "eA=="}})
|
||||
assert both.status_code == 422, both.text
|
||||
r = client.post(f"{SKILLS}/{sid}/publish", params={"n": n}, headers=me)
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
assert client.get(f"{SKILLS}/{sid}", headers=me).json()["current"]["n"] == n - 1
|
||||
_approve(admin_client, sid)
|
||||
|
||||
|
||||
def skill_v1(client, owner, sid) -> dict:
|
||||
return client.get(f"{SKILLS}/{sid}/versions/1", headers=bearer(owner["token"])).json()
|
||||
|
||||
|
||||
def test_base_n_builds_on_the_version_shown(admin_client, client, owner, other):
|
||||
"""Ruling 15: a save names the version it was made on. A proposer looking at the firm's current
|
||||
version builds on it, not on their own newer proposal; a version they cannot read is a 404."""
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
skill = _create(client, bearer(owner["token"]), body="# Approved\n")
|
||||
sid = skill["id"]
|
||||
assert client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"])).status_code == 200
|
||||
_approve(admin_client, sid)
|
||||
me = bearer(other["token"])
|
||||
mine = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Mine\n"}, headers=me)
|
||||
assert mine.status_code == 201 and mine.json()["n"] == 2, mine.text
|
||||
|
||||
# Without base_n the default stays (Ruling 9): the proposer's own newest version.
|
||||
default = client.post(f"{SKILLS}/{sid}/versions", json={"description": "Next."}, headers=me)
|
||||
assert default.status_code == 201 and default.json()["body"] == "# Mine\n", default.text
|
||||
|
||||
shown = client.post(f"{SKILLS}/{sid}/versions", headers=me,
|
||||
json={"base_n": 1, "file_updates": {"sprawdzanie.yaml": "eA=="}})
|
||||
assert shown.status_code == 201, shown.text
|
||||
assert shown.json()["n"] == 4 and shown.json()["body"] == "# Approved\n"
|
||||
assert shown.json()["description"] == skill_v1(client, owner, sid)["description"]
|
||||
assert [f["path"] for f in shown.json()["files"]] == ["sprawdzanie.yaml"]
|
||||
|
||||
owners = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Owner draft\n"},
|
||||
headers=bearer(owner["token"]))
|
||||
assert owners.status_code == 201, owners.text
|
||||
before = len(client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()["versions"])
|
||||
for n in (owners.json()["n"], 99):
|
||||
r = client.post(f"{SKILLS}/{sid}/versions", json={"base_n": n, "body": "# x\n"}, headers=me)
|
||||
assert r.status_code == 404, (n, r.text)
|
||||
after = len(client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()["versions"])
|
||||
assert after == before
|
||||
|
||||
|
||||
def test_a_missing_skill_is_404(client, owner):
|
||||
assert client.get(f"{SKILLS}/{uuid.uuid4()}", headers=bearer(owner["token"])).status_code == 404
|
||||
|
||||
|
||||
# ── publication ───────────────────────────────────────────────────────────────
|
||||
def test_a_new_firm_version_is_not_current_until_approved(admin_client, client, owner, other,
|
||||
def test_a_new_firm_version_stays_invisible_until_approved(admin_client, client, owner, other,
|
||||
firm_skill):
|
||||
"""Written is not published: until an approver says yes the firm's current version stays, and
|
||||
the new one is open to its editors only (Ruling 8); approved, it is the current one for all."""
|
||||
sid = firm_skill["id"]
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
r = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# NDA v2\n\nNew rule.\n"},
|
||||
@@ -192,9 +135,8 @@ def test_a_new_firm_version_is_not_current_until_approved(admin_client, client,
|
||||
out = client.get(f"{SKILLS}/{sid}", headers=bearer(other["token"])).json()
|
||||
return out["current"]["n"], [v["n"] for v in out["versions"]]
|
||||
|
||||
# Written is not published: somebody else's proposal (or the owner's) stays closed to
|
||||
# everybody who did not write it and cannot edit.
|
||||
assert seen_by_other()[0] == n - 1 and n not in seen_by_other()[1]
|
||||
# Written is not published: everybody else still reads the approved version, only.
|
||||
assert seen_by_other() == (n - 1, [n - 1])
|
||||
assert client.get(f"{SKILLS}/{sid}/versions/{n}",
|
||||
headers=bearer(other["token"])).status_code == 404
|
||||
owner_view = client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()
|
||||
@@ -204,7 +146,7 @@ def test_a_new_firm_version_is_not_current_until_approved(admin_client, client,
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
again = client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"]))
|
||||
assert again.status_code == 409 # already waiting
|
||||
assert seen_by_other()[0] == n - 1 and n not in seen_by_other()[1]
|
||||
assert seen_by_other() == (n - 1, [n - 1])
|
||||
|
||||
# The administrator's queue shows both sides of the diff.
|
||||
request = next(q for q in admin_client.get(REQUESTS).json() if q["item"]["id"] == sid)
|
||||
@@ -213,7 +155,7 @@ def test_a_new_firm_version_is_not_current_until_approved(admin_client, client,
|
||||
|
||||
decided = _approve(admin_client, sid)
|
||||
assert decided["status"] == "approved"
|
||||
assert seen_by_other()[0] == n and n in seen_by_other()[1]
|
||||
assert seen_by_other() == (n, [n])
|
||||
assert admin_client.post(f"{REQUESTS}/{request['id']}/approve").status_code == 409
|
||||
|
||||
|
||||
@@ -256,143 +198,6 @@ def test_direct_publication_is_the_administrators_switch(admin_client, client, o
|
||||
assert _audit(admin_client, "skill.publish_request", sid) == []
|
||||
|
||||
|
||||
# ── the firm's approver ───────────────────────────────────────────────────────
|
||||
def _workspace_id(admin_client) -> str:
|
||||
return next(u["id"] for u in admin_client.get("/api/v1/tree/containers").json()
|
||||
if u["kind"] == "workspace")
|
||||
|
||||
|
||||
def _grant(admin_client, node_id: str, person: dict, role: str) -> None:
|
||||
r = admin_client.put(f"/api/v1/nodes/{node_id}/grants",
|
||||
json={"user_id": person["id"], "role": role})
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
|
||||
def _pending_request(admin_client, client, author: dict, **over) -> tuple[dict, str]:
|
||||
"""A personal skill of `author` waiting for approval -> (skill, request id)."""
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
skill = _create(client, bearer(author["token"]), **over)
|
||||
r = client.post(f"{SKILLS}/{skill['id']}/publish", headers=bearer(author["token"]))
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
return skill, r.json()["request_id"]
|
||||
|
||||
|
||||
def test_an_approver_on_the_workspace_decides(admin_client, client, make_user, owner, other):
|
||||
approver = make_user("skills-approver")
|
||||
_grant(admin_client, _workspace_id(admin_client), approver, "approver")
|
||||
head = bearer(approver["token"])
|
||||
assert client.get(f"{SKILLS}/permissions", headers=head).json() == {"approve": True}
|
||||
assert client.get(f"{SKILLS}/permissions", headers=bearer(other["token"])).json() == {
|
||||
"approve": False}
|
||||
|
||||
skill, request_id = _pending_request(admin_client, client, owner)
|
||||
sid = skill["id"]
|
||||
# The approver is not an administrator and the skill is somebody's personal one, yet the
|
||||
# queue shows it and the version can be read: they cannot judge what they cannot open.
|
||||
assert client.get(f"{SKILLS}/{sid}", headers=head).status_code == 404
|
||||
queue = client.get(REQUESTS, headers=head)
|
||||
assert queue.status_code == 200 and any(q["id"] == request_id for q in queue.json())
|
||||
assert client.get(f"{SKILLS}/{sid}/versions/1", headers=head).status_code == 200
|
||||
|
||||
r = client.post(f"{REQUESTS}/{request_id}/approve", headers=head)
|
||||
assert r.status_code == 200 and r.json()["status"] == "approved", r.text
|
||||
firm = client.get(f"{SKILLS}/{sid}", headers=bearer(other["token"])).json()
|
||||
assert firm["scope"] == "firm" and firm["current"]["n"] == 1
|
||||
assert firm["current_version_id"] == firm["current"]["id"]
|
||||
|
||||
|
||||
def test_a_decided_request_opens_nothing_more_to_an_approver(admin_client, client, make_user,
|
||||
owner):
|
||||
approver = make_user("skills-approver-2")
|
||||
_grant(admin_client, _workspace_id(admin_client), approver, "approver")
|
||||
head = bearer(approver["token"])
|
||||
skill, request_id = _pending_request(admin_client, client, owner)
|
||||
sid = skill["id"]
|
||||
assert client.get(f"{SKILLS}/{sid}/versions/1", headers=head).status_code == 200
|
||||
r = client.post(f"{REQUESTS}/{request_id}/decline", headers=head)
|
||||
assert r.status_code == 200 and r.json()["status"] == "declined", r.text
|
||||
assert client.get(f"{SKILLS}/{sid}/versions/1", headers=head).status_code == 404
|
||||
|
||||
|
||||
def test_an_approver_on_a_group_only_may_not(admin_client, client, make_user, owner):
|
||||
person = make_user("skills-group-approver")
|
||||
group = admin_client.post("/api/v1/nodes", json={
|
||||
"kind": "group", "name": f"Skills {RUN}-{uuid.uuid4().hex[:4]}",
|
||||
"parent_id": _workspace_id(admin_client)}).json()
|
||||
_grant(admin_client, group["id"], person, "approver")
|
||||
head = bearer(person["token"])
|
||||
_, request_id = _pending_request(admin_client, client, owner)
|
||||
assert client.get(f"{SKILLS}/permissions", headers=head).json() == {"approve": False}
|
||||
assert client.get(REQUESTS, headers=head).status_code == 403
|
||||
assert client.post(f"{REQUESTS}/{request_id}/approve", headers=head).status_code == 403
|
||||
|
||||
|
||||
def test_an_editor_may_not(admin_client, client, make_user, owner):
|
||||
person = make_user("skills-editor")
|
||||
_grant(admin_client, _workspace_id(admin_client), person, "editor")
|
||||
head = bearer(person["token"])
|
||||
_, request_id = _pending_request(admin_client, client, owner)
|
||||
assert client.get(REQUESTS, headers=head).status_code == 403
|
||||
assert client.post(f"{REQUESTS}/{request_id}/approve", headers=head).status_code == 403
|
||||
|
||||
|
||||
def test_an_approver_may_not_decide_their_own_request(admin_client, client, make_user):
|
||||
approver = make_user("skills-approver-3")
|
||||
_grant(admin_client, _workspace_id(admin_client), approver, "approver")
|
||||
head = bearer(approver["token"])
|
||||
skill, request_id = _pending_request(admin_client, client, approver)
|
||||
for verb in ("approve", "decline"):
|
||||
r = client.post(f"{REQUESTS}/{request_id}/{verb}", headers=head)
|
||||
assert r.status_code == 403 and "cannot decide your own request" in r.text, r.text
|
||||
# An administrator may, whoever filed it.
|
||||
assert admin_client.post(f"{REQUESTS}/{request_id}/approve").status_code == 200
|
||||
|
||||
|
||||
def test_an_approver_may_not_decide_a_request_for_a_version_they_wrote(admin_client, client,
|
||||
make_user, owner):
|
||||
"""Four eyes on the author too: the owner puts forward an approver's proposal (an editor's
|
||||
publish of a non-editor's version is a request, Ruling 10); its author may not decide it,
|
||||
another approver may."""
|
||||
author, second = make_user("skills-approver-author"), make_user("skills-approver-second")
|
||||
for person in (author, second):
|
||||
_grant(admin_client, _workspace_id(admin_client), person, "approver")
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
skill = _create(client, bearer(owner["token"]))
|
||||
sid = skill["id"]
|
||||
assert client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"])).status_code == 200
|
||||
_approve(admin_client, sid)
|
||||
proposal = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# The approver's idea\n"},
|
||||
headers=bearer(author["token"]))
|
||||
assert proposal.status_code == 201, proposal.text
|
||||
n = proposal.json()["n"]
|
||||
r = client.post(f"{SKILLS}/{sid}/publish", params={"n": n}, headers=bearer(owner["token"]))
|
||||
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
|
||||
request_id = r.json()["request_id"]
|
||||
|
||||
for verb in ("approve", "decline"):
|
||||
r = client.post(f"{REQUESTS}/{request_id}/{verb}", headers=bearer(author["token"]))
|
||||
assert r.status_code == 403 and "cannot decide your own request" in r.text, r.text
|
||||
r = client.post(f"{REQUESTS}/{request_id}/approve", headers=bearer(second["token"]))
|
||||
assert r.status_code == 200 and r.json()["status"] == "approved", r.text
|
||||
assert client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()["current"]["n"] == n
|
||||
|
||||
|
||||
def test_only_an_approver_reads_a_version_waiting_in_a_request(admin_client, client, make_user,
|
||||
owner):
|
||||
"""The approver's read exception is the widest new read path: a version waiting in a request on
|
||||
somebody's PERSONAL skill opens, version and file alike, to an approver and to nobody else."""
|
||||
approver, plain = make_user("skills-approver-reader"), make_user("skills-plain")
|
||||
_grant(admin_client, _workspace_id(admin_client), approver, "approver")
|
||||
# "# Zasady\n", base64.
|
||||
skill, _ = _pending_request(admin_client, client, owner, files={"zasady.md": "IyBaYXNhZHkK"})
|
||||
version = f"{SKILLS}/{skill['id']}/versions/1"
|
||||
for path in (version, f"{version}/files/zasady.md"):
|
||||
r = client.get(path, headers=bearer(plain["token"]))
|
||||
assert r.status_code == 404, (path, r.text)
|
||||
r = client.get(path, headers=bearer(approver["token"]))
|
||||
assert r.status_code == 200, (path, r.text)
|
||||
|
||||
|
||||
# ── the audit ─────────────────────────────────────────────────────────────────
|
||||
def test_every_write_leaves_one_audit_row(admin_client, client, owner):
|
||||
with settings_set(admin_client, skills_firm_publish="approval"):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Revision 0015: the SQL that freezes skill and agent versions for the runtime role (DB-free)."""
|
||||
"""Revision 0010: the SQL that freezes skill and agent versions for the runtime role (DB-free)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
@@ -20,7 +20,7 @@ def revision():
|
||||
return module
|
||||
|
||||
|
||||
def test_it_follows_the_workflow_retirement(revision):
|
||||
def test_it_follows_the_model_providers(revision):
|
||||
assert (revision.revision, revision.down_revision) == ("0015", "0014")
|
||||
|
||||
|
||||
@@ -53,8 +53,3 @@ def test_a_role_that_is_not_a_plain_name_is_refused(revision):
|
||||
|
||||
with pytest.raises(GrantsRefused):
|
||||
revision.immutable_versions_sql('app"; DROP TABLE skill; --')
|
||||
|
||||
|
||||
def test_the_sweep_keeps_the_event_log_append_only(revision):
|
||||
# 0011's warning: a later revision re-running the sweep without it re-opens the log.
|
||||
assert "module_event" in revision.APPEND_ONLY
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""`services/skills.py`: the visibility rule, version numbering and content checks (DB-free)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import uuid
|
||||
import zipfile
|
||||
@@ -9,9 +8,8 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.enums import NodeRole
|
||||
from app.errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import AppUser, Skill, SkillFile
|
||||
from app.models import Skill
|
||||
from app.services import skill_pack, skills
|
||||
from app.services.skill_pack import PackRejected
|
||||
|
||||
@@ -54,257 +52,17 @@ def test_someone_elses_personal_skill_is_a_404_not_a_403():
|
||||
skills.archive_skill(db, user, db.skill.id, ip=None)
|
||||
|
||||
|
||||
def test_a_firm_skill_is_archived_only_by_its_editors():
|
||||
def test_a_firm_skill_is_changed_only_by_its_editors():
|
||||
db = _Db(_skill("firm"))
|
||||
with pytest.raises(AuthorizationError):
|
||||
skills.archive_skill(db, OTHER, db.skill.id, ip=None)
|
||||
skills.new_version(db, OTHER, db.skill.id, {}, ip=None)
|
||||
|
||||
|
||||
def _ver(creator, n):
|
||||
return SimpleNamespace(id=uuid.uuid4(), n=n, created_by=creator.id, description="Opis",
|
||||
body_md="Treść", license="MIT", meta={})
|
||||
|
||||
|
||||
def test_an_editor_reads_every_firm_version():
|
||||
v1, v2 = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=v1.id)
|
||||
assert skills.readable_version_ids(OWNER, skill, [v1, v2]) == {v1.id, v2.id}
|
||||
assert skills.readable_version_ids(ADMIN, skill, [v1, v2]) == {v1.id, v2.id}
|
||||
|
||||
|
||||
def test_a_proposer_reads_the_current_version_and_their_own_only():
|
||||
draft, current, mine, theirs = _ver(OWNER, 1), _ver(OWNER, 2), _ver(OTHER, 3), _ver(ADMIN, 4)
|
||||
skill = _skill("firm", current=current.id)
|
||||
# The owner's earlier personal draft (1) and somebody else's proposal (4) stay closed.
|
||||
assert skills.readable_version_ids(OTHER, skill, [draft, current, mine, theirs]) == {
|
||||
current.id, mine.id}
|
||||
|
||||
|
||||
class _VersionDb:
|
||||
"""What `new_version` and `publish_skill` touch. A select is answered by what it filters on
|
||||
(read off its bound parameters): `created_by` narrows to that author, a file query names its
|
||||
version; whatever is added is what a new version stored."""
|
||||
|
||||
def __init__(self, skill, versions, files=None):
|
||||
self.skill, self.versions, self.files = skill, list(versions), files or {}
|
||||
self.users = {u.id: u for u in (OWNER, OTHER, ADMIN)}
|
||||
self.added, self.params = [], []
|
||||
|
||||
def get(self, model, key):
|
||||
if model is Skill:
|
||||
return self.skill
|
||||
if model is AppUser:
|
||||
return self.users.get(key)
|
||||
return next((v for v in self.versions if v.id == key), None)
|
||||
|
||||
def scalar(self, stmt):
|
||||
params = stmt.compile().params
|
||||
self.params.append(params)
|
||||
if "kind_1" in params:
|
||||
return None # the pending-request lookup: nothing waits yet
|
||||
found = self.versions
|
||||
if "created_by_1" in params:
|
||||
found = [v for v in found if v.created_by == params["created_by_1"]]
|
||||
if "n_1" in params:
|
||||
found = [v for v in found if v.n == params["n_1"]]
|
||||
return max(found, key=lambda v: v.n, default=None)
|
||||
|
||||
def scalars(self, stmt):
|
||||
wanted = next((v for v in stmt.compile().params.values() if v in self.files), None)
|
||||
if wanted is not None:
|
||||
return iter(self.files[wanted])
|
||||
return iter(a for a in self.added if isinstance(a, SkillFile))
|
||||
|
||||
def add(self, row):
|
||||
self.added.append(row)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
def _stored(path, data):
|
||||
return SimpleNamespace(path=path, content=data)
|
||||
|
||||
|
||||
def _sha(out):
|
||||
return {f["path"]: f["sha256"] for f in out["files"]}
|
||||
|
||||
|
||||
def _h(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def test_anyone_proposes_on_a_firm_skill_without_moving_current(audited):
|
||||
v1 = _ver(OWNER, 1)
|
||||
skill = _skill("firm", current=v1.id)
|
||||
out = skills.new_version(_VersionDb(skill, [v1]), OTHER, skill.id, {"body": "Nowa"}, ip=None)
|
||||
assert out["n"] == 2 and skill.current_version_id == v1.id
|
||||
assert audited == ["skill.version"]
|
||||
|
||||
|
||||
def test_a_proposal_does_not_rename_a_firm_skill(audited):
|
||||
v1 = _ver(OWNER, 1)
|
||||
skill = _skill("firm", current=v1.id)
|
||||
skills.new_version(_VersionDb(skill, [v1]), OTHER, skill.id, {"name": "Hijacked"}, ip=None)
|
||||
assert skill.name == "NDA"
|
||||
|
||||
|
||||
def test_nobody_proposes_on_someone_elses_personal_skill():
|
||||
db = _VersionDb(_skill("personal"), [_ver(OWNER, 1)])
|
||||
for user in (OTHER, ADMIN):
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.new_version(db, user, db.skill.id, {}, ip=None)
|
||||
|
||||
|
||||
def test_an_archived_firm_skill_takes_no_proposal():
|
||||
skill = _skill("firm")
|
||||
skill.status = "archived"
|
||||
assert not skills.can_propose(OTHER, skill)
|
||||
with pytest.raises(AuthorizationError):
|
||||
skills.new_version(_VersionDb(skill, [_ver(OWNER, 1)]), OTHER, skill.id, {}, ip=None)
|
||||
|
||||
|
||||
def test_file_updates_keep_the_other_files_byte_identical(audited):
|
||||
note, old_yaml = "Notatka\n".encode(), b"wersja_formatu: 1\n"
|
||||
v1 = _ver(OWNER, 1)
|
||||
skill = _skill("firm", current=v1.id)
|
||||
db = _VersionDb(skill, [v1], {v1.id: [_stored("notatka.md", note),
|
||||
_stored("sprawdzanie.yaml", old_yaml)]})
|
||||
new_yaml = b"wersja_formatu: 1\nkroki: []\n"
|
||||
out = skills.new_version(db, OTHER, skill.id, {"file_updates": {"sprawdzanie.yaml": new_yaml}},
|
||||
ip=None)
|
||||
assert _sha(out) == {"notatka.md": _h(note), "sprawdzanie.yaml": _h(new_yaml)}
|
||||
|
||||
|
||||
def test_an_editors_save_does_not_inherit_a_strangers_proposal(audited):
|
||||
approved, proposal = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, proposal], {
|
||||
approved.id: [_stored("notatka.md", b"approved")],
|
||||
proposal.id: [_stored("notatka.md", b"proposal"), _stored("extra.md", b"sneaky")]})
|
||||
out = skills.new_version(db, OWNER, skill.id, {"file_updates": {"b.md": b"b"}}, ip=None)
|
||||
assert _sha(out) == {"notatka.md": _h(b"approved"), "b.md": _h(b"b")}
|
||||
|
||||
|
||||
def test_a_proposers_second_save_builds_on_their_first(audited):
|
||||
approved, first = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, first], {
|
||||
approved.id: [_stored("notatka.md", b"approved")],
|
||||
first.id: [_stored("notatka.md", b"mine")]})
|
||||
out = skills.new_version(db, OTHER, skill.id, {"file_updates": {"b.md": b"b"}}, ip=None)
|
||||
assert out["n"] == 3 and _sha(out) == {"notatka.md": _h(b"mine"), "b.md": _h(b"b")}
|
||||
|
||||
|
||||
def test_a_proposers_save_after_a_newer_approval_builds_on_the_approved_one(audited):
|
||||
first, approved = _ver(OTHER, 1), _ver(OWNER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [first, approved], {
|
||||
first.id: [_stored("notatka.md", b"old mine")],
|
||||
approved.id: [_stored("notatka.md", b"approved")]})
|
||||
out = skills.new_version(db, OTHER, skill.id, {}, ip=None)
|
||||
assert _sha(out) == {"notatka.md": _h(b"approved")}
|
||||
|
||||
|
||||
def test_base_n_builds_on_the_version_shown_even_over_a_newer_own_proposal(audited):
|
||||
"""Ruling 15: the editor saves on top of the version the person was looking at. Without
|
||||
`base_n` this save would take the proposer's own v2 as its base and silently revert it."""
|
||||
approved, mine = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, mine], {
|
||||
approved.id: [_stored("notatka.md", b"approved")],
|
||||
mine.id: [_stored("notatka.md", b"mine")]})
|
||||
out = skills.new_version(db, OTHER, skill.id,
|
||||
{"base_n": 1, "file_updates": {"sprawdzanie.yaml": b"y"}}, ip=None)
|
||||
assert out["n"] == 3
|
||||
assert _sha(out) == {"notatka.md": _h(b"approved"), "sprawdzanie.yaml": _h(b"y")}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("base_n", [2, 9])
|
||||
def test_base_n_on_a_version_the_actor_cannot_read_is_a_404_and_adds_nothing(base_n):
|
||||
"""v2 is the owner's unpublished version of a firm skill: a proposer may not read it, so they
|
||||
may not build on it either (9: no such version). Same 404 as reading it."""
|
||||
approved, owners_draft = _ver(OWNER, 1), _ver(OWNER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, owners_draft])
|
||||
with pytest.raises(NotFoundError) as err:
|
||||
skills.new_version(db, OTHER, skill.id, {"base_n": base_n, "file_updates": {"a.md": b"x"}},
|
||||
ip=None)
|
||||
assert str(err.value) == "Version not found."
|
||||
assert db.added == []
|
||||
|
||||
|
||||
def test_an_absent_base_n_keeps_the_default_base(audited):
|
||||
"""`base_n: None` is what the router passes when the field is left out: Ruling 9 applies."""
|
||||
approved, first = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, first], {
|
||||
approved.id: [_stored("notatka.md", b"approved")],
|
||||
first.id: [_stored("notatka.md", b"mine")]})
|
||||
out = skills.new_version(db, OTHER, skill.id, {"base_n": None, "file_updates": {"b.md": b"b"}},
|
||||
ip=None)
|
||||
assert _sha(out) == {"notatka.md": _h(b"mine"), "b.md": _h(b"b")}
|
||||
|
||||
|
||||
def test_files_and_file_updates_together_are_refused():
|
||||
v1 = _ver(OWNER, 1)
|
||||
skill = _skill("firm", current=v1.id)
|
||||
with pytest.raises(ValidationError) as err:
|
||||
skills.new_version(_VersionDb(skill, [v1]), OTHER, skill.id,
|
||||
{"files": {}, "file_updates": {"a.md": b"x"}}, ip=None)
|
||||
assert str(err.value) == "Send files or file_updates, not both."
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def direct(monkeypatch):
|
||||
monkeypatch.setattr(skills.settings, "get", lambda _db, _key: "direct")
|
||||
|
||||
|
||||
def test_a_proposers_publish_is_a_request_even_when_direct(direct, audited):
|
||||
approved, mine = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
out = skills.publish_skill(_VersionDb(skill, [approved, mine]), OTHER, skill.id, 2, ip=None)
|
||||
assert out["status"] == "pending" and skill.current_version_id == approved.id
|
||||
assert audited == ["skill.publish_request"]
|
||||
|
||||
|
||||
def test_a_non_editor_cannot_publish_a_version_they_did_not_write(direct, audited):
|
||||
draft, current = _ver(OWNER, 1), _ver(OWNER, 2)
|
||||
skill = _skill("firm", current=current.id)
|
||||
db = _VersionDb(skill, [draft, current])
|
||||
for n in (1, 2, 9):
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.publish_skill(db, OTHER, skill.id, n, ip=None)
|
||||
assert not db.added and audited == []
|
||||
|
||||
|
||||
def test_an_editors_publish_of_their_own_version_stays_direct(direct, audited):
|
||||
approved, mine = _ver(OWNER, 1), _ver(ADMIN, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
out = skills.publish_skill(_VersionDb(skill, [approved, mine]), ADMIN, skill.id, 2, ip=None)
|
||||
assert out["status"] == "published" and skill.current_version_id == mine.id
|
||||
|
||||
|
||||
def test_an_editor_publishing_a_proposal_files_a_request_even_when_direct(direct, audited):
|
||||
approved, proposal = _ver(OWNER, 1), _ver(OTHER, 2)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
out = skills.publish_skill(_VersionDb(skill, [approved, proposal]), OWNER, skill.id, 2, ip=None)
|
||||
assert out["status"] == "pending" and skill.current_version_id == approved.id
|
||||
|
||||
|
||||
def test_publish_without_n_picks_the_actors_own_newest_version(direct, audited):
|
||||
approved, proposal, own = _ver(OWNER, 1), _ver(OTHER, 2), _ver(OWNER, 3)
|
||||
skill = _skill("firm", current=approved.id)
|
||||
db = _VersionDb(skill, [approved, proposal, own, _ver(OTHER, 4)])
|
||||
out = skills.publish_skill(db, OWNER, skill.id, ip=None)
|
||||
assert out["status"] == "published" and skill.current_version_id == own.id
|
||||
|
||||
|
||||
def test_skill_out_says_who_may_propose():
|
||||
firm = _skill("firm")
|
||||
assert skills.skill_out(OTHER, firm)["proposable"] is True
|
||||
assert skills.skill_out(OTHER, firm)["editable"] is False
|
||||
assert skills.skill_out(OTHER, _skill("personal"))["proposable"] is False
|
||||
def test_a_non_editor_reads_only_the_current_version():
|
||||
approved, pending = uuid.uuid4(), uuid.uuid4()
|
||||
skill = _skill("firm", current=approved)
|
||||
assert skills.readable_version_ids(OTHER, skill, [approved, pending]) == {approved}
|
||||
assert skills.readable_version_ids(OWNER, skill, [approved, pending]) == {approved, pending}
|
||||
|
||||
|
||||
def test_next_n():
|
||||
@@ -368,8 +126,8 @@ def audited(monkeypatch):
|
||||
return actions
|
||||
|
||||
|
||||
def _version(n=1, by=OWNER):
|
||||
return SimpleNamespace(id=uuid.uuid4(), n=n, created_by=by.id)
|
||||
def _version(n=1):
|
||||
return SimpleNamespace(id=uuid.uuid4(), n=n)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["approval", "direct"])
|
||||
@@ -410,122 +168,13 @@ def test_approving_an_older_version_is_refused():
|
||||
assert not skills.refuses_older(_skill("personal"), None, _version(1))
|
||||
|
||||
|
||||
class _ApproverDb:
|
||||
"""What `may_approve` and `decide_publish` touch: the workspace nodes, the locked request, the
|
||||
item and its versions. `roles` maps a node to the role the resolver would give this person."""
|
||||
|
||||
def __init__(self, nodes=(), request=None, item=None, version=None):
|
||||
self.nodes, self.request, self.item, self.version = list(nodes), request, item, version
|
||||
self.added = []
|
||||
|
||||
def scalars(self, _stmt):
|
||||
return iter(self.nodes)
|
||||
|
||||
def scalar(self, _stmt):
|
||||
return self.request
|
||||
|
||||
def get(self, model, _id):
|
||||
return self.version if model is skills.SkillVersion else self.item
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
def _roles(monkeypatch, granted):
|
||||
"""The resolver answers `granted` for the node named in it, nothing elsewhere."""
|
||||
monkeypatch.setattr(skills.authz, "effective_role",
|
||||
lambda _db, _user, node: granted.get(node.name))
|
||||
|
||||
|
||||
# `_ReadDb.scalars` serves nodes and files alike, so the node also looks like a file row.
|
||||
WORKSPACE = SimpleNamespace(name="firm", kind="workspace", path="p", media_type="t", size=1,
|
||||
sha256="0" * 64)
|
||||
GROUP = SimpleNamespace(name="legal", kind="group")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("granted, allowed", [
|
||||
({"firm": NodeRole.approver}, True), # the role the firm's workspace gives
|
||||
({"firm": NodeRole.manager}, True), # and anything above it
|
||||
({"firm": NodeRole.editor}, False), # an editor writes, never decides
|
||||
({"firm": NodeRole.viewer}, False),
|
||||
({}, False),
|
||||
@pytest.mark.parametrize("call", [
|
||||
lambda: skills.decide_publish(None, OTHER, uuid.uuid4(), approve=True),
|
||||
lambda: skills.pending_publish_requests(None, OTHER),
|
||||
])
|
||||
def test_an_approver_on_the_workspace_decides(monkeypatch, granted, allowed):
|
||||
_roles(monkeypatch, granted)
|
||||
assert skills.may_approve(_ApproverDb([WORKSPACE]), OTHER) is allowed
|
||||
|
||||
|
||||
def test_an_approver_on_a_group_only_may_not(monkeypatch):
|
||||
# The query asks for workspace nodes only, so a role that exists on a group never gets asked.
|
||||
_roles(monkeypatch, {"legal": NodeRole.approver})
|
||||
assert skills.may_approve(_ApproverDb([WORKSPACE]), OTHER) is False
|
||||
def test_only_an_administrator_decides(call):
|
||||
with pytest.raises(AuthorizationError):
|
||||
skills.decide_publish(_ApproverDb([WORKSPACE]), OTHER, uuid.uuid4(), approve=True)
|
||||
|
||||
|
||||
def test_an_editor_may_not(monkeypatch):
|
||||
_roles(monkeypatch, {"firm": NodeRole.editor})
|
||||
for call in (lambda db: skills.decide_publish(db, OTHER, uuid.uuid4(), approve=True),
|
||||
lambda db: skills.pending_publish_requests(db, OTHER)):
|
||||
with pytest.raises(AuthorizationError):
|
||||
call(_ApproverDb([WORKSPACE]))
|
||||
|
||||
|
||||
def test_an_administrator_needs_no_grant():
|
||||
assert skills.may_approve(_ApproverDb(), ADMIN) is True
|
||||
|
||||
|
||||
def _request(requested_by):
|
||||
return SimpleNamespace(id=uuid.uuid4(), kind="skill", status="pending", version_id=uuid.uuid4(),
|
||||
requested_by=requested_by.id, decided_by=None, decided_at=None,
|
||||
note=None)
|
||||
|
||||
|
||||
def test_an_approver_may_not_decide_their_own_request(monkeypatch, audited):
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
req = _request(OTHER)
|
||||
db = _ApproverDb([WORKSPACE], request=req)
|
||||
with pytest.raises(AuthorizationError, match="You cannot decide your own request."):
|
||||
skills.decide_publish(db, OTHER, req.id, approve=True)
|
||||
assert req.status == "pending" and not audited
|
||||
|
||||
|
||||
def test_an_approver_may_not_decide_a_request_for_a_version_they_wrote(monkeypatch, audited):
|
||||
"""Four eyes on the author as well: an editor's publish of an approver's proposal is a request
|
||||
(Ruling 10), and the approver who wrote that version is not the second pair of eyes on it."""
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
version = _version(2, by=OTHER)
|
||||
skill = _skill("firm")
|
||||
req = _request(OWNER)
|
||||
monkeypatch.setattr(skills, "_resolve", lambda _db, _req: (skill, version))
|
||||
db = _ApproverDb([WORKSPACE], request=req, item=skill, version=version)
|
||||
for approve in (True, False):
|
||||
with pytest.raises(AuthorizationError, match="You cannot decide your own request."):
|
||||
skills.decide_publish(db, OTHER, req.id, approve=approve)
|
||||
assert req.status == "pending" and skill.current_version_id is None and not audited
|
||||
|
||||
|
||||
def test_an_admin_still_decides_their_own_request(monkeypatch, audited):
|
||||
version = _version()
|
||||
skill = _skill("personal")
|
||||
req = _request(ADMIN)
|
||||
monkeypatch.setattr(skills, "_request_out", lambda _db, _req: {})
|
||||
monkeypatch.setattr(skills, "_resolve", lambda _db, _req: (skill, version))
|
||||
db = _ApproverDb(request=req, item=skill, version=version)
|
||||
skills.decide_publish(db, ADMIN, req.id, approve=True)
|
||||
assert req.status == "approved" and skill.current_version_id == db.version.id
|
||||
|
||||
|
||||
def test_an_approver_decides_somebody_elses_request(monkeypatch, audited):
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
version = _version()
|
||||
skill = _skill("personal")
|
||||
req = _request(OWNER)
|
||||
monkeypatch.setattr(skills, "_request_out", lambda _db, _req: {})
|
||||
monkeypatch.setattr(skills, "_resolve", lambda _db, _req: (skill, version))
|
||||
db = _ApproverDb([WORKSPACE], request=req, item=skill, version=version)
|
||||
skills.decide_publish(db, OTHER, req.id, approve=True)
|
||||
assert (req.status, req.decided_by, skill.scope) == ("approved", OTHER.id, "firm")
|
||||
call()
|
||||
|
||||
|
||||
def test_an_imported_slug_takes_the_first_free_number():
|
||||
@@ -563,7 +212,7 @@ def test_an_agent_pack_or_a_pack_without_skill_md_is_not_a_skill_import():
|
||||
# ---- agents ----
|
||||
|
||||
def _sv(skill, current=False):
|
||||
version = SimpleNamespace(id=uuid.uuid4(), skill_id=skill.id, n=1, created_by=OWNER.id)
|
||||
version = SimpleNamespace(id=uuid.uuid4(), skill_id=skill.id, n=1)
|
||||
if current:
|
||||
skill.current_version_id = version.id
|
||||
return version
|
||||
@@ -642,110 +291,3 @@ def test_an_agent_file_name_is_ascii_kebab():
|
||||
assert skills._slugish("Asystent umów NDA!") == "asystent-umow-nda"
|
||||
assert skills._slugish("Łódź") == "lodz"
|
||||
assert skills._slugish("—") == "agent"
|
||||
|
||||
|
||||
# ---- reading a version for the checking service ------------------------------------------------
|
||||
|
||||
class _ReadDb:
|
||||
"""`get` answers the skill; `scalar` the queued answers in order (version, then file);
|
||||
`scalars` the files of the version."""
|
||||
|
||||
def __init__(self, skill, scalars_=(), files=()):
|
||||
self.skill, self._queue, self._files = skill, list(scalars_), list(files)
|
||||
|
||||
def get(self, _model, _id):
|
||||
return self.skill
|
||||
|
||||
def scalar(self, _stmt):
|
||||
return self._queue.pop(0)
|
||||
|
||||
def scalars(self, _stmt):
|
||||
return iter(self._files)
|
||||
|
||||
|
||||
def _full_version(n=1):
|
||||
return SimpleNamespace(id=uuid.uuid4(), n=n, description="d", body_md="b", license="l",
|
||||
meta={}, content_sha256="0" * 64, provenance=None,
|
||||
created_at=None, created_by=OWNER.id)
|
||||
|
||||
|
||||
def test_version_says_whether_it_is_the_firms_approved_one():
|
||||
approved, proposal = _full_version(1), _full_version(2)
|
||||
firm = _skill("firm", current=approved.id)
|
||||
out = skills.get_version(_ReadDb(firm, [approved]), OWNER, firm.id, 1)
|
||||
assert out["approved_for_firm"] is True and out["skill_name"] == "NDA"
|
||||
out = skills.get_version(_ReadDb(firm, [proposal]), OWNER, firm.id, 2)
|
||||
assert out["approved_for_firm"] is False
|
||||
personal = _skill("personal", current=approved.id)
|
||||
out = skills.get_version(_ReadDb(personal, [approved]), OWNER, personal.id, 1)
|
||||
assert out["approved_for_firm"] is False
|
||||
|
||||
|
||||
def test_an_archived_firm_skill_has_no_approved_version():
|
||||
"""Archiving is the firm's kill switch: the checking service reads `approved_for_firm` fresh on
|
||||
every real-contract order, so an archived skill stops serving real contracts at once."""
|
||||
approved = _full_version(1)
|
||||
firm = _skill("firm", current=approved.id)
|
||||
firm.status = "archived"
|
||||
out = skills.get_version(_ReadDb(firm, [approved]), OWNER, firm.id, 1)
|
||||
assert out["approved_for_firm"] is False
|
||||
|
||||
|
||||
def test_get_file_returns_the_bytes_of_a_readable_version():
|
||||
version = _full_version()
|
||||
skill = _skill("firm", current=version.id)
|
||||
stored = SimpleNamespace(media_type="application/yaml", content=b"steps: []\n")
|
||||
db = _ReadDb(skill, [version, stored])
|
||||
assert skills.get_file(db, OTHER, skill.id, 1, "sprawdzanie.yaml") == (
|
||||
"application/yaml", b"steps: []\n")
|
||||
|
||||
|
||||
def test_get_file_is_404_for_a_version_the_person_cannot_read():
|
||||
pending = _full_version(2)
|
||||
skill = _skill("firm", current=uuid.uuid4())
|
||||
stored = SimpleNamespace(media_type="application/yaml", content=b"x")
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.get_file(_ReadDb(skill, [pending, None, stored]), OTHER, skill.id, 2,
|
||||
"sprawdzanie.yaml")
|
||||
|
||||
|
||||
def test_get_file_is_404_for_a_missing_path():
|
||||
version = _full_version()
|
||||
skill = _skill("firm", current=version.id)
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.get_file(_ReadDb(skill, [version, None]), OTHER, skill.id, 1, "nope.yaml")
|
||||
|
||||
|
||||
def test_an_approver_reads_a_version_in_a_pending_request(monkeypatch):
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
pending = _full_version(2)
|
||||
skill = _skill("firm", current=uuid.uuid4())
|
||||
stored = SimpleNamespace(media_type="application/yaml", content=b"x")
|
||||
# version, then a pending request for it; the roster of workspace nodes answers `scalars`
|
||||
db = _ReadDb(skill, [pending, uuid.uuid4(), stored], files=[WORKSPACE])
|
||||
assert skills.get_file(db, OTHER, skill.id, 2, "sprawdzanie.yaml") == ("application/yaml", b"x")
|
||||
|
||||
|
||||
def test_an_approver_reads_a_pending_version_of_a_personal_skill(monkeypatch):
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
pending = _full_version(1)
|
||||
skill = _skill("personal")
|
||||
db = _ReadDb(skill, [pending, uuid.uuid4()], files=[WORKSPACE])
|
||||
assert skills.get_version(db, OTHER, skill.id, 1)["n"] == 1
|
||||
|
||||
|
||||
def test_a_pending_request_grants_nothing_to_somebody_who_may_not_decide(monkeypatch):
|
||||
_roles(monkeypatch, {"firm": NodeRole.editor})
|
||||
skill = _skill("personal")
|
||||
db = _ReadDb(skill, [_full_version(1), uuid.uuid4()], files=[WORKSPACE])
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.get_version(db, OTHER, skill.id, 1)
|
||||
|
||||
|
||||
def test_a_decided_request_grants_nothing_to_an_approver(monkeypatch):
|
||||
_roles(monkeypatch, {"firm": NodeRole.approver})
|
||||
skill = _skill("firm", current=uuid.uuid4())
|
||||
# the lookup filters on status = pending, so a decided request is the same as none: None
|
||||
db = _ReadDb(skill, [_full_version(2), None], files=[WORKSPACE])
|
||||
with pytest.raises(NotFoundError):
|
||||
skills.get_version(db, OTHER, skill.id, 2)
|
||||
|
||||
+3
-4
@@ -38,10 +38,9 @@ MODULES_DIR=./modules
|
||||
# Its optional OCR worker is a second profile, `ocr`, which only means something with `insider` on.
|
||||
# Arbiter (contract analysis, built from the arbiter submodule's apps/arbiter) ships switched off too,
|
||||
# under the `arbiter` profile (deploy/RUNBOOK-arbiter.md).
|
||||
# Lexicon and Agora (the split plan's M2-M3) the same, each under a profile of its own name
|
||||
# (deploy/RUNBOOK-m2-m4.md); Parafa and Scribe (M6, M7) likewise (deploy/RUNBOOK-m6-m7.md),
|
||||
# and Workflow, the approval engine (deploy/RUNBOOK-workflow.md).
|
||||
# COMPOSE_PROFILES=insider,arbiter,lexicon,agora,parafa,scribe,workflow
|
||||
# Lexicon, Agora and Panorama (the split plan's M2-M4) the same, each under a profile of its own name
|
||||
# (deploy/RUNBOOK-m2-m4.md); Parafa and Scribe (M6, M7) likewise (deploy/RUNBOOK-m6-m7.md).
|
||||
# COMPOSE_PROFILES=insider,arbiter,lexicon,agora,panorama,parafa,scribe
|
||||
# Parafa's signer: a directory holding the operator's PKCS#12 signing file and its passphrase file,
|
||||
# mounted READ-ONLY into parafa-backend at /run/parafa-signer (env/parafa.env names the files).
|
||||
# Relative to this directory; empty or missing = signing unconfigured (409 signing_unconfigured).
|
||||
|
||||
+6
-14
@@ -60,29 +60,21 @@ deployment, and the kit in this directory does the per-app work for all four app
|
||||
| Arbiter (off by default) | `arbiter` | `arbiter_migrator`, `arbiter_app` | none | `audit_log`, `analysis_signoff`, `agent_version`, `frozen_card` append-only; `analysis` never deleted |
|
||||
| Lexicon (off by default) | `lexicon` | `lexicon_migrator`, `lexicon_app` | none | `audit_log` append-only |
|
||||
| Agora (off by default) | `agora` | `agora_migrator`, `agora_app` | none | `audit_log`, `module_event`, `module_event_receipt` append-only; `negotiation_room`, `negotiation_round`, `negotiation_comment` never deleted |
|
||||
| Panorama (off by default) | `panorama` | `panorama_migrator`, `panorama_app` | none | `audit_log` append-only |
|
||||
| Parafa (off by default) | `parafa` | `parafa_migrator`, `parafa_app` | none | `audit_log`, `module_event`, `module_event_receipt` append-only; `signing_request` never deleted |
|
||||
| Scribe (off by default) | `scribe` | `scribe_migrator`, `scribe_app` | none | `audit_log` append-only; `draft_export` never deleted |
|
||||
| Workflow (off by default) | `workflow` | `workflow_migrator`, `workflow_app` | `pgcrypto` | `audit_log`, `module_event`, `module_event_receipt`, `workflow_event` append-only; `workflow_run`, `request`, `workflow_template`, `request_type`, `approver_group` never deleted |
|
||||
|
||||
**Workflow (codename `compass`) was retired on 2026-11-14** and is no longer in the kit; a box that ran
|
||||
it is taken down by the removal runbook kept outside the kit (dump, stop, DROP SCHEMA, DROP ROLE), and Atrium's
|
||||
revision `0014` removes its catalogue entry and its `module_permission` rows. **Panorama (the dashboard, M4) was
|
||||
retired in Atrium#53**: its trends are Atrium's home page now (`GET /home/trends`), Atrium's revision `0018` hides
|
||||
its catalogue entry, and its services, env templates and submodule are gone from the kit. On a box that ran it,
|
||||
`docker compose up -d --remove-orphans` stops its containers; its schema, roles and `panorama-data` volume stay
|
||||
until the operator drops them, and `panorama_app` should leave `MODULE_EVENT_READER_ROLES`. A box that sets
|
||||
`FRONTDOOR_UPSTREAMS` in its own env must drop `panorama=…` from it too: the front door refuses to start on a
|
||||
slug it no longer serves. **Insider** (legal acts and case law, REST + MCP at
|
||||
revision `0014` removes its catalogue entry and its `module_permission` rows. **Insider** (legal acts and case law, REST + MCP at
|
||||
`/insider/mcp`), ships switched off the same way (profile `insider`, with an optional OCR worker under a
|
||||
second profile, `ocr`); bringing it in is [`RUNBOOK-insider.md`](RUNBOOK-insider.md). **Arbiter** (contract analysis, split out of
|
||||
Compass; built from the `arbiter` submodule's `apps/arbiter`, repository `Alpaq92/Arbiter`), ships switched off under the profile `arbiter`;
|
||||
bringing it in is [`RUNBOOK-arbiter.md`](RUNBOOK-arbiter.md). **Lexicon and Agora, the eighth and ninth**
|
||||
(the clause library and negotiation rooms, the split plan's M2-M3) ship switched off the same way,
|
||||
bringing it in is [`RUNBOOK-arbiter.md`](RUNBOOK-arbiter.md). **Lexicon, Agora and Panorama, the eighth to tenth**
|
||||
(the clause library, negotiation rooms and the dashboard, the split plan's M2-M4) ship switched off the same way,
|
||||
each under a profile of its own name; bringing them in is [`RUNBOOK-m2-m4.md`](RUNBOOK-m2-m4.md). **Parafa and Scribe, the
|
||||
eleventh and twelfth** (PAdES signing of PDFs and drafting from templates and clauses, M6 and M7) the same; bringing
|
||||
them in is [`RUNBOOK-m6-m7.md`](RUNBOOK-m6-m7.md). **Workflow** (`Alpaq92/Workflow`, slug `workflow`: the
|
||||
general approval engine, a new module, not the retired `compass`) the same; bringing it in is
|
||||
[`RUNBOOK-workflow.md`](RUNBOOK-workflow.md). **Licences:** Atrium, Galena, Sygna and Counsel
|
||||
them in is [`RUNBOOK-m6-m7.md`](RUNBOOK-m6-m7.md). **Licences:** Atrium, Galena, Sygna and Counsel
|
||||
Scorecard each run a CI licence gate that refuses GPL, AGPL and SSPL, and no image in the kit ships
|
||||
copyleft code: Arbiter's image carries no analysis engine (orders run on a workstation). See [`../CREDITS.md`](../CREDITS.md#the-platform-kit-deploy).
|
||||
|
||||
@@ -152,7 +144,7 @@ Then verify as in §7 step 7, and set Atrium's module addresses as in §8.
|
||||
|
||||
**One address, a path per module, and Atrium is the front door.** There is no reverse proxy:
|
||||
`atrium-backend` publishes `:80` and serves the whole family as one site — `<site>/atrium`,
|
||||
`<site>/galena`, `<site>/sygna`, `<site>/counsel`, `<site>/insider`, `<site>/arbiter`, `<site>/lexicon`, `<site>/agora`, `<site>/parafa`, `<site>/scribe`, `<site>/workflow`; `/` redirects to `/atrium/` and a
|
||||
`<site>/galena`, `<site>/sygna`, `<site>/counsel`, `<site>/insider`, `<site>/arbiter`, `<site>/lexicon`, `<site>/agora`, `<site>/panorama`, `<site>/parafa`, `<site>/scribe`; `/` redirects to `/atrium/` and a
|
||||
bare `/<slug>` to `/<slug>/`. It serves Atrium itself and streams every other path to that module's
|
||||
backend, from a **fixed** map in `compose.yaml` (`FRONTDOOR_UPSTREAMS`; no target ever comes from a
|
||||
request), refuses encoded or dot-segment path tricks, drops inbound `X-Forwarded-*` and sets them anew
|
||||
|
||||
+21
-18
@@ -1,10 +1,6 @@
|
||||
# Runbook: Lexicon and Agora onto a running platform
|
||||
# Runbook: Lexicon, Agora and Panorama onto a running platform
|
||||
|
||||
> **Panorama (M4) is retired** (Atrium#53): its trends are Atrium's home page now (`GET /home/trends`),
|
||||
> Atrium's revision `0018` hides its catalogue entry, and the kit no longer carries it. Its steps are
|
||||
> gone from this runbook; `deploy/README.md` says what to do on a box that ran it.
|
||||
|
||||
The eighth and ninth modules, split out of Compass (the split plan's M2 and M3). Each is a
|
||||
The eighth to tenth modules, split out of Compass (the split plan's M2, M3 and M4). Each is a
|
||||
dredd-core app in simple tenancy with its own repository, its own submodule under
|
||||
`deploy/modules/<slug>`, its own schema and roles, `MODULE_SLUG=<slug>`, one account through Atrium,
|
||||
and each ships **switched off** under a Compose profile of its own name.
|
||||
@@ -13,13 +9,14 @@ and each ships **switched off** under a Compose profile of its own name.
|
||||
|---|---|---|---|---|---|
|
||||
| Lexicon (clause and standards library) | `/lexicon` | `Alpaq92/Lexicon` | 172.30.17.0/24 / 172.30.27.0/24 | `MODEL_PROVIDER_KEY_READER_ROLES` += `lexicon_app` | `--append-only audit_log --model-provider-keys` |
|
||||
| Agora (negotiation rooms) | `/agora` | `Alpaq92/Agora` | 172.30.18.0/24 / 172.30.28.0/24 | `MODULE_EVENT_EMITTER_ROLES` += `agora_app` | `--append-only audit_log module_event module_event_receipt --no-delete negotiation_room negotiation_round negotiation_comment --events` |
|
||||
| Panorama (dashboard) | `/panorama` | `Alpaq92/Panorama` | 172.30.19.0/24 / 172.30.29.0/24 | `MODULE_EVENT_READER_ROLES` += `panorama_app` | `--append-only audit_log --events-reader` |
|
||||
|
||||
What the kit carries for each: `<slug>-migrate` / `<slug>-backend` in `compose.yaml`
|
||||
(`FORWARDED_ALLOW_IPS` = its own subnet, `FRAME_ANCESTORS='self'`, no published port, volume
|
||||
`<slug>-data`, health at `/healthz`), the front door's `<slug>=http://<slug>-backend:8000`,
|
||||
`env/<slug>.env.example` + `env/<slug>.migrate.env.example`, `./init.sh --add <slug>`, and push.sh's
|
||||
provision, migrate and check. The catalogue tiles (Lexicon green `file`, Agora red `users`)
|
||||
are offered once to an already-seeded Atrium by its seed (`ADDED_AFTER_FIRST_SEED`).
|
||||
provision, migrate and check. The catalogue tiles (Lexicon green `file`, Agora red `users`, Panorama
|
||||
pink `chart`) are offered once to an already-seeded Atrium by its seed (`ADDED_AFTER_FIRST_SEED`).
|
||||
|
||||
**What each needs from the others.**
|
||||
|
||||
@@ -33,6 +30,11 @@ are offered once to an already-seeded Atrium by its seed (`ADDED_AFTER_FIRST_SEE
|
||||
- **Agora** writes `negotiation.round_received` to the hub's event log when the other side sends a
|
||||
round: `agora_app` must be an event EMITTER before Agora goes live, or every such round fails.
|
||||
`GALENA_BASE_URL` (hairpin) makes a Galena room's rounds new versions of its document.
|
||||
- **Panorama** reads every other module's `GET /api/v1/stats` with the viewer's own token (the
|
||||
`*_BASE_URL` hairpins in `env/panorama.env`, all written by init) and the event log as a READER
|
||||
only (dredd-core 0.23.0's reader tier). The hub grants that tier only from this Atrium release on:
|
||||
Atrium pins dredd-core **v0.23.0** and passes `MODULE_EVENT_READER_ROLES` to `event_grants_sql`; the
|
||||
push's check (`--events-reader`) runs with Atrium's dredd-core too.
|
||||
|
||||
**Rules for the whole sitting.** Run everything from `/srv/atrium/deploy` (Option A). Never
|
||||
`./init.sh --force` and never `docker compose down -v`. Pass `-T` to every `docker compose run`/`exec`
|
||||
@@ -45,7 +47,7 @@ in `env/atrium.env` and refuses a listed role that does not exist.
|
||||
## Step 0 — Before the box
|
||||
|
||||
- This Atrium release is merged and pushed; its submodule pins are commits on each module's `main`.
|
||||
- The deploy token reaches `Lexicon`, `Agora`, `dredd-core` and `Arbiter`.
|
||||
- The deploy token reaches `Lexicon`, `Agora`, `Panorama`, `dredd-core` and `Arbiter`.
|
||||
|
||||
## Step 1 — A dump
|
||||
|
||||
@@ -58,7 +60,7 @@ docker compose exec -T postgres sh -c 'pg_dump -U postgres -d "$POSTGRES_DB" -Fc
|
||||
|
||||
```bash
|
||||
git -C .. pull --ff-only
|
||||
git -C .. submodule update --init deploy/modules/lexicon deploy/modules/agora
|
||||
git -C .. submodule update --init deploy/modules/lexicon deploy/modules/agora deploy/modules/panorama
|
||||
```
|
||||
|
||||
## Step 3 — Write their settings
|
||||
@@ -66,12 +68,13 @@ git -C .. submodule update --init deploy/modules/lexicon deploy/modules/agora
|
||||
```bash
|
||||
./init.sh --add lexicon
|
||||
./init.sh --add agora
|
||||
./init.sh --add panorama
|
||||
```
|
||||
|
||||
Each writes `env/<slug>.env` / `env/<slug>.migrate.env` (mode 600), puts `<SLUG>_*_PASSWORD` in
|
||||
`db.env`, adds `<slug>_app` / `<slug>_migrator` to `IDENTITY_*_ROLES` and its opt-in (table above) in
|
||||
`env/atrium.env`, and `<slug>` to `COMPOSE_PROFILES` in `.env`. A box whose `env/atrium.env` predates
|
||||
`MODULE_EVENT_READER_ROLES` gets the key appended (empty: no module reads the log alone now).
|
||||
`MODULE_EVENT_READER_ROLES` gets the key appended. Check that `panorama_app` is in no emitter list.
|
||||
|
||||
**Connections.** Ten apps at 4 / 8 are 130 connections. `compose.yaml` now sets `max_connections=170`
|
||||
(136 at 80%); if `db.env` sets `LOCAL_DB_MAX_CONNECTIONS` explicitly (120 after Arbiter), raise it to
|
||||
@@ -82,7 +85,7 @@ Each writes `env/<slug>.env` / `env/<slug>.migrate.env` (mode 600), puts `<SLUG>
|
||||
|
||||
```bash
|
||||
read -rs DREDD_CORE_TOKEN && export DREDD_CORE_TOKEN
|
||||
docker compose build atrium-backend lexicon-backend agora-backend && unset DREDD_CORE_TOKEN
|
||||
docker compose build atrium-backend lexicon-backend agora-backend panorama-backend && unset DREDD_CORE_TOKEN
|
||||
```
|
||||
|
||||
`atrium-backend` is rebuilt for dredd-core 0.23.0 (the event reader tier).
|
||||
@@ -90,23 +93,23 @@ docker compose build atrium-backend lexicon-backend agora-backend && unset DREDD
|
||||
## Step 5 — Push
|
||||
|
||||
```bash
|
||||
./push.sh --dry-run atrium lexicon agora # complete, the two in the plan, budget fits
|
||||
./push.sh atrium lexicon agora
|
||||
./push.sh --dry-run atrium lexicon agora panorama # complete, the three in the plan, budget fits
|
||||
./push.sh atrium lexicon agora panorama
|
||||
```
|
||||
|
||||
Order: all four provisioned, Atrium migrates and re-applies the identity, model-provider and event
|
||||
tiers to the new roles (`emitters=...,agora_app` in its log), then each module's
|
||||
tiers to the new roles (`emitters=...,agora_app readers=panorama_app` in its log), then each module's
|
||||
own revisions, then the checks.
|
||||
|
||||
## Step 6 — Start
|
||||
|
||||
```bash
|
||||
docker compose up -d atrium-backend lexicon-backend agora-backend
|
||||
for slug in lexicon agora; do curl -fsS "$SITE/$slug/healthz"; done
|
||||
docker compose up -d atrium-backend lexicon-backend agora-backend panorama-backend
|
||||
for slug in lexicon agora panorama; do curl -fsS "$SITE/$slug/healthz"; done
|
||||
```
|
||||
|
||||
Then, in Atrium as the administrator: give people a `user` or `moderator` row for each (Administration
|
||||
→ Modules); no row is no access.
|
||||
→ Modules); no row is no access. Panorama's tiles for a module someone has no row for stay empty.
|
||||
|
||||
## Local models (Lexicon)
|
||||
|
||||
|
||||
+12
-9
@@ -3,9 +3,8 @@
|
||||
The eleventh and twelfth modules, split out of Compass (the split plan's M6 and M7). Each is a
|
||||
dredd-core app in simple tenancy with its own repository, its own submodule under
|
||||
`deploy/modules/<slug>`, its own schema and roles, `MODULE_SLUG=<slug>`, one account through Atrium,
|
||||
and each ships **switched off** under a Compose profile of its own name — exactly like Lexicon and Agora
|
||||
([`RUNBOOK-m2-m4.md`](RUNBOOK-m2-m4.md), whose rules for the sitting apply unchanged). Panorama, once
|
||||
listed here too, is retired (Atrium#53: its trends are Atrium's home page now; `deploy/README.md`).
|
||||
and each ships **switched off** under a Compose profile of its own name — exactly like Lexicon, Agora
|
||||
and Panorama ([`RUNBOOK-m2-m4.md`](RUNBOOK-m2-m4.md), whose rules for the sitting apply unchanged).
|
||||
|
||||
| Module | Path / profile | Repository | Network / db network | Opt-ins in `env/atrium.env` | Evidence (push.sh check) |
|
||||
|---|---|---|---|---|---|
|
||||
@@ -34,6 +33,10 @@ tile hue in this release.
|
||||
- **Scribe** takes clauses from Lexicon and exports drafts into Galena, each call with the person's
|
||||
own token: `LEXICON_URL` / `GALENA_URL` in `env/scribe.env` (hairpins, written by init),
|
||||
`MODULE_CALL_TIMEOUT` (seconds, default 15). It takes no part in the event log.
|
||||
- **Panorama** shows a card for each once `PARAFA_BASE_URL` / `SCRIBE_BASE_URL` are set in
|
||||
`env/panorama.env`. A fresh init writes them; on a box whose Panorama predates them, add the two
|
||||
lines by hand (`http://<site>/parafa`, `http://<site>/scribe`) and repin Panorama (it learnt the two
|
||||
slugs in its feat/parafa-scribe commit).
|
||||
|
||||
---
|
||||
|
||||
@@ -53,7 +56,7 @@ docker compose exec -T postgres sh -c 'pg_dump -U postgres -d "$POSTGRES_DB" -Fc
|
||||
|
||||
```bash
|
||||
git -C .. pull --ff-only
|
||||
git -C .. submodule update --init deploy/modules/parafa deploy/modules/scribe
|
||||
git -C .. submodule update --init deploy/modules/parafa deploy/modules/scribe deploy/modules/panorama
|
||||
```
|
||||
|
||||
## Step 3 — Write their settings, and the signer
|
||||
@@ -67,7 +70,7 @@ install -d -m 750 parafa-signer # then copy signer.p12 + passphrase in, and
|
||||
Each `--add` writes `env/<slug>.env` / `env/<slug>.migrate.env` (mode 600), puts `<SLUG>_*_PASSWORD`
|
||||
in `db.env`, adds `<slug>_app` / `<slug>_migrator` to `IDENTITY_*_ROLES` (and, for Parafa,
|
||||
`parafa_app` to `MODULE_EVENT_EMITTER_ROLES`) in `env/atrium.env`, and `<slug>` to `COMPOSE_PROFILES`
|
||||
in `.env`.
|
||||
in `.env`. Add `PARAFA_BASE_URL` / `SCRIBE_BASE_URL` to `env/panorama.env` (above).
|
||||
|
||||
**Connections.** Twelve apps at 4 / 8 are 156 connections. `compose.yaml` now sets
|
||||
`max_connections=200` (160 at 80%); if `db.env` sets `LOCAL_DB_MAX_CONNECTIONS` explicitly, raise it
|
||||
@@ -79,7 +82,7 @@ reconnects). Or set `DB_POOL_SIZE=3` / `DB_MAX_OVERFLOW=6` in every `env/<app>.e
|
||||
|
||||
```bash
|
||||
read -rs DREDD_CORE_TOKEN && export DREDD_CORE_TOKEN
|
||||
docker compose build atrium-backend parafa-backend scribe-backend && unset DREDD_CORE_TOKEN
|
||||
docker compose build atrium-backend parafa-backend scribe-backend panorama-backend && unset DREDD_CORE_TOKEN
|
||||
```
|
||||
|
||||
`atrium-backend` is rebuilt for the front door's two new paths, the catalogue tiles and the `yellow`
|
||||
@@ -88,8 +91,8 @@ tile hue.
|
||||
## Step 5 — Push
|
||||
|
||||
```bash
|
||||
./push.sh --dry-run atrium parafa scribe # complete, both in the plan, budget fits
|
||||
./push.sh atrium parafa scribe
|
||||
./push.sh --dry-run atrium parafa scribe panorama # complete, both in the plan, budget fits
|
||||
./push.sh atrium parafa scribe panorama
|
||||
```
|
||||
|
||||
Atrium migrates first and re-applies the event tiers (`emitters=...,parafa_app` in its log), then each
|
||||
@@ -98,7 +101,7 @@ module's own revisions, then the checks.
|
||||
## Step 6 — Start
|
||||
|
||||
```bash
|
||||
docker compose up -d atrium-backend parafa-backend scribe-backend
|
||||
docker compose up -d atrium-backend parafa-backend scribe-backend panorama-backend
|
||||
for slug in parafa scribe; do curl -fsS "$SITE/$slug/healthz"; done
|
||||
```
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
# Runbook: Workflow onto a running platform
|
||||
|
||||
Workflow is the platform's general approval engine: a run (*obieg akceptacji*) on a Galena document, an
|
||||
uploaded file or a request (*wniosek*), through 1-10 stages approved by people, an approver group or a
|
||||
Galena role. It is not the retired Workflow of `compass-contract-hub` (slug `compass`, removed by
|
||||
Atrium's revision `0014`): this one is `Alpaq92/Workflow`, slug `workflow`. Like Parafa and Scribe
|
||||
([`RUNBOOK-m6-m7.md`](RUNBOOK-m6-m7.md), whose steps apply unchanged with the slug swapped), it is a
|
||||
dredd-core app in simple tenancy with its own submodule under `deploy/modules/workflow`, its own schema
|
||||
and roles, one account through Atrium, and it ships **switched off** under the `workflow` profile.
|
||||
|
||||
| Module | Path / profile | Repository | Network / db network | Opt-ins in `env/atrium.env` | Evidence (push.sh check) |
|
||||
|---|---|---|---|---|---|
|
||||
| Workflow (approval runs) | `/workflow` | `Alpaq92/Workflow` | 172.30.32.0/24 / 172.30.42.0/24 | `MODULE_EVENT_EMITTER_ROLES` += `workflow_app` | `--append-only audit_log module_event module_event_receipt workflow_event --no-delete workflow_run request workflow_template request_type approver_group --events` |
|
||||
|
||||
It pins dredd-core **v0.24.0** (the Workflow contract, `dredd_core.workflow_contract`): that tag must
|
||||
exist before the image builds. Its committed `db/managed/provision.sql` is the platform rendering with
|
||||
`--extension pgcrypto`, which push.sh provisions and compares. The catalogue tile (gray `clock`, `live`,
|
||||
category "Dokumenty") is offered once to an already-seeded Atrium (`ADDED_AFTER_FIRST_SEED`).
|
||||
|
||||
**What it needs from the others.** Every step of a run writes to the hub's event log, so `workflow_app`
|
||||
must be an event EMITTER before Workflow goes live (`--add workflow` lists it). `GALENA_BASE_URL`
|
||||
(hairpin, written by init) lets a run pin a Galena document and a stage be approved by a Galena role;
|
||||
empty, Workflow runs on uploaded files and requests only. **Connections:** Workflow takes the twelfth
|
||||
place Compass left, so the twelve-app budget (`max_connections=200`) holds as it is.
|
||||
|
||||
## Steps
|
||||
|
||||
```bash
|
||||
cd /srv/atrium/deploy
|
||||
docker compose exec -T postgres sh -c 'pg_dump -U postgres -d "$POSTGRES_DB" -Fc' > "$HOME/dredd-pre-workflow.dump"
|
||||
git -C .. pull --ff-only && git -C .. submodule update --init deploy/modules/workflow
|
||||
./init.sh --add workflow
|
||||
read -rs DREDD_CORE_TOKEN && export DREDD_CORE_TOKEN
|
||||
docker compose build atrium-backend workflow-backend && unset DREDD_CORE_TOKEN
|
||||
./push.sh --dry-run atrium workflow && ./push.sh atrium workflow
|
||||
docker compose up -d atrium-backend workflow-backend && curl -fsS "$SITE/workflow/healthz"
|
||||
```
|
||||
|
||||
Then, in Atrium as the administrator: give people a `user` or `moderator` row (Administration →
|
||||
Modules); no row is no access.
|
||||
|
||||
**A box that ran Workflow by hand** (a `compose.override.yaml` with `workflow-*` services): remove those
|
||||
services from the override before `docker compose up`, or Compose merges two definitions of one service.
|
||||
The database roles, schema and `workflow-data` volume are the same names, so the data stays.
|
||||
|
||||
## Rollback
|
||||
|
||||
`COMPOSE_PROFILES` without `workflow`, `docker compose stop workflow-backend`; the schema stays.
|
||||
@@ -116,6 +116,14 @@ services:
|
||||
volumes:
|
||||
- *db_ca
|
||||
|
||||
panorama-migrate:
|
||||
networks:
|
||||
panorama-db: !reset null
|
||||
depends_on:
|
||||
postgres: !reset null
|
||||
volumes:
|
||||
- *db_ca
|
||||
|
||||
parafa-migrate:
|
||||
networks:
|
||||
parafa-db: !reset null
|
||||
@@ -132,14 +140,6 @@ services:
|
||||
volumes:
|
||||
- *db_ca
|
||||
|
||||
workflow-migrate:
|
||||
networks:
|
||||
workflow-db: !reset null
|
||||
depends_on:
|
||||
postgres: !reset null
|
||||
volumes:
|
||||
- *db_ca
|
||||
|
||||
# ── the backends: their networks with the front door (compose.yaml) and their own migrate, plus the CA ──
|
||||
atrium-backend:
|
||||
networks:
|
||||
@@ -205,6 +205,14 @@ services:
|
||||
volumes:
|
||||
- *db_ca
|
||||
|
||||
panorama-backend:
|
||||
networks:
|
||||
panorama-db: !reset null
|
||||
depends_on:
|
||||
postgres: !reset null
|
||||
volumes:
|
||||
- *db_ca
|
||||
|
||||
parafa-backend:
|
||||
networks:
|
||||
parafa-db: !reset null
|
||||
@@ -221,14 +229,6 @@ services:
|
||||
volumes:
|
||||
- *db_ca
|
||||
|
||||
workflow-backend:
|
||||
networks:
|
||||
workflow-db: !reset null
|
||||
depends_on:
|
||||
postgres: !reset null
|
||||
volumes:
|
||||
- *db_ca
|
||||
|
||||
# Insider's optional OCR worker (profiles `insider` + `ocr`): like a one-shot, it listens on nothing,
|
||||
# so without its database network it lands on the project's default network.
|
||||
insider-ocr:
|
||||
|
||||
@@ -84,7 +84,7 @@ services:
|
||||
|
||||
networks:
|
||||
certbot:
|
||||
ipam: { config: [{ subnet: 172.30.50.0/24 }] }
|
||||
ipam: { config: [{ subnet: 172.30.30.0/24 }] }
|
||||
|
||||
volumes:
|
||||
# NEVER `docker compose down -v` (compose.yaml): letsencrypt holds the ACME account and the
|
||||
|
||||
+104
-94
@@ -22,7 +22,7 @@
|
||||
# ONE ADDRESS, ONE MODULE PER PATH, AND ATRIUM IS THE FRONT DOOR. There is no reverse proxy: Atrium's
|
||||
# backend (backend/app/frontdoor.py) redirects `/` to /atrium/ and `/<slug>` to `/<slug>/`, serves Atrium
|
||||
# itself under /atrium, and streams /galena, /sygna, /counsel, /insider, /arbiter, /lexicon, /agora,
|
||||
# /parafa, /scribe and /workflow to the backends named in
|
||||
# /panorama, /parafa and /scribe to the backends named in
|
||||
# FRONTDOOR_UPSTREAMS below — a FIXED map; no target ever comes from a request. It strips the prefix on
|
||||
# the way, and each module's ROOT_PATH (env/<app>.env, handed to uvicorn as --root-path by its image's
|
||||
# CMD) puts it back on every URL that module generates. Both halves or neither: change one without the
|
||||
@@ -36,7 +36,7 @@
|
||||
# The consoles are COPIED into the images at build time, from the second build context `frontend`.
|
||||
#
|
||||
# Where the code comes from: Atrium is this repository (../backend, ../frontend); the modules are
|
||||
# ${MODULES_DIR}/galena, /sygna, /counsel, /insider, /arbiter, /lexicon, /agora, /parafa, /scribe and /workflow: the git submodules under ./modules
|
||||
# ${MODULES_DIR}/galena, /sygna, /counsel, /insider, /arbiter, /lexicon, /agora, /panorama, /parafa and /scribe: the git submodules under ./modules
|
||||
# (Arbiter's repository also carries the analysis engine, so its app sits at apps/arbiter of its checkout)
|
||||
# (MODULES_DIR=./modules in .env.example), or sibling checkouts next to this repository (MODULES_DIR=../..;
|
||||
# modules/README.md).
|
||||
@@ -83,7 +83,7 @@ services:
|
||||
# verify-full. Rename it and every app refuses to start.
|
||||
image: postgres:17
|
||||
# The server settings that are not initdb's, and the one hook for changing them. max_connections is
|
||||
# raised from postgres:17's default of 100 for twelve apps (12 x 13 = 156 of 160; Workflow is the twelfth since Compass left), and the push budgets 80% of it
|
||||
# raised from postgres:17's default of 100 for twelve apps (12 x 13 = 156 of 160), and the push budgets 80% of it
|
||||
# (README, Option A, "Sizing"): raise it here and LOCAL_DB_MAX_CONNECTIONS in db.env together, then
|
||||
# `docker compose up -d postgres`. `postgres` must stay the first word — the image's entrypoint only
|
||||
# does its setup when the command is the server itself.
|
||||
@@ -125,7 +125,7 @@ services:
|
||||
retries: 20
|
||||
start_period: 30s
|
||||
networks: [atrium-db, galena-db, sygna-db, counsel-db, insider-db, arbiter-db, lexicon-db,
|
||||
agora-db, parafa-db, scribe-db, workflow-db]
|
||||
agora-db, panorama-db, parafa-db, scribe-db]
|
||||
logging: *logging
|
||||
|
||||
# ── Atrium, the hub ────────────────────────────────────────────────────────────
|
||||
@@ -167,10 +167,10 @@ services:
|
||||
MIGRATION_DATABASE_URL: ""
|
||||
# THE FRONT DOOR's fixed routing table (backend/app/frontdoor.py): slug=backend, nothing else. A slug
|
||||
# outside the family refuses start-up; a module listed here whose backend is not running (Insider,
|
||||
# Arbiter, Lexicon, Agora, Parafa, Scribe or Workflow while its profile is off) answers 502 at its path. Each name resolves on that module's own
|
||||
# Arbiter, Lexicon, Agora, Panorama, Parafa or Scribe while its profile is off) answers 502 at its path. Each name resolves on that module's own
|
||||
# network below. No FORWARDED_ALLOW_IPS: nothing stands in front of this process, so its image runs
|
||||
# uvicorn with --no-proxy-headers and the peer address IS the client (the audit log's IP).
|
||||
FRONTDOOR_UPSTREAMS: "galena=http://galena-backend:8000,sygna=http://sygna-backend:8000,counsel=http://counsel-backend:8000,insider=http://insider-backend:8000,arbiter=http://arbiter-backend:8000,lexicon=http://lexicon-backend:8000,agora=http://agora-backend:8000,parafa=http://parafa-backend:8000,scribe=http://scribe-backend:8000,workflow=http://workflow-backend:8000"
|
||||
FRONTDOOR_UPSTREAMS: "galena=http://galena-backend:8000,sygna=http://sygna-backend:8000,counsel=http://counsel-backend:8000,insider=http://insider-backend:8000,arbiter=http://arbiter-backend:8000,lexicon=http://lexicon-backend:8000,agora=http://agora-backend:8000,panorama=http://panorama-backend:8000,parafa=http://parafa-backend:8000,scribe=http://scribe-backend:8000"
|
||||
# The ONE published port of the whole stack: plain HTTP. TLS is optional and off by default:
|
||||
# compose.tls.yaml (switched on in deploy/.env, RUNBOOK-tls.md) adds :443 here and the certbot sidecar.
|
||||
ports:
|
||||
@@ -192,9 +192,9 @@ services:
|
||||
arbiter: {}
|
||||
lexicon: {}
|
||||
agora: {}
|
||||
panorama: {}
|
||||
parafa: {}
|
||||
scribe: {}
|
||||
workflow: {}
|
||||
depends_on:
|
||||
atrium-migrate: { condition: service_completed_successfully }
|
||||
postgres: { condition: service_healthy }
|
||||
@@ -527,7 +527,9 @@ services:
|
||||
profiles: ["arbiter"]
|
||||
build:
|
||||
context: ${MODULES_DIR:-./modules}/arbiter/apps/arbiter/backend
|
||||
# No console (Atrium#53): the chat is its only screen, so no `frontend` context.
|
||||
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
|
||||
additional_contexts:
|
||||
frontend: ${MODULES_DIR:-./modules}/arbiter/apps/arbiter/frontend
|
||||
secrets: [dredd_core_token]
|
||||
image: dredd-family/arbiter-backend:local
|
||||
# `required: false` for Insider's reason: a missing env_file breaks the whole PROJECT, and the
|
||||
@@ -554,7 +556,9 @@ services:
|
||||
profiles: ["arbiter"]
|
||||
build:
|
||||
context: ${MODULES_DIR:-./modules}/arbiter/apps/arbiter/backend
|
||||
# No console (Atrium#53): the chat is its only screen, so no `frontend` context.
|
||||
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
|
||||
additional_contexts:
|
||||
frontend: ${MODULES_DIR:-./modules}/arbiter/apps/arbiter/frontend
|
||||
secrets: [dredd_core_token]
|
||||
image: dredd-family/arbiter-backend:local
|
||||
env_file:
|
||||
@@ -602,7 +606,9 @@ services:
|
||||
profiles: ["lexicon"]
|
||||
build:
|
||||
context: ${MODULES_DIR:-./modules}/lexicon/backend
|
||||
# No console (Lexicon b2c998e, Atrium#53): the chat is its only screen, so no `frontend` context.
|
||||
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
|
||||
additional_contexts:
|
||||
frontend: ${MODULES_DIR:-./modules}/lexicon/frontend
|
||||
secrets: [dredd_core_token]
|
||||
image: dredd-family/lexicon-backend:local
|
||||
# `required: false` for Insider's reason: a missing env_file breaks the whole PROJECT, and the
|
||||
@@ -629,7 +635,9 @@ services:
|
||||
profiles: ["lexicon"]
|
||||
build:
|
||||
context: ${MODULES_DIR:-./modules}/lexicon/backend
|
||||
# No console (Lexicon b2c998e, Atrium#53): the chat is its only screen, so no `frontend` context.
|
||||
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
|
||||
additional_contexts:
|
||||
frontend: ${MODULES_DIR:-./modules}/lexicon/frontend
|
||||
secrets: [dredd_core_token]
|
||||
image: dredd-family/lexicon-backend:local
|
||||
env_file:
|
||||
@@ -736,6 +744,78 @@ services:
|
||||
retries: 10
|
||||
logging: *logging
|
||||
|
||||
# ── Panorama (repository Alpaq92/Panorama): the platform dashboard (M4) ──────────────────────────────────────────
|
||||
# SWITCHED OFF until deploy/.env names `panorama` in COMPOSE_PROFILES, exactly like Insider and
|
||||
# Arbiter (deploy/RUNBOOK-m2-m4.md).
|
||||
# It reads every other module's /api/v1/stats with the viewer's own token (a hairpin through the
|
||||
# front door, the *_BASE_URL settings in env/panorama.env) and the hub's event log as a READER only
|
||||
# (MODULE_EVENT_READER_ROLES in env/atrium.env, dredd-core 0.23.0's reader tier).
|
||||
panorama-migrate:
|
||||
profiles: ["panorama"]
|
||||
build:
|
||||
context: ${MODULES_DIR:-./modules}/panorama/backend
|
||||
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
|
||||
additional_contexts:
|
||||
frontend: ${MODULES_DIR:-./modules}/panorama/frontend
|
||||
secrets: [dredd_core_token]
|
||||
image: dredd-family/panorama-backend:local
|
||||
# `required: false` for Insider's reason: a missing env_file breaks the whole PROJECT, and the
|
||||
# profile keeps the service off until the files exist (push.sh refuses a missing one by name).
|
||||
env_file:
|
||||
- path: ${DEPLOY_ENV_DIR:-./env}/panorama.env
|
||||
required: false
|
||||
- path: ${DEPLOY_ENV_DIR:-./env}/panorama.migrate.env
|
||||
required: false
|
||||
command: ["sh", "-c", "alembic upgrade head && python -m app.seed"]
|
||||
restart: "no"
|
||||
volumes:
|
||||
- panorama-data:/data
|
||||
networks:
|
||||
panorama-db: {}
|
||||
depends_on:
|
||||
# Identity and the event log are shared and Atrium's migration is what creates them (and grants
|
||||
# panorama_app SELECT on the log through MODULE_EVENT_READER_ROLES).
|
||||
atrium-migrate: { condition: service_completed_successfully }
|
||||
postgres: { condition: service_healthy }
|
||||
logging: *logging
|
||||
|
||||
panorama-backend:
|
||||
profiles: ["panorama"]
|
||||
build:
|
||||
context: ${MODULES_DIR:-./modules}/panorama/backend
|
||||
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
|
||||
additional_contexts:
|
||||
frontend: ${MODULES_DIR:-./modules}/panorama/frontend
|
||||
secrets: [dredd_core_token]
|
||||
image: dredd-family/panorama-backend:local
|
||||
env_file:
|
||||
- path: ${DEPLOY_ENV_DIR:-./env}/panorama.env
|
||||
required: false
|
||||
environment:
|
||||
MIGRATION_DATABASE_URL: ""
|
||||
# Trust X-Forwarded-* only from this module's own network, where atrium-backend (the front door) is
|
||||
# the one other member; change it together with the subnet at the bottom of this file.
|
||||
FORWARDED_ALLOW_IPS: "172.30.19.0/24"
|
||||
# Atrium frames this module's console at the one origin: SAMEORIGIN / frame-ancestors 'self'
|
||||
# (the module's own default is 'none' / DENY). Set here, not in env/, so no env file can undo it.
|
||||
FRAME_ANCESTORS: "'self'"
|
||||
expose: ["8000"]
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- panorama-data:/data
|
||||
networks:
|
||||
panorama: {}
|
||||
panorama-db: {}
|
||||
depends_on:
|
||||
panorama-migrate: { condition: service_completed_successfully }
|
||||
postgres: { condition: service_healthy }
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/healthz').status==200 else 1)"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
logging: *logging
|
||||
|
||||
# ── Parafa (repository Alpaq92/Parafa): PAdES signing of PDFs (M6) ──────────────────────────────────────────
|
||||
# SWITCHED OFF until deploy/.env names `parafa` in COMPOSE_PROFILES, exactly like the modules above
|
||||
# (deploy/RUNBOOK-m6-m7.md).
|
||||
@@ -821,7 +901,9 @@ services:
|
||||
profiles: ["scribe"]
|
||||
build:
|
||||
context: ${MODULES_DIR:-./modules}/scribe/backend
|
||||
# No console (Atrium#53): the chat is its only screen, so no `frontend` context.
|
||||
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
|
||||
additional_contexts:
|
||||
frontend: ${MODULES_DIR:-./modules}/scribe/frontend
|
||||
secrets: [dredd_core_token]
|
||||
image: dredd-family/scribe-backend:local
|
||||
# `required: false` for Insider's reason: a missing env_file breaks the whole PROJECT, and the
|
||||
@@ -847,7 +929,9 @@ services:
|
||||
profiles: ["scribe"]
|
||||
build:
|
||||
context: ${MODULES_DIR:-./modules}/scribe/backend
|
||||
# No console (Atrium#53): the chat is its only screen, so no `frontend` context.
|
||||
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
|
||||
additional_contexts:
|
||||
frontend: ${MODULES_DIR:-./modules}/scribe/frontend
|
||||
secrets: [dredd_core_token]
|
||||
image: dredd-family/scribe-backend:local
|
||||
env_file:
|
||||
@@ -878,79 +962,6 @@ services:
|
||||
retries: 10
|
||||
logging: *logging
|
||||
|
||||
# ── Workflow (repository Alpaq92/Workflow): approval runs on documents, files and requests ─────────────────
|
||||
# SWITCHED OFF until deploy/.env names `workflow` in COMPOSE_PROFILES, exactly like the modules above
|
||||
# (deploy/RUNBOOK-workflow.md).
|
||||
# Every step of a run writes to the hub's shared event log (dredd_core.workflow_contract), so workflow_app
|
||||
# must be an event EMITTER (MODULE_EVENT_EMITTER_ROLES in env/atrium.env) before it goes live. Galena is
|
||||
# optional: GALENA_BASE_URL in env/workflow.env, empty = runs on uploaded files and requests only.
|
||||
workflow-migrate:
|
||||
profiles: ["workflow"]
|
||||
build:
|
||||
context: ${MODULES_DIR:-./modules}/workflow/backend
|
||||
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
|
||||
additional_contexts:
|
||||
frontend: ${MODULES_DIR:-./modules}/workflow/frontend
|
||||
secrets: [dredd_core_token]
|
||||
image: dredd-family/workflow-backend:local
|
||||
# `required: false` for Insider's reason: a missing env_file breaks the whole PROJECT, and the
|
||||
# profile keeps the service off until the files exist (push.sh refuses a missing one by name).
|
||||
env_file:
|
||||
- path: ${DEPLOY_ENV_DIR:-./env}/workflow.env
|
||||
required: false
|
||||
- path: ${DEPLOY_ENV_DIR:-./env}/workflow.migrate.env
|
||||
required: false
|
||||
command: ["sh", "-c", "alembic upgrade head && python -m app.seed"]
|
||||
restart: "no"
|
||||
volumes:
|
||||
- workflow-data:/data
|
||||
networks:
|
||||
workflow-db: {}
|
||||
depends_on:
|
||||
# Identity and the event log are shared and Atrium's migration is what creates them (and grants
|
||||
# workflow_app the log through MODULE_EVENT_EMITTER_ROLES).
|
||||
atrium-migrate: { condition: service_completed_successfully }
|
||||
postgres: { condition: service_healthy }
|
||||
logging: *logging
|
||||
|
||||
workflow-backend:
|
||||
profiles: ["workflow"]
|
||||
build:
|
||||
context: ${MODULES_DIR:-./modules}/workflow/backend
|
||||
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
|
||||
additional_contexts:
|
||||
frontend: ${MODULES_DIR:-./modules}/workflow/frontend
|
||||
secrets: [dredd_core_token]
|
||||
image: dredd-family/workflow-backend:local
|
||||
env_file:
|
||||
- path: ${DEPLOY_ENV_DIR:-./env}/workflow.env
|
||||
required: false
|
||||
environment:
|
||||
MIGRATION_DATABASE_URL: ""
|
||||
# Trust X-Forwarded-* only from this module's own network, where atrium-backend (the front door) is
|
||||
# the one other member; change it together with the subnet at the bottom of this file.
|
||||
FORWARDED_ALLOW_IPS: "172.30.32.0/24"
|
||||
# Atrium frames this module's console at the one origin: SAMEORIGIN / frame-ancestors 'self'
|
||||
# (the module's own default is 'none' / DENY). Set here, not in env/, so no env file can undo it.
|
||||
FRAME_ANCESTORS: "'self'"
|
||||
expose: ["8000"]
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
# Uploaded run subjects and request attachments.
|
||||
- workflow-data:/data
|
||||
networks:
|
||||
workflow: {}
|
||||
workflow-db: {}
|
||||
depends_on:
|
||||
workflow-migrate: { condition: service_completed_successfully }
|
||||
postgres: { condition: service_healthy }
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/healthz').status==200 else 1)"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
logging: *logging
|
||||
|
||||
# One network per module backend, shared only with atrium-backend (the front door): a module cannot reach
|
||||
# another module's backend directly, and each trusts X-Forwarded-For from exactly its own subnet. If a
|
||||
# subnet collides with an existing network on the host, change it here AND in that FORWARDED_ALLOW_IPS.
|
||||
@@ -989,6 +1000,10 @@ networks:
|
||||
ipam: { config: [{ subnet: 172.30.18.0/24 }] }
|
||||
agora-db:
|
||||
ipam: { config: [{ subnet: 172.30.28.0/24 }] }
|
||||
panorama:
|
||||
ipam: { config: [{ subnet: 172.30.19.0/24 }] }
|
||||
panorama-db:
|
||||
ipam: { config: [{ subnet: 172.30.29.0/24 }] }
|
||||
parafa:
|
||||
ipam: { config: [{ subnet: 172.30.30.0/24 }] }
|
||||
parafa-db:
|
||||
@@ -997,19 +1012,14 @@ networks:
|
||||
ipam: { config: [{ subnet: 172.30.31.0/24 }] }
|
||||
scribe-db:
|
||||
ipam: { config: [{ subnet: 172.30.41.0/24 }] }
|
||||
workflow:
|
||||
ipam: { config: [{ subnet: 172.30.32.0/24 }] }
|
||||
workflow-db:
|
||||
ipam: { config: [{ subnet: 172.30.42.0/24 }] }
|
||||
|
||||
volumes:
|
||||
# NEVER `docker compose down -v`. It deletes all of these at once, and they hold the only copy of
|
||||
# something: pgdata is the whole family's database (Option A), galena-data is Galena's git
|
||||
# repositories, which are not in the database at all, sygna-data holds uploads, and
|
||||
# insider-data is Insider's DATA_DIR (shared with its optional OCR worker), arbiter-data Arbiter's,
|
||||
# and lexicon-data / agora-data theirs (Lexicon's sources, Agora's plain-file rounds),
|
||||
# parafa-data / scribe-data Parafa's uploaded and signed PDFs and Scribe's exports,
|
||||
# workflow-data Workflow's run files and request attachments.
|
||||
# and lexicon-data / agora-data / panorama-data theirs (Lexicon's sources, Agora's plain-file rounds),
|
||||
# parafa-data / scribe-data Parafa's uploaded and signed PDFs and Scribe's exports.
|
||||
# `down` without -v keeps them; to stop the stack, use `docker compose down` or `stop`. Back them up
|
||||
# (README, Option A, "Backups", and §9). A box that ran the Caddy release still has caddy_data and
|
||||
# caddy_config volumes: nothing uses them any more, and removing them is the operator's call.
|
||||
@@ -1020,9 +1030,9 @@ volumes:
|
||||
arbiter-data:
|
||||
lexicon-data:
|
||||
agora-data:
|
||||
panorama-data:
|
||||
parafa-data:
|
||||
scribe-data:
|
||||
workflow-data:
|
||||
|
||||
secrets:
|
||||
# Used only by each image's build stage (one `pip install` of the private dredd-core); no running
|
||||
|
||||
@@ -105,14 +105,13 @@ PLATFORM_IDENTITY_SCHEMA=dredd
|
||||
# With Arbiter switched on as well, seven apps: 7 x 13 = 91 does NOT fit 80 — raise max_connections
|
||||
# (compose.yaml) and LOCAL_DB_MAX_CONNECTIONS to 120 (91 of 96), or use 3 / 6 -> 7 x 10 = 70 of 80.
|
||||
# Option B with seven: 3 / 5 -> 7 x 9 = 63 of 72 at 90; with 60, 2 / 2 -> 7 x 5 = 35 of 48.
|
||||
# With Lexicon and Agora too (and Panorama, retired since), ten apps: 10 x 13 = 130 — compose.yaml now sets max_connections
|
||||
# With Lexicon, Agora and Panorama too, ten apps: 10 x 13 = 130 — compose.yaml now sets max_connections
|
||||
# to 170 (130 of 136; LOCAL_DB_MAX_CONNECTIONS defaults to the same 170), or use 3 / 6 -> 10 x 10 = 100.
|
||||
# Option B with ten: 2 / 4 -> 10 x 7 = 70 of 72 at 90 (tight); with 60, 1 / 2 -> 10 x 4 = 40 of 48.
|
||||
# With Parafa and Scribe too, twelve apps: 12 x 13 = 156 — compose.yaml now sets max_connections to
|
||||
# 200 (156 of 160; LOCAL_DB_MAX_CONNECTIONS defaults to the same 200), or use 3 / 6 -> 12 x 10 = 120.
|
||||
# Option B with twelve: 1 / 4 -> 12 x 6 = 72 of 72 at 90 (no headroom: prefer 1 / 3 -> 60); with 60,
|
||||
# 1 / 1 -> 12 x 3 = 36 of 48.
|
||||
# Workflow takes the twelfth place Compass left (retired 2026-11-14), so the same twelve-app budget holds.
|
||||
#
|
||||
# Sized for FIVE modules, not four (2026-10-03). At the old 5 / 10 a fifth app made it 5 x 16 = 80 of
|
||||
# 80 — the budget met exactly, with nothing left for a `psql`, a `docker compose run --rm <app>-migrate`
|
||||
@@ -145,12 +144,12 @@ LEXICON_MIGRATOR_PASSWORD=
|
||||
LEXICON_APP_PASSWORD=
|
||||
AGORA_MIGRATOR_PASSWORD=
|
||||
AGORA_APP_PASSWORD=
|
||||
PANORAMA_MIGRATOR_PASSWORD=
|
||||
PANORAMA_APP_PASSWORD=
|
||||
PARAFA_MIGRATOR_PASSWORD=
|
||||
PARAFA_APP_PASSWORD=
|
||||
SCRIBE_MIGRATOR_PASSWORD=
|
||||
SCRIBE_APP_PASSWORD=
|
||||
WORKFLOW_MIGRATOR_PASSWORD=
|
||||
WORKFLOW_APP_PASSWORD=
|
||||
|
||||
# ── Role names: leave them on a real deployment ────────────────────────────────────────────────
|
||||
# Role names are cluster-wide, so each carries its app's name. Override only on a test cluster
|
||||
@@ -171,12 +170,12 @@ WORKFLOW_APP_PASSWORD=
|
||||
# LEXICON_APP_ROLE=lexicon_app
|
||||
# AGORA_MIGRATOR_ROLE=agora_migrator
|
||||
# AGORA_APP_ROLE=agora_app
|
||||
# PANORAMA_MIGRATOR_ROLE=panorama_migrator
|
||||
# PANORAMA_APP_ROLE=panorama_app
|
||||
# PARAFA_MIGRATOR_ROLE=parafa_migrator
|
||||
# PARAFA_APP_ROLE=parafa_app
|
||||
# SCRIBE_MIGRATOR_ROLE=scribe_migrator
|
||||
# SCRIBE_APP_ROLE=scribe_app
|
||||
# WORKFLOW_MIGRATOR_ROLE=workflow_migrator
|
||||
# WORKFLOW_APP_ROLE=workflow_app
|
||||
|
||||
# ── --local only (no Docker on this machine) ───────────────────────────────────────────────────
|
||||
# The module checkouts and the CA come from deploy/.env (or --compose-env FILE) as for Compose.
|
||||
|
||||
Vendored
-4
@@ -76,7 +76,3 @@ APP_TOKENS_ENABLED=true
|
||||
OTEL_ENABLED=false
|
||||
OTEL_SERVICE_NAME=agora-backend
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
|
||||
# Workflow's workflow.approved on a room's last Galena round marks the room accepted.
|
||||
# Trusted from this database role only; init.sh writes it with the role prefix.
|
||||
WORKFLOW_EVENT_ROLES=workflow_app
|
||||
|
||||
Vendored
-4
@@ -70,10 +70,6 @@ ENGINE_COMMIT=
|
||||
# another module (compose.yaml), so `galena-backend` does not resolve from here. An order fetches its
|
||||
# subject's bytes from Galena with the orderer's token. Empty: subjects are plain files only.
|
||||
GALENA_BASE_URL=http://<site>/galena
|
||||
# Atrium's PUBLIC address, the same hairpin: a skill version (`sprawdzanie.yaml`) is read through
|
||||
# Atrium's API with the acting person's token when a skill is synced or ordered by version. Empty:
|
||||
# skills cannot be read, and syncing one answers 409 atrium_disabled.
|
||||
ATRIUM_BASE_URL=http://<site>/atrium
|
||||
|
||||
# ── secrets at rest ────────────────────────────────────────────────────────────────────────────
|
||||
# The platform's model-provider secret (dredd-core 0.15.0): the provider API keys live in the hub's
|
||||
|
||||
Vendored
+12
-15
@@ -57,7 +57,7 @@ IDENTITY_SCHEMA=dredd
|
||||
# does not exist. So Insider, switched off by default, is not listed; switch it on by adding
|
||||
# insider_app / insider_migrator here together with `insider` in COMPOSE_PROFILES in deploy/.env,
|
||||
# before the first push (`./init.sh --add insider` writes both). Arbiter the same: arbiter_app / arbiter_migrator with `arbiter` in COMPOSE_PROFILES
|
||||
# (`./init.sh --add arbiter`). Lexicon, Agora, Parafa, Scribe and Workflow likewise (`./init.sh --add lexicon` etc.).
|
||||
# (`./init.sh --add arbiter`). Lexicon, Agora, Panorama, Parafa and Scribe likewise (`./init.sh --add lexicon` etc.).
|
||||
# Insider is a reader of the shared model providers like every listed module, never a key reader. Atrium's own two roles are never listed — its runtime role IS the writer tier
|
||||
# (DB_APP_ROLE) and its migrator owns the schema. The grants are applied by Atrium's revisions, once
|
||||
# each: after the last one has run, a module joining later also needs a revision that re-applies them
|
||||
@@ -82,24 +82,21 @@ MODEL_PROVIDER_MIGRATOR_ROLES=arbiter_migrator
|
||||
# runtime role always does. Each takes effect once its role is in IDENTITY_READER_ROLES too; a module
|
||||
# not listed reaches nothing in the log. Re-applied on every migrate (python -m app.identity_grants).
|
||||
# Agora writes `negotiation.round_received` when the other side sends a round, so agora_app is listed;
|
||||
# Parafa writes `document.signed` when a PDF is signed, so parafa_app is listed too; Workflow writes
|
||||
# its run events (dredd_core.workflow_contract), so workflow_app is listed as well; Arbiter writes
|
||||
# `analysis.accepted` when a lawyer accepts an analysis, so arbiter_app is listed too.
|
||||
MODULE_EVENT_EMITTER_ROLES=galena_app,agora_app,parafa_app,workflow_app,arbiter_app
|
||||
# Parafa writes `document.signed` when a PDF is signed, so parafa_app is listed too.
|
||||
MODULE_EVENT_EMITTER_ROLES=galena_app,agora_app,parafa_app
|
||||
# The event log's READER tier (dredd-core 0.23.0): SELECT and nothing else, for a module that reports
|
||||
# on the log and says nothing itself. Empty since Panorama left the platform (its trends are Atrium's
|
||||
# home now). Joined the same way; a role is an emitter or a reader, never both (the grant
|
||||
# block refuses the overlap). push.sh checks a module checked with --events-reader against it.
|
||||
MODULE_EVENT_READER_ROLES=
|
||||
# on the log and says nothing itself — Panorama's trends. Joined the same way; a role is an emitter or
|
||||
# a reader, never both (the grant block refuses the overlap). push.sh checks it with --events-reader.
|
||||
MODULE_EVENT_READER_ROLES=panorama_app
|
||||
# The shared counterparty register (dredd-core 0.21.0, revision 0012), in the same schema. Writers:
|
||||
# SELECT, INSERT, UPDATE, never DELETE a counterparty (Sygna, Galena). Readers: SELECT only. Migrators: SELECT + REFERENCES, and the import door while
|
||||
# SELECT, INSERT, UPDATE, never DELETE a counterparty (Sygna). Readers: SELECT only. Migrators: SELECT + REFERENCES, and the import door while
|
||||
# their module still holds counterparties of its own. Each takes effect once joined; a module not
|
||||
# listed reaches nothing. push.sh checks each module with the tier listed here (--counterparties) and
|
||||
# refuses Sygna, Galena, Agora or Parafa when it is not listed. Agora and Parafa only read
|
||||
# (spec 2026-11-25 part A); their migrators are listed for REFERENCES (their foreign keys).
|
||||
COUNTERPARTY_WRITER_ROLES=sygna_app,galena_app
|
||||
COUNTERPARTY_READER_ROLES=agora_app,parafa_app
|
||||
COUNTERPARTY_MIGRATOR_ROLES=sygna_migrator,galena_migrator,agora_migrator,parafa_migrator
|
||||
# refuses Sygna when it is not listed. No module reads it since Workflow
|
||||
# (Compass) was retired on 2026-11-14.
|
||||
COUNTERPARTY_WRITER_ROLES=sygna_app
|
||||
COUNTERPARTY_READER_ROLES=
|
||||
COUNTERPARTY_MIGRATOR_ROLES=sygna_migrator
|
||||
# The platform's model-provider secret: provider API keys are encrypted under a key derived from it,
|
||||
# by the hub, Arbiter and Lexicon alike, so it must be IDENTICAL in env/arbiter.env and
|
||||
# env/lexicon.env. init.sh generates it once and writes it into all three. Never in the database, never logged; keep it in the secret store with
|
||||
|
||||
Vendored
-17
@@ -119,20 +119,3 @@ BACKUP_S3_ENDPOINT=
|
||||
|
||||
OTEL_ENABLED=false
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
|
||||
# Who Galena trusts in the shared event log, per kind of event that moves or fills a contract card:
|
||||
# the senders' DATABASE roles (the log's row-level security proves the role). init.sh writes them with
|
||||
# the role prefix; without it the defaults are the plain names, and a prefixed deployment would see
|
||||
# every such event refused.
|
||||
WORKFLOW_EVENT_ROLES=workflow_app
|
||||
SIGNING_EVENT_ROLES=parafa_app
|
||||
NEGOTIATION_EVENT_ROLES=agora_app
|
||||
ANALYSIS_EVENT_ROLES=arbiter_app
|
||||
|
||||
# The Archive's read-only token (Atrium#53): what Galena collects a contract's archive package with
|
||||
# when no person is there (after document.signed / workflow.signed_on_paper). A SECRET: mint it once,
|
||||
# after the first push, with
|
||||
# docker compose run --rm --no-deps -T atrium-migrate python -m app.archive_reader
|
||||
# and paste the one line it prints here (and into the secret store). Empty = the automatic archiving
|
||||
# waits on the "Do zarchiwizowania" list; a moderator can still archive by hand.
|
||||
ARCHIVE_READER_TOKEN=
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
# deploy/env/workflow.env — Workflow's backend, on the platform.
|
||||
# deploy/env/panorama.env — Panorama's backend, on the platform.
|
||||
#
|
||||
# Copy to workflow.env (init.sh writes it; `./init.sh --add workflow` on a box that predates Workflow) and
|
||||
# fill in. Read by workflow-backend and workflow-migrate; the migrator's URL lives in workflow.migrate.env,
|
||||
# Copy to panorama.env (init.sh writes it; `./init.sh --add panorama` on a box that predates Panorama) and
|
||||
# fill in. Read by panorama-backend and panorama-migrate; the migrator's URL lives in panorama.migrate.env,
|
||||
# which only the one-shot reads.
|
||||
#
|
||||
# The app's own template is modules/workflow/.env.example, and it is the authority on every key below
|
||||
# The app's own template is modules/panorama/.env.example, and it is the authority on every key below
|
||||
# that is not about this platform. Where the two differ, that one wins: this file exists to say what
|
||||
# changes when Workflow is a module rather than a standalone stack. Leave out POSTGRES_DB /
|
||||
# changes when Panorama is a module rather than a standalone stack. Leave out POSTGRES_DB /
|
||||
# DB_*_PASSWORD (the kit's postgres service is configured in deploy/.env).
|
||||
|
||||
APP_ENV=production
|
||||
|
||||
# The front door (atrium-backend) strips /workflow before the request arrives; this puts it back on
|
||||
# The front door (atrium-backend) strips /panorama before the request arrives; this puts it back on
|
||||
# every URL the app generates (the image's CMD hands it to uvicorn as --root-path). The two are one
|
||||
# decision — see compose.yaml's header. FORWARDED_ALLOW_IPS and FRAME_ANCESTORS='self' are set by
|
||||
# compose.yaml, not here: the first names the subnet the front door forwards from (172.30.32.0/24).
|
||||
ROOT_PATH=/workflow
|
||||
APP_BASE_URL=http://<site>/workflow
|
||||
# compose.yaml, not here: the first names the subnet the front door forwards from (172.30.19.0/24).
|
||||
ROOT_PATH=/panorama
|
||||
APP_BASE_URL=http://<site>/panorama
|
||||
|
||||
# ── one account (the default) ──────────────────────────────────────────────────────────────────
|
||||
# The shared identity schema. Set, this app reads the platform's accounts and never writes them;
|
||||
# empty, it is a standalone Workflow with its own sign-in. It must equal PLATFORM_IDENTITY_SCHEMA in
|
||||
# deploy/db.env — push.sh refuses the half-done combination by name. Switching Workflow on also means
|
||||
# listing workflow_app / workflow_migrator in env/atrium.env's IDENTITY_*_ROLES (the push refuses
|
||||
# without them; `./init.sh --add workflow` does both, and the event emitter list (every step of a run writes to the hub's event log)). STANDALONE (`./init.sh --standalone`):
|
||||
# empty, it is a standalone Panorama with its own sign-in. It must equal PLATFORM_IDENTITY_SCHEMA in
|
||||
# deploy/db.env — push.sh refuses the half-done combination by name. Switching Panorama on also means
|
||||
# listing panorama_app / panorama_migrator in env/atrium.env's IDENTITY_*_ROLES (the push refuses
|
||||
# without them; `./init.sh --add panorama` does both, and the event READER list (Panorama's trends read the hub's event log, SELECT only)). STANDALONE (`./init.sh --standalone`):
|
||||
# both lines commented out, with every other app's identity settings blanked to match.
|
||||
#
|
||||
# SESSION_COOKIE_NAME must match every other app's: one origin plus one cookie plus one session row
|
||||
@@ -32,20 +32,20 @@ IDENTITY_SCHEMA=dredd
|
||||
SESSION_COOKIE_NAME=dredd_session
|
||||
# The name this module answers to, and the slug Atrium's catalogue uses for it: a permission row and
|
||||
# an app token are both addressed by it, and two spellings fail silently.
|
||||
MODULE_SLUG=workflow
|
||||
MODULE_SLUG=panorama
|
||||
# Where the console sends somebody who is not signed in. Blank is correct here: the hub is a sibling
|
||||
# path at the same origin.
|
||||
IDENTITY_HUB_URL=
|
||||
|
||||
# ── database ───────────────────────────────────────────────────────────────────────────────────
|
||||
# Option A (the default): the runtime role workflow_app on this box's own PostgreSQL — plain role
|
||||
# Option A (the default): the runtime role panorama_app on this box's own PostgreSQL — plain role
|
||||
# name, the compose service `postgres`, LOCAL_DB_NAME from deploy/.env, NO sslmode / sslrootcert.
|
||||
# Password: WORKFLOW_APP_PASSWORD from db.env, percent-encoded.
|
||||
DATABASE_URL=postgresql+pg8000://workflow_app:<percent-encoded-password>@postgres:5432/dredd
|
||||
# Must be DATABASE_URL's role (Workflow refuses to start otherwise).
|
||||
DB_APP_ROLE=workflow_app
|
||||
# Password: PANORAMA_APP_PASSWORD from db.env, percent-encoded.
|
||||
DATABASE_URL=postgresql+pg8000://panorama_app:<percent-encoded-password>@postgres:5432/dredd
|
||||
# Must be DATABASE_URL's role (Panorama refuses to start otherwise).
|
||||
DB_APP_ROLE=panorama_app
|
||||
# Option B: a managed PostgreSQL provider's database (deploy/README.md, "Option B").
|
||||
# DATABASE_URL=postgresql+pg8000://workflow_app.<tenant>:<percent-encoded-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
|
||||
# DATABASE_URL=postgresql+pg8000://panorama_app.<tenant>:<percent-encoded-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
|
||||
# Every app shares one connection limit (db.env.example, "Connection budget"). Do not raise these for
|
||||
# one app without redoing that arithmetic.
|
||||
DB_POOL_SIZE=4
|
||||
@@ -57,12 +57,26 @@ DATA_DIR=/data
|
||||
# A production module seeds no demo content: the platform's people and documents are real.
|
||||
SEED_DEMO=false
|
||||
|
||||
# Galena's PUBLIC address, a hairpin back through the front door: no module shares a network with
|
||||
# another module (compose.yaml), so `galena-backend` does not resolve from here. A run on a Galena
|
||||
# document pins it and a stage can be approved by a Galena role, both read with the acting person's own
|
||||
# token. Empty: Galena off for this module (runs on uploaded files and requests only; anything on a
|
||||
# Galena document answers 409 galena_disabled).
|
||||
# ── the modules it reports on ──────────────────────────────────────────────────────────────────
|
||||
# Each module's PUBLIC address, a hairpin back through the front door (no module shares a network with
|
||||
# another). Panorama asks each one's GET /api/v1/stats with the viewer's own token and never reads
|
||||
# another module's tables. Empty: that tile is off. A module whose profile is off answers 502 at its
|
||||
# path, which the dashboard shows as unavailable; blank its line here to hide it instead.
|
||||
GALENA_BASE_URL=http://<site>/galena
|
||||
SYGNA_BASE_URL=http://<site>/sygna
|
||||
COUNSEL_BASE_URL=http://<site>/counsel
|
||||
ARBITER_BASE_URL=http://<site>/arbiter
|
||||
LEXICON_BASE_URL=http://<site>/lexicon
|
||||
AGORA_BASE_URL=http://<site>/agora
|
||||
PARAFA_BASE_URL=http://<site>/parafa
|
||||
SCRIBE_BASE_URL=http://<site>/scribe
|
||||
INSIDER_BASE_URL=http://<site>/insider
|
||||
# Seconds per module call; the calls run in parallel.
|
||||
STATS_TIMEOUT_SECONDS=3
|
||||
# Who sees the trends (aggregates over the shared event log, never per person): moderators or
|
||||
# everyone. The log is readable only because env/atrium.env lists panorama_app in
|
||||
# MODULE_EVENT_READER_ROLES (push.sh checks it with --events-reader).
|
||||
TRENDS_AUDIENCE=moderators
|
||||
|
||||
# ── auth ───────────────────────────────────────────────────────────────────────────────────────
|
||||
SESSION_TTL_HOURS=12
|
||||
@@ -70,10 +84,10 @@ LOGIN_MAX_ATTEMPTS=5
|
||||
LOGIN_LOCKOUT_MINUTES=15
|
||||
# Empty = auto-detect from the request scheme (Secure over HTTPS only).
|
||||
SESSION_COOKIE_SECURE=
|
||||
# App tokens (workflow_pat_...) stay listable and revocable here; on the platform they are minted at
|
||||
# App tokens (panorama_pat_...) stay listable and revocable here; on the platform they are minted at
|
||||
# the hub.
|
||||
APP_TOKENS_ENABLED=true
|
||||
|
||||
OTEL_ENABLED=false
|
||||
OTEL_SERVICE_NAME=workflow-backend
|
||||
OTEL_SERVICE_NAME=panorama-backend
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
+8
-8
@@ -1,16 +1,16 @@
|
||||
# Workflow's one-shot settings: loaded ONLY by workflow-migrate (together with workflow.env), never by the
|
||||
# Panorama's one-shot settings: loaded ONLY by panorama-migrate (together with panorama.env), never by the
|
||||
# long-running backend. Alembic runs as the migrator; the seed after it runs as the runtime role
|
||||
# (workflow_app, workflow.env's DATABASE_URL). init.sh writes env/workflow.migrate.env from this template
|
||||
# (git-ignored); on a deployment that already exists, `./init.sh --add workflow` does.
|
||||
# (panorama_app, panorama.env's DATABASE_URL). init.sh writes env/panorama.migrate.env from this template
|
||||
# (git-ignored); on a deployment that already exists, `./init.sh --add panorama` does.
|
||||
|
||||
# ── Option A (the default): the migrator workflow_migrator on this box's own PostgreSQL ──────────
|
||||
# ── Option A (the default): the migrator panorama_migrator on this box's own PostgreSQL ──────────
|
||||
# Plain role name, the `postgres` service, LOCAL_DB_NAME from deploy/.env, no TLS parameters (see
|
||||
# workflow.env). Password: WORKFLOW_MIGRATOR_PASSWORD, percent-encoded.
|
||||
MIGRATION_DATABASE_URL=postgresql+pg8000://workflow_migrator:<percent-encoded-password>@postgres:5432/dredd
|
||||
# panorama.env). Password: PANORAMA_MIGRATOR_PASSWORD, percent-encoded.
|
||||
MIGRATION_DATABASE_URL=postgresql+pg8000://panorama_migrator:<percent-encoded-password>@postgres:5432/dredd
|
||||
|
||||
# ── Option B: a managed PostgreSQL provider's database (deploy/README.md, "Option B") ───────────
|
||||
# Comment MIGRATION_DATABASE_URL above and uncomment this one, together with DATABASE_URL in workflow.env.
|
||||
# MIGRATION_DATABASE_URL=postgresql+pg8000://workflow_migrator.<tenant>:<percent-encoded-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
|
||||
# Comment MIGRATION_DATABASE_URL above and uncomment this one, together with DATABASE_URL in panorama.env.
|
||||
# MIGRATION_DATABASE_URL=postgresql+pg8000://panorama_migrator.<tenant>:<percent-encoded-password>@<host>:5432/postgres?sslmode=verify-full&sslrootcert=/run/certs/db-ca.crt
|
||||
|
||||
# One account (the default): nobody is created here — Atrium is the one place accounts are made, and
|
||||
# this module holds no INSERT on the shared `app_user` — so the EMAIL names the hub's first
|
||||
Vendored
-1
@@ -64,7 +64,6 @@ SEED_DEMO=false
|
||||
# local library only, exports as plain files).
|
||||
LEXICON_URL=http://<site>/lexicon
|
||||
GALENA_URL=http://<site>/galena
|
||||
INSIDER_URL=http://<site>/insider
|
||||
# Seconds a call to a sibling may take.
|
||||
MODULE_CALL_TIMEOUT=15
|
||||
|
||||
|
||||
+35
-44
@@ -3,7 +3,7 @@
|
||||
# its own PostgreSQL (deploy/README.md, "Option A"): every setting, every secret, every file, mode 600.
|
||||
#
|
||||
# The family is ONE SITE with one module per path — <site>/atrium, /galena, /sygna, /counsel,
|
||||
# /insider, /arbiter, /lexicon, /agora, /parafa, /scribe, /workflow, and / goes to Atrium (atrium-backend is the front door, compose.yaml) — so what this asks for is ONE
|
||||
# /insider, /arbiter, /lexicon, /agora, /panorama, /parafa, /scribe, and / goes to Atrium (atrium-backend is the front door, compose.yaml) — so what this asks for is ONE
|
||||
# address:
|
||||
#
|
||||
# ./init.sh --ip 1.2.3.4 # a plain-HTTP trial: http://dredd.1.2.3.4.sslip.io/atrium ...
|
||||
@@ -19,16 +19,16 @@
|
||||
# ./init.sh --add insider # ONE app joins a deployment that already exists (deploy/, or --into;
|
||||
# # Insider: deploy/RUNBOOK-insider.md)
|
||||
# ./init.sh --add arbiter # (and for Arbiter: deploy/RUNBOOK-arbiter.md)
|
||||
# ./init.sh --add lexicon # (Lexicon and Agora: deploy/RUNBOOK-m2-m4.md)
|
||||
# ./init.sh --add lexicon # (Lexicon, Agora and Panorama: deploy/RUNBOOK-m2-m4.md)
|
||||
# ./init.sh --add agora
|
||||
# ./init.sh --add panorama
|
||||
# ./init.sh --add parafa # (Parafa and Scribe: deploy/RUNBOOK-m6-m7.md)
|
||||
# ./init.sh --add scribe
|
||||
# ./init.sh --add workflow # (Workflow: deploy/RUNBOOK-workflow.md)
|
||||
#
|
||||
# ONE ACCOUNT FOR THE WHOLE PLATFORM is what it writes by default: PLATFORM_IDENTITY_SCHEMA=dredd in
|
||||
# db.env, IDENTITY_SCHEMA=dredd and SESSION_COOKIE_NAME=dredd_session in every env/<app>.env, and in
|
||||
# env/atrium.env the module roles Atrium's migration grants the shared schema to (IDENTITY_READER_ROLES /
|
||||
# IDENTITY_MIGRATOR_ROLES: Galena's, Sygna's and Counsel's — Insider, Arbiter, Lexicon, Agora, Parafa, Scribe and Workflow ship switched off, so
|
||||
# IDENTITY_MIGRATOR_ROLES: Galena's, Sygna's and Counsel's — Insider, Arbiter, Lexicon, Agora, Panorama, Parafa and Scribe ship switched off, so
|
||||
# their roles join the lists when they do). People sign in once, at /atrium, as the one first administrator in
|
||||
# env/atrium.migrate.env. --standalone writes the opt-out instead, all of it at once: those keys blank
|
||||
# (and each module's commented out, so each app keeps its own cookie name), four apps with four sets
|
||||
@@ -40,8 +40,8 @@
|
||||
# regenerated. When db.env sets PLATFORM_IDENTITY_SCHEMA (the one-account platform) it also sets the
|
||||
# app's IDENTITY_SCHEMA and SESSION_COOKIE_NAME to the platform's and adds the app's two roles to
|
||||
# env/atrium.env's IDENTITY_READER_ROLES / IDENTITY_MIGRATOR_ROLES (for arbiter also the
|
||||
# model-provider key reader and migrator lists, for lexicon the key reader list, for agora, parafa and workflow the event
|
||||
# emitters), and for every module that ships switched off it adds
|
||||
# model-provider key reader and migrator lists, for lexicon the key reader list, for agora and parafa the event
|
||||
# emitters, for panorama the event readers), and for every module that ships switched off it adds
|
||||
# the app's own profile to COMPOSE_PROFILES in .env: Atrium's identity grants will name the new roles, so the next push must
|
||||
# provision them, and it does only for an app that is switched on. When db.env does not, the app is
|
||||
# written standalone (its identity lines commented out). It refuses when APP's files exist, when
|
||||
@@ -100,9 +100,9 @@
|
||||
set -euo pipefail
|
||||
|
||||
DEPLOY_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
FAMILY="atrium galena sygna counsel insider arbiter lexicon agora parafa scribe workflow"
|
||||
FAMILY="atrium galena sygna counsel insider arbiter lexicon agora panorama parafa scribe"
|
||||
# The modules that ship switched off, each under a compose profile of its own name (compose.yaml).
|
||||
PROFILED="insider arbiter lexicon agora parafa scribe workflow"
|
||||
PROFILED="insider arbiter lexicon agora panorama parafa scribe"
|
||||
refuse() { printf 'init: %s\n' "$*" >&2; exit 2; }
|
||||
usage() { sed -n '2,/^set -euo pipefail$/p' "${BASH_SOURCE[0]}" | sed -e '$d' -e 's/^# \{0,1\}//'; }
|
||||
|
||||
@@ -427,29 +427,20 @@ write_app_files() {
|
||||
set_key "$runtime" MODEL_PROVIDER_MIGRATOR_ROLES "$ROLE_PREFIX"arbiter_migrator
|
||||
# The modules that take part in the shared event log (dredd-core 0.20.0, revision 0011); like
|
||||
# the opt-ins above, each takes effect once its role is also an identity reader.
|
||||
# Agora emits (a round from the other side), Parafa too (document.signed), and Workflow (every
|
||||
# step of a run, dredd_core.workflow_contract), and Arbiter (analysis.accepted).
|
||||
set_key "$runtime" MODULE_EVENT_EMITTER_ROLES "$ROLE_PREFIX"galena_app,"$ROLE_PREFIX"agora_app,"$ROLE_PREFIX"parafa_app,"$ROLE_PREFIX"workflow_app,"$ROLE_PREFIX"arbiter_app
|
||||
# No module only reads the log since Panorama left the platform: the reader tier starts empty.
|
||||
set_key "$runtime" MODULE_EVENT_READER_ROLES ""
|
||||
# The shared counterparty register (dredd-core 0.21.0, revision 0012; spec 2026-11-25 part A):
|
||||
# Sygna and Galena write (organisations only), and Sygna's migrator moves its own
|
||||
# counterparties in. Agora and Parafa only read. Every migrator listed gets REFERENCES, which
|
||||
# the foreign keys of Galena's contract cards, Agora's rooms and Parafa's requests need.
|
||||
set_key "$runtime" COUNTERPARTY_WRITER_ROLES "$ROLE_PREFIX"sygna_app,"$ROLE_PREFIX"galena_app
|
||||
set_key "$runtime" COUNTERPARTY_READER_ROLES "$ROLE_PREFIX"agora_app,"$ROLE_PREFIX"parafa_app
|
||||
set_key "$runtime" COUNTERPARTY_MIGRATOR_ROLES "$ROLE_PREFIX"sygna_migrator,"$ROLE_PREFIX"galena_migrator,"$ROLE_PREFIX"agora_migrator,"$ROLE_PREFIX"parafa_migrator ;;
|
||||
# Agora emits (a round from the other side), Parafa too (document.signed); Panorama only reads
|
||||
# (dredd-core 0.23.0's reader tier).
|
||||
set_key "$runtime" MODULE_EVENT_EMITTER_ROLES "$ROLE_PREFIX"galena_app,"$ROLE_PREFIX"agora_app,"$ROLE_PREFIX"parafa_app
|
||||
set_key "$runtime" MODULE_EVENT_READER_ROLES "$ROLE_PREFIX"panorama_app
|
||||
# The shared counterparty register (dredd-core 0.21.0, revision 0012): Sygna writes, and its
|
||||
# migrator moves its own counterparties in. No reader since Workflow (Compass) was retired.
|
||||
set_key "$runtime" COUNTERPARTY_WRITER_ROLES "$ROLE_PREFIX"sygna_app
|
||||
set_key "$runtime" COUNTERPARTY_READER_ROLES ""
|
||||
set_key "$runtime" COUNTERPARTY_MIGRATOR_ROLES "$ROLE_PREFIX"sygna_migrator ;;
|
||||
galena)
|
||||
set_key "$runtime" APP_BASE_URL "$PUBLIC/galena"
|
||||
# Galena renders its own link-preview tags from this address, so it must carry
|
||||
# the module's path, or every shared link would unfurl as the platform root.
|
||||
set_key "$runtime" GALENA_PUBLIC_URL "$PUBLIC/galena"
|
||||
# The senders it trusts in the event log, with the role prefix (the plain defaults would refuse
|
||||
# every event on a prefixed deployment).
|
||||
set_key "$runtime" WORKFLOW_EVENT_ROLES "$ROLE_PREFIX"workflow_app
|
||||
set_key "$runtime" SIGNING_EVENT_ROLES "$ROLE_PREFIX"parafa_app
|
||||
set_key "$runtime" NEGOTIATION_EVENT_ROLES "$ROLE_PREFIX"agora_app
|
||||
set_key "$runtime" ANALYSIS_EVENT_ROLES "$ROLE_PREFIX"arbiter_app
|
||||
set_key "$runtime" ENCRYPTION_MASTER_KEY "$ENCRYPTION_MASTER_KEY" ;;
|
||||
sygna)
|
||||
set_key "$runtime" APP_BASE_URL "$PUBLIC/sygna"
|
||||
@@ -471,9 +462,7 @@ write_app_files() {
|
||||
set_key "$runtime" MODEL_PROVIDER_SECRET "$MODEL_PROVIDER_SECRET"
|
||||
# Galena's PUBLIC address, a hairpin back through the front door (as Sygna's): an order fetches
|
||||
# its subject's bytes from Galena with the orderer's own token.
|
||||
set_key "$runtime" GALENA_BASE_URL "$PUBLIC/galena"
|
||||
# The hub's, the same hairpin: a skill version is read from Atrium with the person's own token.
|
||||
set_key "$runtime" ATRIUM_BASE_URL "$PUBLIC/atrium" ;;
|
||||
set_key "$runtime" GALENA_BASE_URL "$PUBLIC/galena" ;;
|
||||
lexicon)
|
||||
set_key "$runtime" APP_BASE_URL "$PUBLIC/lexicon"
|
||||
set_key "$runtime" SECRET_KEY "$LEXICON_SECRET_KEY"
|
||||
@@ -483,9 +472,14 @@ write_app_files() {
|
||||
agora)
|
||||
set_key "$runtime" APP_BASE_URL "$PUBLIC/agora"
|
||||
# A round on a Galena room is a new version of its document, saved with the person's own token.
|
||||
set_key "$runtime" GALENA_BASE_URL "$PUBLIC/galena"
|
||||
# Workflow's approval of a negotiation's result, trusted by its REAL role name.
|
||||
set_key "$runtime" WORKFLOW_EVENT_ROLES "$ROLE_PREFIX"workflow_app ;;
|
||||
set_key "$runtime" GALENA_BASE_URL "$PUBLIC/galena" ;;
|
||||
panorama)
|
||||
set_key "$runtime" APP_BASE_URL "$PUBLIC/panorama"
|
||||
# Every module's PUBLIC address (hairpins through the front door): Panorama asks each one's
|
||||
# /api/v1/stats with the viewer's own token.
|
||||
for other in galena sygna counsel arbiter lexicon agora parafa scribe insider; do
|
||||
set_key "$runtime" "$(printf '%s' "$other" | tr '[:lower:]' '[:upper:]')_BASE_URL" "$PUBLIC/$other"
|
||||
done ;;
|
||||
parafa)
|
||||
set_key "$runtime" APP_BASE_URL "$PUBLIC/parafa"
|
||||
# A request on a Galena document reads it and writes the signed PDF back as a new version,
|
||||
@@ -493,16 +487,9 @@ write_app_files() {
|
||||
set_key "$runtime" GALENA_BASE_URL "$PUBLIC/galena" ;;
|
||||
scribe)
|
||||
set_key "$runtime" APP_BASE_URL "$PUBLIC/scribe"
|
||||
# Clauses come from Lexicon, exports go to Galena and citations from Insider, each with the
|
||||
# person's own token.
|
||||
# Clauses come from Lexicon and exports go to Galena, each with the person's own token.
|
||||
set_key "$runtime" LEXICON_URL "$PUBLIC/lexicon"
|
||||
set_key "$runtime" GALENA_URL "$PUBLIC/galena"
|
||||
set_key "$runtime" INSIDER_URL "$PUBLIC/insider" ;;
|
||||
workflow)
|
||||
set_key "$runtime" APP_BASE_URL "$PUBLIC/workflow"
|
||||
# A run on a Galena document pins it, and a stage can be approved by a Galena role: both read
|
||||
# with the person's own token.
|
||||
set_key "$runtime" GALENA_BASE_URL "$PUBLIC/galena" ;;
|
||||
set_key "$runtime" GALENA_URL "$PUBLIC/galena" ;;
|
||||
esac
|
||||
WRITTEN="$WRITTEN $runtime $migrate"
|
||||
}
|
||||
@@ -539,11 +526,16 @@ if [ -n "$ADD" ]; then
|
||||
add_to_list "$OUT/env/atrium.env" IDENTITY_READER_ROLES "$ROLE_PREFIX${ADD}_app"
|
||||
add_to_list "$OUT/env/atrium.env" IDENTITY_MIGRATOR_ROLES "$ROLE_PREFIX${ADD}_migrator"
|
||||
CHANGED="$CHANGED\n env/atrium.env IDENTITY_READER_ROLES += $ROLE_PREFIX${ADD}_app, IDENTITY_MIGRATOR_ROLES += $ROLE_PREFIX${ADD}_migrator"
|
||||
# Galena, Agora, Parafa, Workflow and Arbiter take part in the shared event log (push.sh checks them with --events).
|
||||
case $ADD in galena|agora|parafa|workflow|arbiter)
|
||||
# Galena, Agora and Parafa take part in the shared event log (push.sh checks them with --events).
|
||||
case $ADD in galena|agora|parafa)
|
||||
add_to_list "$OUT/env/atrium.env" MODULE_EVENT_EMITTER_ROLES "$ROLE_PREFIX${ADD}_app"
|
||||
CHANGED="$CHANGED\n env/atrium.env MODULE_EVENT_EMITTER_ROLES += $ROLE_PREFIX${ADD}_app" ;;
|
||||
esac
|
||||
# Panorama reads the event log and writes nothing (dredd-core 0.23.0's reader tier; --events-reader).
|
||||
case $ADD in panorama)
|
||||
add_to_list "$OUT/env/atrium.env" MODULE_EVENT_READER_ROLES "$ROLE_PREFIX${ADD}_app"
|
||||
CHANGED="$CHANGED\n env/atrium.env MODULE_EVENT_READER_ROLES += $ROLE_PREFIX${ADD}_app" ;;
|
||||
esac
|
||||
# Lexicon's typing calls the models (a key reader); no table of its references model_provider.
|
||||
case $ADD in lexicon)
|
||||
add_to_list "$OUT/env/atrium.env" MODEL_PROVIDER_KEY_READER_ROLES "$ROLE_PREFIX${ADD}_app"
|
||||
@@ -713,7 +705,6 @@ if [ "$OUT" = "$DEPLOY_DIR" ]; then
|
||||
printf ' docker compose up -d postgres # then wait for it to report healthy\n'
|
||||
printf ' ./push.sh # provision + migrate + seed + check, all four apps\n'
|
||||
printf ' docker compose up -d\n'
|
||||
[ "$STANDALONE" = 1 ] || printf ' docker compose run --rm --no-deps -T atrium-migrate python -m app.archive_reader\n # once: the Archive token -> ARCHIVE_READER_TOKEN in env/galena.env\n # (a secret), then docker compose up -d galena-backend\n'
|
||||
else
|
||||
printf '\nNext: ./push.sh --db-env %s --compose-env %s (--local for a scratch database)\n' \
|
||||
"$OUT/db.env" "$OUT/.env"
|
||||
|
||||
@@ -21,9 +21,9 @@ both modes (the front door)
|
||||
- apart from the front door on each module's `<app>` network, no two apps share any network
|
||||
|
||||
local (Option A, this box's own PostgreSQL)
|
||||
- the twenty-three services: postgres, and <app>-migrate and <app>-backend for the eleven apps (Insider's
|
||||
- the twenty-five services: postgres, and <app>-migrate and <app>-backend for the twelve apps (Insider's
|
||||
optional OCR worker is under its own `ocr` profile, which the preflight does not activate)
|
||||
- postgres on all eleven `<app>-db` networks; each module backend on its `<app>` + `<app>-db` networks,
|
||||
- postgres on all twelve `<app>-db` networks; each module backend on its `<app>` + `<app>-db` networks,
|
||||
atrium-backend on `atrium` + `atrium-db` + every module's `<app>`; each one-shot on `<app>-db` only;
|
||||
everything that connects waits for postgres
|
||||
- postgres keeps its data in a named volume, mounts local-db/ read-only as its init directory, probes
|
||||
@@ -41,14 +41,14 @@ local (Option A, this box's own PostgreSQL)
|
||||
|
||||
managed (Option B, a managed PostgreSQL provider)
|
||||
- postgres is switched off (absent from the rendered model, or present only under a profile), the
|
||||
other twenty-two services are there
|
||||
other twenty-four services are there
|
||||
- no service is on any `<app>-db` network: each module backend on its `<app>` network only,
|
||||
atrium-backend on `atrium` + every module's `<app>`, each one-shot on the default network only (the
|
||||
one-shots listen on nothing and exit; that is the one network two apps' services share, and no
|
||||
backend is on it); nothing waits for postgres
|
||||
- all twenty-two app services mount the provider's CA read-only at /run/certs/db-ca.crt; Galena's,
|
||||
Sygna's, Insider's, Arbiter's, Lexicon's, Agora's,
|
||||
Parafa's, Scribe's and Workflow's data volumes survived the merge
|
||||
- all twenty-four app services mount the provider's CA read-only at /run/certs/db-ca.crt; Galena's,
|
||||
Sygna's, Insider's, Arbiter's, Lexicon's, Agora's, Panorama's,
|
||||
Parafa's and Scribe's data volumes survived the merge
|
||||
|
||||
Standard library only. Exit 0 = every property holds, 1 = a property failed (each one printed),
|
||||
2 = the model could not be read.
|
||||
@@ -59,15 +59,15 @@ import json
|
||||
import sys
|
||||
|
||||
HUB = "atrium"
|
||||
MODULES = ("galena", "sygna", "counsel", "insider", "arbiter", "lexicon", "agora",
|
||||
"parafa", "scribe", "workflow")
|
||||
MODULES = ("galena", "sygna", "counsel", "insider", "arbiter", "lexicon", "agora", "panorama",
|
||||
"parafa", "scribe")
|
||||
APPS = (HUB, *MODULES)
|
||||
FRONT_DOOR = f"{HUB}-backend"
|
||||
PG = "postgres"
|
||||
CA_TARGET = "/run/certs/db-ca.crt"
|
||||
DATA_VOLUMES = {"galena": "/data", "sygna": "/data", "insider": "/data", "arbiter": "/data",
|
||||
"lexicon": "/data", "agora": "/data", "parafa": "/data",
|
||||
"scribe": "/data", "workflow": "/data"}
|
||||
"lexicon": "/data", "agora": "/data", "panorama": "/data", "parafa": "/data",
|
||||
"scribe": "/data"}
|
||||
#: Optional workers, each under a compose profile of its own that the preflight never activates — so the
|
||||
#: rendered model leaves them out, while compose.yaml read as YAML (test_deploy_front_door_kit.py) has
|
||||
#: them. Either way they are held to the same rules: the profile, no ports, no migrator URL, and (Option
|
||||
@@ -178,8 +178,6 @@ def _front_door(services: dict, networks: dict, problems: list[str], *, tls: boo
|
||||
if env.get("FRAME_ANCESTORS") not in FRAME_SELF:
|
||||
problems.append(f"{backend} has FRAME_ANCESTORS={env.get('FRAME_ANCESTORS')!r}, expected 'self': Atrium frames it")
|
||||
for app in APPS:
|
||||
if app in CONSOLELESS:
|
||||
continue
|
||||
for name in (f"{app}-migrate", f"{app}-backend"):
|
||||
if name in services:
|
||||
contexts = (services[name].get("build") or {}).get("additional_contexts") or {}
|
||||
@@ -187,10 +185,6 @@ def _front_door(services: dict, networks: dict, problems: list[str], *, tls: boo
|
||||
problems.append(f"{name}'s build has no `frontend` context: its image copies the console from it")
|
||||
|
||||
|
||||
# Modules whose image ships no console (Arbiter, Lexicon, Scribe since Atrium#53: the chat is their only screen).
|
||||
CONSOLELESS = frozenset({"arbiter", "lexicon", "scribe"})
|
||||
|
||||
|
||||
def _tls(services: dict, networks: dict, problems: list[str]) -> None:
|
||||
"""compose.tls.yaml merged: the front door's half and the certbot sidecar's."""
|
||||
for name, svc in services.items():
|
||||
|
||||
@@ -47,7 +47,7 @@ _envfile_value_pick() {
|
||||
}
|
||||
|
||||
# Compose's own settings (deploy/.env): the ones the kit reads besides Compose.
|
||||
# COMPOSE_PROFILES is how a module ships in the kit switched off (Insider, Arbiter, Lexicon, Agora, Parafa, Scribe, Workflow) and is switched on per box.
|
||||
# COMPOSE_PROFILES is how a module ships in the kit switched off (Insider, Arbiter, Lexicon, Agora, Panorama, Parafa, Scribe) and is switched on per box.
|
||||
# PARAFA_SIGNER_DIR is the host directory compose.yaml mounts read-only into parafa-backend.
|
||||
# The TLS switch (compose.tls.yaml): TLS, the site's ATRIUM_DOMAIN, ACME_EMAIL, ACME_STAGING,
|
||||
# HSTS_MAX_AGE, and COMPOSE_FILE, which is how a plain `docker compose up` finds that override.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Module checkouts
|
||||
|
||||
`deploy/compose.yaml` builds Galena, Sygna and Counsel Scorecard from `${MODULES_DIR}/galena`,
|
||||
`${MODULES_DIR}/sygna` and `${MODULES_DIR}/counsel` (and Arbiter from `${MODULES_DIR}/arbiter/apps/arbiter`, Insider from `${MODULES_DIR}/insider`, Lexicon, Agora, Parafa, Scribe and Workflow from `${MODULES_DIR}/lexicon`, `/agora`, `/parafa`, `/scribe` and `/workflow`),
|
||||
`${MODULES_DIR}/sygna` and `${MODULES_DIR}/counsel` (and Arbiter from `${MODULES_DIR}/arbiter/apps/arbiter`, Insider from `${MODULES_DIR}/insider`, Lexicon, Agora, Panorama, Parafa and Scribe from `${MODULES_DIR}/lexicon`, `/agora`, `/panorama`, `/parafa` and `/scribe`),
|
||||
each image with a second build context, `frontend`, the module's console, which the image serves itself. Atrium itself is the repository this directory is in.
|
||||
`MODULES_DIR` is set in `deploy/.env`, which Compose, `push.sh` and `preflight.sh` all read (`init.sh
|
||||
--modules-dir` writes it).
|
||||
|
||||
+1
-1
Submodule deploy/modules/agora updated: 0d61e7fe03...c82c1cf238
+1
-1
Submodule deploy/modules/arbiter updated: a5eaa7ce04...085bfc9afe
+1
-1
Submodule deploy/modules/counsel updated: 7b20554a84...c6d04b1ee5
+1
-1
Submodule deploy/modules/galena updated: b9d2d80fbe...1138421e05
+1
-1
Submodule deploy/modules/insider updated: 4853393865...140ab3e5b9
+1
-1
Submodule deploy/modules/lexicon updated: 5d405aad86...b2b6267f4f
Submodule
+1
Submodule deploy/modules/panorama added at 31ecd59ca6
+1
-1
Submodule deploy/modules/parafa updated: f781bd7557...5f8c2fd2d7
+1
-1
Submodule deploy/modules/scribe updated: 4b42bd6f48...87ebdaa3b5
+1
-1
Submodule deploy/modules/sygna updated: 9230e24fbe...124bc0e666
Submodule deploy/modules/workflow deleted from d379ce2288
+24
-26
@@ -30,7 +30,7 @@
|
||||
#
|
||||
# The module checkouts are where deploy/.env's MODULES_DIR says (a MODULES_DIR in the shell wins, as in
|
||||
# Compose), else deploy/modules. A missing checkout FAILS step 4, because its switch can't be checked.
|
||||
# Only with --ci (or CI=true, which Gitea Actions sets), where the module repositories are not checked
|
||||
# Only with --ci (or CI=true, which GitHub Actions sets), where the module repositories are not checked
|
||||
# out, is a missing one skipped. Steps 2, 5 and 6 use empty stand-ins whenever a checkout is missing:
|
||||
# they check the kit's own files, not the modules.
|
||||
#
|
||||
@@ -99,7 +99,7 @@ missing=""
|
||||
# repository also carries the analysis engine (packages/*), so its app is apps/arbiter; the others are the app.
|
||||
module_subdir() { case $1 in arbiter) printf 'apps/arbiter' ;; *) printf '' ;; esac; }
|
||||
module_checkout() { printf '%s' "$1"; }
|
||||
for slug in galena sygna counsel insider arbiter lexicon agora parafa scribe workflow; do
|
||||
for slug in galena sygna counsel insider arbiter lexicon agora panorama parafa scribe; do
|
||||
sub=$(module_subdir "$slug")
|
||||
[ -d "$modules/$(module_checkout "$slug")${sub:+/$sub}/backend" ] || missing="$missing $slug"
|
||||
done
|
||||
@@ -116,7 +116,7 @@ kit_modules=$modules
|
||||
if [ -n "$missing" ]; then
|
||||
kit_modules=$tmp/modules
|
||||
echo " (steps 2, 5 and 6 use empty stand-ins for every module: they check the kit's files, not the modules)"
|
||||
for slug in galena sygna counsel insider arbiter lexicon agora parafa scribe workflow; do
|
||||
for slug in galena sygna counsel insider arbiter lexicon agora panorama parafa scribe; do
|
||||
sub=$(module_subdir "$slug")
|
||||
root=$tmp/modules/$(module_checkout "$slug")${sub:+/$sub}
|
||||
mkdir -p "$root/backend" "$root/frontend" "$root/db/managed"
|
||||
@@ -168,7 +168,7 @@ CLEAN_KEYS="$COMPOSE_KEYS POSTGRES_PASSWORD
|
||||
MANAGED_DB_MAX_CONNECTIONS
|
||||
DB_POOL_SIZE DB_MAX_OVERFLOW CHECK_REQUIRE_TLS PLATFORM_IDENTITY_SCHEMA
|
||||
DB_HOST DB_PORT DB_NAME ROLE_PREFIX OUT"
|
||||
for upper in ATRIUM GALENA SYGNA COUNSEL INSIDER ARBITER LEXICON AGORA PARAFA SCRIBE WORKFLOW; do
|
||||
for upper in ATRIUM GALENA SYGNA COUNSEL INSIDER ARBITER LEXICON AGORA PANORAMA PARAFA SCRIBE; do
|
||||
for suffix in MIGRATOR_PASSWORD APP_PASSWORD MIGRATOR_ROLE APP_ROLE PYTHON; do
|
||||
CLEAN_KEYS="$CLEAN_KEYS ${upper}_$suffix"
|
||||
done
|
||||
@@ -179,11 +179,11 @@ for key in $CLEAN_KEYS; do CLEAN_ARGS+=(-u "$key"); done
|
||||
clean() { env "${CLEAN_ARGS[@]}" "$@"; }
|
||||
compose() {
|
||||
clean docker compose --project-directory "$DEPLOY_DIR" -f "$DEPLOY_DIR/compose.yaml" --env-file "$tmp/.env" \
|
||||
--profile insider --profile arbiter --profile lexicon --profile agora --profile parafa --profile scribe --profile workflow "$@"
|
||||
--profile insider --profile arbiter --profile lexicon --profile agora --profile panorama --profile parafa --profile scribe "$@"
|
||||
}
|
||||
compose_managed_db() {
|
||||
clean docker compose --project-directory "$DEPLOY_DIR" -f "$DEPLOY_DIR/compose.yaml" \
|
||||
-f "$DEPLOY_DIR/compose.managed-db.yaml" --env-file "$tmp/.env.managed-db" --profile insider --profile arbiter --profile lexicon --profile agora --profile parafa --profile scribe --profile workflow "$@"
|
||||
-f "$DEPLOY_DIR/compose.managed-db.yaml" --env-file "$tmp/.env.managed-db" --profile insider --profile arbiter --profile lexicon --profile agora --profile panorama --profile parafa --profile scribe "$@"
|
||||
}
|
||||
# Steps 2 and 2b render with every profile a module can be switched on by, so a switched-off module is
|
||||
# still checked like the others. Step 2c renders WITHOUT them, which is what a box that has not deployed
|
||||
@@ -204,7 +204,7 @@ elif ! compose config -q; then
|
||||
else
|
||||
ok "compose.yaml is valid"
|
||||
services=$(compose config --services | sort | tr '\n' ' ') || services="(failed)"
|
||||
expected="agora-backend agora-migrate arbiter-backend arbiter-migrate atrium-backend atrium-migrate counsel-backend counsel-migrate galena-backend galena-migrate insider-backend insider-migrate lexicon-backend lexicon-migrate parafa-backend parafa-migrate postgres scribe-backend scribe-migrate sygna-backend sygna-migrate workflow-backend workflow-migrate "
|
||||
expected="agora-backend agora-migrate arbiter-backend arbiter-migrate atrium-backend atrium-migrate counsel-backend counsel-migrate galena-backend galena-migrate insider-backend insider-migrate lexicon-backend lexicon-migrate panorama-backend panorama-migrate parafa-backend parafa-migrate postgres scribe-backend scribe-migrate sygna-backend sygna-migrate "
|
||||
if [ "$services" = "$expected" ]; then ok "services: $services"; else bad "services are '$services', expected '$expected'"; fi
|
||||
compose config --format json > "$tmp/compose.json" || bad "docker compose config --format json"
|
||||
if "$PYTHON" "$DEPLOY_DIR/lib/compose_checks.py" local "$tmp/compose.json"; then
|
||||
@@ -224,7 +224,7 @@ elif ! compose_managed_db config -q; then
|
||||
else
|
||||
ok "the merge is valid"
|
||||
services=$(compose_managed_db config --services | sort | tr '\n' ' ') || services="(failed)"
|
||||
expected="agora-backend agora-migrate arbiter-backend arbiter-migrate atrium-backend atrium-migrate counsel-backend counsel-migrate galena-backend galena-migrate insider-backend insider-migrate lexicon-backend lexicon-migrate parafa-backend parafa-migrate scribe-backend scribe-migrate sygna-backend sygna-migrate workflow-backend workflow-migrate "
|
||||
expected="agora-backend agora-migrate arbiter-backend arbiter-migrate atrium-backend atrium-migrate counsel-backend counsel-migrate galena-backend galena-migrate insider-backend insider-migrate lexicon-backend lexicon-migrate panorama-backend panorama-migrate parafa-backend parafa-migrate scribe-backend scribe-migrate sygna-backend sygna-migrate "
|
||||
if [ "$services" = "$expected" ]; then ok "services: $services (postgres switched off)"; else bad "services are '$services', expected '$expected'"; fi
|
||||
compose_managed_db config --format json > "$tmp/compose.managed-db.json" || bad "docker compose config --format json (merged)"
|
||||
if "$PYTHON" "$DEPLOY_DIR/lib/compose_checks.py" managed "$tmp/compose.managed-db.json"; then
|
||||
@@ -245,25 +245,23 @@ else
|
||||
mkdir -p "$tmp/env-aside"
|
||||
mv "$tmp/env/insider.env" "$tmp/env/insider.migrate.env" \
|
||||
"$tmp/env/arbiter.env" "$tmp/env/arbiter.migrate.env" "$tmp/env/lexicon.env" "$tmp/env/lexicon.migrate.env" \
|
||||
"$tmp/env/agora.env" "$tmp/env/agora.migrate.env" \
|
||||
"$tmp/env/parafa.env" "$tmp/env/parafa.migrate.env" "$tmp/env/scribe.env" "$tmp/env/scribe.migrate.env" \
|
||||
"$tmp/env/workflow.env" "$tmp/env/workflow.migrate.env" "$tmp/env-aside/"
|
||||
"$tmp/env/agora.env" "$tmp/env/agora.migrate.env" "$tmp/env/panorama.env" "$tmp/env/panorama.migrate.env" \
|
||||
"$tmp/env/parafa.env" "$tmp/env/parafa.migrate.env" "$tmp/env/scribe.env" "$tmp/env/scribe.migrate.env" "$tmp/env-aside/"
|
||||
if ! compose_off config -q 2> "$tmp/compose-off.err"; then
|
||||
sed 's/^/ | /' "$tmp/compose-off.err"
|
||||
bad "without the switched-off modules' env files and with their profiles off, docker compose config fails: a pull would break every compose command on a box that has not deployed them"
|
||||
else
|
||||
services=$(compose_off config --services | sort | tr '\n' ' ') || services="(failed)"
|
||||
case " $services " in
|
||||
*" insider-"*|*" arbiter-"*|*" lexicon-"*|*" agora-"*|*" parafa-"*|*" scribe-"*|*" workflow-"*) bad "a switched-off module's services are active without the profile: $services" ;;
|
||||
*" insider-"*|*" arbiter-"*|*" lexicon-"*|*" agora-"*|*" panorama-"*|*" parafa-"*|*" scribe-"*) bad "a switched-off module's services are active without the profile: $services" ;;
|
||||
*) ok "the switched-off modules' env files absent and their profiles off: the kit loads, and up -d would start none of them" ;;
|
||||
esac
|
||||
fi
|
||||
mv "$tmp/env-aside/insider.env" "$tmp/env-aside/insider.migrate.env" \
|
||||
"$tmp/env-aside/arbiter.env" "$tmp/env-aside/arbiter.migrate.env" "$tmp/env-aside/lexicon.env" \
|
||||
"$tmp/env-aside/lexicon.migrate.env" "$tmp/env-aside/agora.env" "$tmp/env-aside/agora.migrate.env" \
|
||||
"$tmp/env-aside/parafa.env" \
|
||||
"$tmp/env-aside/parafa.migrate.env" "$tmp/env-aside/scribe.env" "$tmp/env-aside/scribe.migrate.env" \
|
||||
"$tmp/env-aside/workflow.env" "$tmp/env-aside/workflow.migrate.env" "$tmp/env/"
|
||||
"$tmp/env-aside/panorama.env" "$tmp/env-aside/panorama.migrate.env" "$tmp/env-aside/parafa.env" \
|
||||
"$tmp/env-aside/parafa.migrate.env" "$tmp/env-aside/scribe.env" "$tmp/env-aside/scribe.migrate.env" "$tmp/env/"
|
||||
fi
|
||||
|
||||
step "2d. optional TLS: compose.tls.yaml merged, with TLS=on example settings"
|
||||
@@ -284,7 +282,7 @@ else
|
||||
files=(-f "$DEPLOY_DIR/compose.yaml" -f "$DEPLOY_DIR/compose.managed-db.yaml" -f "$DEPLOY_DIR/compose.tls.yaml")
|
||||
envf=$tmp/.env.managed-db.tls
|
||||
fi
|
||||
if ! clean docker compose --project-directory "$DEPLOY_DIR" "${files[@]}" --env-file "$envf" --profile insider --profile arbiter --profile lexicon --profile agora --profile parafa --profile scribe --profile workflow \
|
||||
if ! clean docker compose --project-directory "$DEPLOY_DIR" "${files[@]}" --env-file "$envf" --profile insider --profile arbiter --profile lexicon --profile agora --profile panorama --profile parafa --profile scribe \
|
||||
config --format json > "$tmp/compose.$shape.tls.json"; then
|
||||
bad "docker compose config ($shape + compose.tls.yaml)"
|
||||
elif "$PYTHON" "$DEPLOY_DIR/lib/compose_checks.py" "$shape" "$tmp/compose.$shape.tls.json" --tls; then
|
||||
@@ -314,7 +312,7 @@ step "4. header parity: each module exposes the FRAME_ANCESTORS switch the kit s
|
||||
# Atrium tab framing it would go blank with nothing in any log. So each checkout must carry the field
|
||||
# (default 'none'), the validator that refuses anything but 'none' / 'self', and the SAMEORIGIN its edge
|
||||
# stamps for 'self'. The headers' VALUES are each module's own tests' business (tests/test_edge.py there).
|
||||
for slug in galena sygna counsel insider arbiter lexicon agora parafa scribe workflow; do
|
||||
for slug in galena sygna counsel insider arbiter lexicon agora panorama parafa scribe; do
|
||||
sub=$(module_subdir "$slug")
|
||||
app=$modules/$(module_checkout "$slug")${sub:+/$sub}/backend/app
|
||||
if [ ! -d "$app" ]; then
|
||||
@@ -461,7 +459,7 @@ if clean bash "$DEPLOY_DIR/init.sh" --ip 203.0.113.10 --modules-dir "$kit_module
|
||||
# app's env file, one cookie name, and the hub's grants naming the modules that ship switched on.
|
||||
one_account=1
|
||||
grep -q '^PLATFORM_IDENTITY_SCHEMA=dredd$' "$init_out/db.env" || one_account=0
|
||||
for slug in atrium galena sygna counsel insider arbiter lexicon agora parafa scribe workflow; do
|
||||
for slug in atrium galena sygna counsel insider arbiter lexicon agora panorama parafa scribe; do
|
||||
grep -q '^IDENTITY_SCHEMA=dredd$' "$init_out/env/$slug.env" || one_account=0
|
||||
grep -q '^SESSION_COOKIE_NAME=dredd_session$' "$init_out/env/$slug.env" || one_account=0
|
||||
done
|
||||
@@ -519,26 +517,26 @@ if clean bash "$DEPLOY_DIR/init.sh" --ip 203.0.113.10 --modules-dir "$kit_module
|
||||
sed 's/^/ | /' "$tmp/dry-run.init.arbiter.log"
|
||||
bad "push.sh --dry-run with Arbiter switched on (and listed) is not complete, or does not include arbiter"
|
||||
fi
|
||||
# Lexicon, Agora, Parafa, Scribe and Workflow (M2-M4, M6, M7) together: their opt-ins (model-provider
|
||||
# key reader, event emitters) are in env/atrium.env from the first init, so only the
|
||||
# Lexicon, Agora, Panorama, Parafa and Scribe (M2-M4, M6, M7) together: their opt-ins (model-provider
|
||||
# key reader, event emitters, event reader) are in env/atrium.env from the first init, so only the
|
||||
# identity lists change here.
|
||||
all_profiles=insider,arbiter,lexicon,agora,parafa,scribe,workflow
|
||||
sed -e 's/^IDENTITY_READER_ROLES=.*/&,lexicon_app,agora_app,parafa_app,scribe_app,workflow_app/' \
|
||||
-e 's/^IDENTITY_MIGRATOR_ROLES=.*/&,lexicon_migrator,agora_migrator,parafa_migrator,scribe_migrator,workflow_migrator/' \
|
||||
all_profiles=insider,arbiter,lexicon,agora,panorama,parafa,scribe
|
||||
sed -e 's/^IDENTITY_READER_ROLES=.*/&,lexicon_app,agora_app,panorama_app,parafa_app,scribe_app/' \
|
||||
-e 's/^IDENTITY_MIGRATOR_ROLES=.*/&,lexicon_migrator,agora_migrator,panorama_migrator,parafa_migrator,scribe_migrator/' \
|
||||
"$init_out/env/atrium.env" > "$tmp/atrium.env.m2m4" && install -m 600 "$tmp/atrium.env.m2m4" "$init_out/env/atrium.env"
|
||||
if clean env COMPOSE_PROFILES=$all_profiles bash "$DEPLOY_DIR/push.sh" --dry-run --db-env "$init_out/db.env" \
|
||||
--compose-env "$init_out/.env" > "$tmp/dry-run.init.m2m4.log" 2>&1 \
|
||||
&& grep -q "^Dry run: the inputs are complete.$" "$tmp/dry-run.init.m2m4.log" \
|
||||
&& grep -q "^\[lexicon\] schema lexicon, roles " "$tmp/dry-run.init.m2m4.log" \
|
||||
&& grep -q "^\[agora\] schema agora, roles " "$tmp/dry-run.init.m2m4.log" \
|
||||
&& grep -q "^\[panorama\] schema panorama, roles " "$tmp/dry-run.init.m2m4.log" \
|
||||
&& grep -q "^\[parafa\] schema parafa, roles " "$tmp/dry-run.init.m2m4.log" \
|
||||
&& grep -q "^\[scribe\] schema scribe, roles " "$tmp/dry-run.init.m2m4.log" \
|
||||
&& grep -q "^\[workflow\] schema workflow, roles " "$tmp/dry-run.init.m2m4.log" \
|
||||
&& grep -q "^ budget 11 apps" "$tmp/dry-run.init.m2m4.log"; then
|
||||
ok "with every profile on and every module's roles listed the files are complete, the plan includes lexicon, agora, parafa, scribe and workflow, and the budget counts eleven apps"
|
||||
ok "with every profile on and every module's roles listed the files are complete, the plan includes lexicon, agora, panorama, parafa and scribe, and the budget counts eleven apps"
|
||||
else
|
||||
sed 's/^/ | /' "$tmp/dry-run.init.m2m4.log"
|
||||
bad "push.sh --dry-run with Lexicon, Agora, Parafa, Scribe and Workflow switched on (and listed) is not complete, or does not include them"
|
||||
bad "push.sh --dry-run with Lexicon, Agora, Panorama, Parafa and Scribe switched on (and listed) is not complete, or does not include them"
|
||||
fi
|
||||
# The opt-out: separate accounts per app, written whole, and a push that accepts it as it stands.
|
||||
if clean bash "$DEPLOY_DIR/init.sh" --ip 203.0.113.10 --standalone --modules-dir "$kit_modules" \
|
||||
|
||||
+34
-42
@@ -8,12 +8,12 @@
|
||||
# [--stop-backend] [--lock-timeout DURATION]
|
||||
# [--db-env FILE] [--compose-env FILE] [--env-dir DIR]
|
||||
# [atrium] [galena] [sygna] [counsel] [insider] [arbiter] [lexicon] [agora]
|
||||
# [parafa] [scribe] [workflow]
|
||||
# [panorama] [parafa] [scribe]
|
||||
#
|
||||
# No app named = every DEPLOYED app: all four, plus insider, arbiter, lexicon, agora,
|
||||
# parafa, scribe and workflow when COMPOSE_PROFILES names them (deploy/.env). Apps always run in the
|
||||
# family order (atrium, galena, sygna, counsel, insider, arbiter, lexicon, agora,
|
||||
# parafa, scribe, workflow).
|
||||
# panorama, parafa and scribe when COMPOSE_PROFILES names them (deploy/.env). Apps always run in the
|
||||
# family order (atrium, galena, sygna, counsel, insider, arbiter, lexicon, agora, panorama,
|
||||
# parafa, scribe).
|
||||
#
|
||||
# 1. preflight before anything connects, for EVERY selected app: the platform admin's URL is
|
||||
# well-formed; the app's env files match deploy/db.env as its <app>-migrate AND its
|
||||
@@ -117,9 +117,9 @@ CONTAINER_CA=/run/certs/db-ca.crt
|
||||
MANAGED_DB_COMPOSE=$DEPLOY_DIR/compose.managed-db.yaml
|
||||
# The database service of compose.yaml, which is also LOCAL_DB_HOST's default.
|
||||
LOCAL_DB_SERVICE=postgres
|
||||
FAMILY="atrium galena sygna counsel insider arbiter lexicon agora parafa scribe workflow"
|
||||
FAMILY="atrium galena sygna counsel insider arbiter lexicon agora panorama parafa scribe"
|
||||
# The modules that ship in the kit switched OFF, each under a compose profile of its own name.
|
||||
PROFILED="insider arbiter lexicon agora parafa scribe workflow"
|
||||
PROFILED="insider arbiter lexicon agora panorama parafa scribe"
|
||||
# The Compose service every step of the platform admin runs in.
|
||||
PROVISIONER=atrium-migrate
|
||||
ORIG_ARGS=("$@")
|
||||
@@ -156,7 +156,7 @@ while [ $# -gt 0 ]; do
|
||||
--env-dir) [ $# -ge 2 ] || refuse "--env-dir needs a directory"; ENV_DIR_ARG=$2; shift ;;
|
||||
--env-dir=*) ENV_DIR_ARG=${1#*=} ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
atrium|galena|sygna|counsel|insider|arbiter|lexicon|agora|parafa|scribe|workflow) SELECTED="$SELECTED $1" ;;
|
||||
atrium|galena|sygna|counsel|insider|arbiter|lexicon|agora|panorama|parafa|scribe) SELECTED="$SELECTED $1" ;;
|
||||
*) refuse "unknown argument: $1 (see --help)" ;;
|
||||
esac
|
||||
shift
|
||||
@@ -201,7 +201,7 @@ push_key() { # the settings deploy/db.env may carry (anything else is refused,
|
||||
# alembic and seed in --local mode, where env/<app>.env is silent about it, and the migration
|
||||
# would run with a setting the deployed backend will not have.
|
||||
PLATFORM_IDENTITY_SCHEMA) return 0 ;;
|
||||
ATRIUM_*|GALENA_*|SYGNA_*|COUNSEL_*|INSIDER_*|ARBITER_*|LEXICON_*|AGORA_*|PARAFA_*|SCRIBE_*|WORKFLOW_*)
|
||||
ATRIUM_*|GALENA_*|SYGNA_*|COUNSEL_*|INSIDER_*|ARBITER_*|LEXICON_*|AGORA_*|PANORAMA_*|PARAFA_*|SCRIBE_*)
|
||||
case ${1#*_} in MIGRATOR_PASSWORD|APP_PASSWORD|MIGRATOR_ROLE|APP_ROLE|PYTHON) return 0 ;; esac ;;
|
||||
esac
|
||||
return 1
|
||||
@@ -306,7 +306,7 @@ resolve_compose_key() {
|
||||
resolve_compose_key MODULES_DIR ./modules; MODULES_ROOT=$(abspath "$RESOLVED") MODULES_SOURCE=$SOURCE
|
||||
resolve_compose_key DEPLOY_ENV_DIR ./env; ENV_DIR=$(abspath "$RESOLVED") ENV_DIR_SOURCE=$SOURCE
|
||||
|
||||
# Insider, Arbiter, Lexicon, Agora, Parafa, Scribe and Workflow ship in the kit switched OFF: compose.yaml puts their services under a profile
|
||||
# Insider, Arbiter, Lexicon, Agora, Panorama, Parafa and Scribe ship in the kit switched OFF: compose.yaml puts their services under a profile
|
||||
# of the module's own name, so `docker compose up -d` leaves each alone until deploy/.env names it in
|
||||
# COMPOSE_PROFILES. A push with no app named follows the same switch — otherwise the four deployed apps
|
||||
# would be held up by one that is not, refused over env files and passwords nobody has written yet.
|
||||
@@ -352,18 +352,18 @@ STRIP=${STRIP# } FAMILY_ROLES=${FAMILY_ROLES# }
|
||||
|
||||
module_repo() {
|
||||
case $1 in
|
||||
atrium) printf 'http://77.216.148.202:3000/Haski/Atrium' ;;
|
||||
galena) printf 'http://77.216.148.202:3000/Haski/Galena' ;;
|
||||
sygna) printf 'http://77.216.148.202:3000/Haski/Sygna' ;;
|
||||
counsel) printf 'http://77.216.148.202:3000/Haski/CounselScorecard' ;;
|
||||
insider) printf 'http://77.216.148.202:3000/Haski/Insider' ;;
|
||||
atrium) printf 'https://github.com/Alpaq92/Atrium' ;;
|
||||
galena) printf 'https://github.com/Alpaq92/Galena' ;;
|
||||
sygna) printf 'https://github.com/Alpaq92/Sygna' ;;
|
||||
counsel) printf 'https://github.com/Alpaq92/CounselScorecard' ;;
|
||||
insider) printf 'https://github.com/Alpaq92/Insider' ;;
|
||||
# Arbiter's repository also carries the analysis engine (packages/*): the app is apps/arbiter in it.
|
||||
arbiter) printf 'http://77.216.148.202:3000/Haski/Arbiter' ;;
|
||||
lexicon) printf 'http://77.216.148.202:3000/Haski/Lexicon' ;;
|
||||
agora) printf 'http://77.216.148.202:3000/Haski/Agora' ;;
|
||||
parafa) printf 'http://77.216.148.202:3000/Haski/Parafa' ;;
|
||||
scribe) printf 'http://77.216.148.202:3000/Haski/Scribe' ;;
|
||||
workflow) printf 'http://77.216.148.202:3000/Haski/Workflow' ;;
|
||||
arbiter) printf 'https://github.com/Alpaq92/Arbiter' ;;
|
||||
lexicon) printf 'https://github.com/Alpaq92/Lexicon' ;;
|
||||
agora) printf 'https://github.com/Alpaq92/Agora' ;;
|
||||
panorama) printf 'https://github.com/Alpaq92/Panorama' ;;
|
||||
parafa) printf 'https://github.com/Alpaq92/Parafa' ;;
|
||||
scribe) printf 'https://github.com/Alpaq92/Scribe' ;;
|
||||
esac
|
||||
}
|
||||
|
||||
@@ -389,14 +389,13 @@ app_setup() { # sets the per-app globals for $1
|
||||
# Arbiter (the split plan's M1) lives at apps/arbiter of its repository (which also carries the
|
||||
# analysis engine's packages/*), so SUBDIR is set: the checkout root is not the app root. Its evidence is
|
||||
# app.models APPEND_ONLY_TABLES / NO_DELETE_TABLES — the lists its 0002, 0005 and 0006 grant from
|
||||
# (test_deploy_arbiter_check_args.py compares them); its event tables are Agora's case
|
||||
# (analysis.accepted: --events). Its 0001 runs CREATE EXTENSION IF NOT EXISTS
|
||||
# (test_deploy_arbiter_check_args.py compares them). Its 0001 runs CREATE EXTENSION IF NOT EXISTS
|
||||
# "pgcrypto", which Galena's provisioning has already put in the database, and its committed
|
||||
# provision.sql declares no extension — Insider's case exactly, so none is asked for here.
|
||||
arbiter) UP=ARBITER; EXTENSIONS=""
|
||||
CHECK_EXTRA="--append-only audit_log analysis_signoff agent_version frozen_card module_event module_event_receipt --no-delete analysis"
|
||||
CHECK_EXTRA="--append-only audit_log analysis_signoff agent_version frozen_card --no-delete analysis"
|
||||
SUBDIR=apps/arbiter ;;
|
||||
# Lexicon and Agora (the split plan's M2, M3): each app.models APPEND_ONLY_TABLES /
|
||||
# Lexicon, Agora and Panorama (the split plan's M2, M3, M4): each app.models APPEND_ONLY_TABLES /
|
||||
# NO_DELETE_TABLES, the lists their 0002 grants from and their CI's managed check passes
|
||||
# (test_deploy_m2_m4_check_args.py compares them). Each 0001 runs CREATE EXTENSION IF NOT EXISTS
|
||||
# "pgcrypto", which Galena's provisioning has already put in the database, and each committed
|
||||
@@ -404,20 +403,14 @@ app_setup() { # sets the per-app globals for $1
|
||||
# tables are Galena's case: standalone its own, on the platform the hub's (the --events rule).
|
||||
lexicon) UP=LEXICON; EXTENSIONS=""; CHECK_EXTRA="--append-only audit_log" ;;
|
||||
agora) UP=AGORA; EXTENSIONS=""
|
||||
CHECK_EXTRA="--append-only audit_log module_event module_event_receipt --no-delete negotiation_room negotiation_round negotiation_comment room_invite" ;;
|
||||
CHECK_EXTRA="--append-only audit_log module_event module_event_receipt --no-delete negotiation_room negotiation_round negotiation_comment" ;;
|
||||
panorama) UP=PANORAMA; EXTENSIONS=""; CHECK_EXTRA="--append-only audit_log" ;;
|
||||
# Parafa and Scribe (M6, M7): the same rule, their app.models lists (test_deploy_m6_m7_check_args.py).
|
||||
# Parafa's event tables are Agora's case (it emits document.signed: --events); a signing request is
|
||||
# evidence and is never deleted. Scribe takes no part in the event log; an export is never deleted.
|
||||
parafa) UP=PARAFA; EXTENSIONS=""
|
||||
CHECK_EXTRA="--append-only audit_log module_event module_event_receipt --no-delete signing_request" ;;
|
||||
scribe) UP=SCRIBE; EXTENSIONS=""; CHECK_EXTRA="--append-only audit_log --no-delete draft_export" ;;
|
||||
# Workflow: the same rule, its app.models lists (test_deploy_workflow_check_args.py). Its event tables
|
||||
# are Agora's case (every step of a run is an event: --events), and its own timeline is append-only;
|
||||
# a run, its request and the templates, types and groups it ran on are archived, never deleted. Its
|
||||
# committed provision.sql is rendered with --extension pgcrypto (Galena's case), so the drift check
|
||||
# and the provisioning must ask for it too.
|
||||
workflow) UP=WORKFLOW; EXTENSIONS=pgcrypto
|
||||
CHECK_EXTRA="--append-only audit_log module_event module_event_receipt workflow_event --no-delete workflow_run request workflow_template request_type approver_group" ;;
|
||||
esac
|
||||
SCHEMA=$slug
|
||||
local var tier
|
||||
@@ -466,23 +459,22 @@ app_setup() { # sets the per-app globals for $1
|
||||
# Only once the module itself pins dredd-core 0.20.0 or later: an older pin's `managed check` has
|
||||
# no --events flag and would refuse the whole check.
|
||||
# Agora emits too (a round from the other side; it pins 0.22.0, so always --events), and Parafa
|
||||
# (document.signed; it pins 0.23.0), and Workflow (its runs' events; it pins 0.24.0), and Arbiter
|
||||
# (analysis.accepted; it pins 0.25.0).
|
||||
case $slug in galena|agora|parafa|workflow|arbiter)
|
||||
# (document.signed; it pins 0.23.0).
|
||||
case $slug in galena|agora|parafa)
|
||||
pin=$(sed -n 's/^dredd-core @ .*@v\([0-9.]*\).*/\1/p' "$MODULE/backend/requirements.txt" 2>/dev/null | head -1 || true)
|
||||
case $pin in 0.[0-9].*|0.1[0-9].*) ;; *) IDENTITY_CHECK_ARGS="$IDENTITY_CHECK_ARGS --events" ;; esac ;;
|
||||
esac
|
||||
# No module reads the log without writing it since Panorama left the platform: nothing is
|
||||
# checked with --events-reader now. The reader tier (MODULE_EVENT_READER_ROLES) and its consistency
|
||||
# check below stay for the next module that needs it.
|
||||
# Panorama READS the log and writes nothing (dredd-core 0.23.0's reader tier, MODULE_EVENT_READER_ROLES):
|
||||
# its check proves SELECT and nothing more. The flag is new in 0.23.0, and the check runs with
|
||||
# Atrium's dredd-core (pinned 0.23.0 for exactly this).
|
||||
case $slug in panorama) IDENTITY_CHECK_ARGS="$IDENTITY_CHECK_ARGS --events-reader" ;; esac
|
||||
# The shared counterparty register (dredd-core 0.21.0): the module's tier is the one the hub
|
||||
# grants it (COUNTERPARTY_WRITER_ROLES / COUNTERPARTY_READER_ROLES in env/atrium.env; a role in
|
||||
# both is a writer, as app.identity_grants decides), so the check proves exactly that tier; a
|
||||
# module the hub does not list is checked without the flag, which proves it reaches nothing.
|
||||
# Only once the module pins dredd-core 0.21.0 or later: an older pin's `managed check` has no
|
||||
# --counterparties flag and would refuse the whole check.
|
||||
# CP_NEEDED marks the modules whose own revision moves counterparties in (Sygna's parties) or
|
||||
# points a foreign key at the register (Galena's cards, Agora's rooms, Parafa's requests):
|
||||
# CP_NEEDED marks the modules whose own revision moves counterparties in (Sygna's parties):
|
||||
# the preflight requires the hub to list them.
|
||||
CP_TIER="" CP_NEEDED=""
|
||||
if [ "$slug" != atrium ]; then
|
||||
@@ -492,7 +484,7 @@ app_setup() { # sets the per-app globals for $1
|
||||
case ",$HUB_CP_READERS," in *",$APP_ROLE,"*) CP_TIER=reader ;; esac ;;
|
||||
esac
|
||||
[ -z "$CP_TIER" ] || IDENTITY_CHECK_ARGS="$IDENTITY_CHECK_ARGS --counterparties $CP_TIER"
|
||||
case $slug in sygna|galena|agora|parafa) CP_NEEDED=1 ;; esac ;;
|
||||
case $slug in sygna) CP_NEEDED=1 ;; esac ;;
|
||||
esac
|
||||
fi
|
||||
fi
|
||||
@@ -744,7 +736,7 @@ for app in $APPS; do
|
||||
# register: without a tier its runtime cannot read the register, and without the migrator in
|
||||
# COUNTERPARTY_MIGRATOR_ROLES its revision finds no import door and stops mid-deploy.
|
||||
if [ -n "$CP_NEEDED" ]; then
|
||||
[ -n "$CP_TIER" ] || problem "$slug: $HUB_ENV_FILE lists $APP_ROLE in neither COUNTERPARTY_WRITER_ROLES nor COUNTERPARTY_READER_ROLES: $slug reads the shared counterparty register (dredd-core 0.21.0). Sygna and Galena write it (COUNTERPARTY_WRITER_ROLES); Agora and Parafa read it (COUNTERPARTY_READER_ROLES). Add it and push atrium too (or before): atrium-migrate re-applies the counterparty grants on every run"
|
||||
[ -n "$CP_TIER" ] || problem "$slug: $HUB_ENV_FILE lists $APP_ROLE in neither COUNTERPARTY_WRITER_ROLES nor COUNTERPARTY_READER_ROLES: $slug reads the shared counterparty register (dredd-core 0.21.0). Sygna writes it (COUNTERPARTY_WRITER_ROLES); without Sygna the module that needs counterparties does; every other one reads (COUNTERPARTY_READER_ROLES). Add it and push atrium too (or before): atrium-migrate re-applies the counterparty grants on every run"
|
||||
case ",$HUB_CP_MIGRATORS," in *",$MIGRATOR_ROLE,"*) ;; *)
|
||||
problem "$slug: $HUB_ENV_FILE does not list $MIGRATOR_ROLE in COUNTERPARTY_MIGRATOR_ROLES: $slug's revision moves its own counterparties into the shared register through the hub's import door, which opens only for the migrators listed there (and its foreign keys need REFERENCES). Add it and push atrium too (or before)" ;;
|
||||
esac
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user