Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab47ebbe41 | ||
|
|
1204828e06 | ||
|
|
2fef7d1a9e | ||
|
|
6dfd81329f | ||
|
|
a91203b80b | ||
|
|
59cb84f75e | ||
|
|
638ddaaa9d | ||
|
|
33202056f0 |
+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,workflow=http://workflow-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, Workflow) 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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+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 ────────────────────────
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -53,7 +53,7 @@ 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",
|
||||
MODULES = ("galena", "sygna", "counsel", "insider", "arbiter", "lexicon", "agora", "panorama",
|
||||
"parafa", "scribe", "workflow")
|
||||
SLUGS = (ATRIUM, *MODULES)
|
||||
|
||||
@@ -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, /scribe and /workflow.")
|
||||
|
||||
# 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.
|
||||
|
||||
@@ -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__ = (
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -215,8 +215,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):
|
||||
|
||||
+16
-22
@@ -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,10 +35,8 @@ 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",
|
||||
# joins appends its slug here; nothing ever leaves this tuple.
|
||||
ADDED_AFTER_FIRST_SEED: tuple[str, ...] = ("insider", "arbiter", "lexicon", "agora", "panorama",
|
||||
"parafa", "scribe", "workflow")
|
||||
|
||||
|
||||
@@ -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": (
|
||||
@@ -279,10 +277,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()
|
||||
|
||||
@@ -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"]
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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.2
|
||||
|
||||
# Web framework
|
||||
fastapi==0.115.6
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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,162 @@
|
||||
"""Home chat, step 1c (spec 2026-11-27, B): the act the model named is the act code asks Insider for.
|
||||
|
||||
On the 20.11 exam the rewrite step named the right act and code still found none: "Kodeks postępowania cywilny"
|
||||
(Qwen's nominative, 10 times) was known only as "…cywilnego", and "Konstytucja Rzeczypospolitej Polskiej" (8 and
|
||||
9 times) never equalled Insider's title, which ends "z dnia 2 kwietnia 1997 r.". The names are copied here once
|
||||
from the `rw_akt` field of `klasy2.json` (research notes "Lokalny embedding a błędy czatu"), with other cases and
|
||||
the regressions the old code already guarded.
|
||||
|
||||
The chat block runs under Node over the world of `test_chat_traps_console.py`, with a stub of Insider that
|
||||
records every `resolve` and `search` it is asked. DB-free and network-free; skipped only where no `node` exists.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import test_chat_traps_console as traps
|
||||
|
||||
pytestmark = traps.pytestmark
|
||||
|
||||
_NAMES = "'chatCarry'];"
|
||||
assert _NAMES in traps._PRELUDE
|
||||
_PRELUDE = traps._PRELUDE.replace(_NAMES, "'chatCarry', 'chatActDoc', 'chatRewrite'];") + r"""
|
||||
// Insider: `resolve` answers a code's abbreviation with a document named after it; the act search answers
|
||||
// every query with the same few acts, so the title comparison alone decides. Every call is recorded.
|
||||
const insider = [];
|
||||
const ACTS = [
|
||||
{ id: 'dzu:DU/1997/483', title: 'Konstytucja Rzeczypospolitej Polskiej z dnia 2 kwietnia 1997 r.' },
|
||||
{ id: 'dzu:DU/2024/1796', title: 'Ustawa o prawach konsumenta (tekst jednolity)' },
|
||||
{ id: 'dzu:DU/2023/1', title: 'Ustawa z dnia 1 grudnia 2022 r. o zmianie ustawy o prawach konsumenta oraz niektórych innych ustaw' },
|
||||
{ id: 'dzu:DU/2024/323', title: 'Ustawa o świadczeniach rodzinnych (tekst jednolity)' },
|
||||
{ id: 'dzu:DU/1999/930', title: 'Ustawa z dnia 10 września 1999 r. - Kodeks karny skarbowy' }];
|
||||
const worldFetch = (url) => {
|
||||
const u = new URL(String(url));
|
||||
const m = /^\/insider\/api\/v1\/(.*)$/.exec(u.pathname);
|
||||
if (!m) return null;
|
||||
insider.push(m[1] + u.search);
|
||||
const code = m[1] === 'resolve' && u.searchParams.get('citation').replace(/^art\. 1 /, '');
|
||||
const body = code ? { documents: [{ id: 'code:' + code, title: code }] } : m[1] === 'search' ? { acts: ACTS } : undefined;
|
||||
return body === undefined ? new Response('{}', { status: 404 }) : new Response(JSON.stringify(body), { status: 200 });
|
||||
};
|
||||
// What code found for each name, and what it asked Insider for it.
|
||||
async function found(names) {
|
||||
const { f } = session();
|
||||
const out = {};
|
||||
for (const n of names) {
|
||||
insider.length = 0;
|
||||
const d = await f.chatActDoc(n);
|
||||
out[n] = { id: d ? d.id : null, asked: [...insider] };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// What the rewrite step made of each model reply, and the max_tokens it asked for.
|
||||
async function rewritten(replies) {
|
||||
const out = [];
|
||||
for (const r of replies) {
|
||||
const s = session([r]);
|
||||
const rw = await s.f.chatRewrite('m', 'Pytanie?', () => {});
|
||||
out.push({ ...rw, max_tokens: s.asked[0].max_tokens });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
"""
|
||||
_PRELUDE = _PRELUDE.replace(" const fetch = async (url, o = {}) => {\n",
|
||||
" const fetch = async (url, o = {}) => {\n const ins = worldFetch(url); if (ins) return ins;\n", 1)
|
||||
assert "worldFetch(url); if (ins)" in _PRELUDE
|
||||
|
||||
|
||||
def _run(js: str) -> object:
|
||||
old = traps._PRELUDE
|
||||
traps._PRELUDE = _PRELUDE
|
||||
try:
|
||||
return traps._run(js)
|
||||
finally:
|
||||
traps._PRELUDE = old
|
||||
|
||||
|
||||
def _found(names: list[str]) -> dict:
|
||||
return _run(f"return found({names!r});")
|
||||
|
||||
|
||||
_CODES = {
|
||||
# From the 20.11 logs: Qwen's nominative (12 times), and the genitive every other answer gave.
|
||||
"Kodeks postępowania cywilny": "k.p.c.",
|
||||
"Kodeks postępowania cywilnego": "k.p.c.",
|
||||
"Kodeksie postępowania cywilnym": "k.p.c.",
|
||||
"Kodeks postępowania karny": "k.p.k.",
|
||||
"Kodeks postępowania karnego": "k.p.k.",
|
||||
"Kodeksie postępowania karnym": "k.p.k.",
|
||||
"Kodeks postępowania administracyjny": "k.p.a.",
|
||||
"Kodeks postępowania administracyjnego": "k.p.a.",
|
||||
"Kodeksie postępowania administracyjnym": "k.p.a.",
|
||||
"Kodeks spółek handlowych": "k.s.h.",
|
||||
"Kodeksu spółek handlowych": "k.s.h.",
|
||||
"Kodeksie spółek handlowych": "k.s.h.",
|
||||
"Kodeks cywilny": "k.c.",
|
||||
"Kodeksu cywilnego": "k.c.",
|
||||
"Kodeksie cywilnym": "k.c.",
|
||||
"Kodeks karny": "k.k.",
|
||||
"Kodeksu karnego": "k.k.",
|
||||
"Kodeksie karnym": "k.k.",
|
||||
"Kodeks rodzinny i opiekuńczy": "k.r.o.",
|
||||
"Kodeks pracy": "k.p.",
|
||||
"Kodeks wykroczeń": "k.w.",
|
||||
}
|
||||
|
||||
|
||||
def test_codes_resolve_by_abbreviation_in_every_case() -> None:
|
||||
got = _found(list(_CODES))
|
||||
for name, code in _CODES.items():
|
||||
assert got[name] == {"id": "code:" + code, "asked": ["resolve?citation=" + ("art. 1 " + code).replace(" ", "%20")]}, name
|
||||
|
||||
|
||||
def test_kodeks_postepowania_cywilnego_never_reaches_the_civil_code() -> None:
|
||||
got = _found(["Kodeks postępowania cywilny", "kodeks postępowania cywilnego", "Kodeksu postępowania cywilnego"])
|
||||
assert {v["id"] for v in got.values()} == {"code:k.p.c."}
|
||||
|
||||
|
||||
def test_konstytucja_is_found_despite_the_date_in_its_title() -> None:
|
||||
names = ["Konstytucja Rzeczypospolitej Polskiej", " Konstytucja Rzeczypospolitej Polskiej", # both from the logs
|
||||
"Konstytucja RP", "Konstytucja", "Konstytucji RP",
|
||||
"Konstytucja Rzeczypospolitej Polskiej z dnia 2 kwietnia 1997 r."]
|
||||
got = _found(names)
|
||||
for n in names:
|
||||
assert got[n]["id"] == "dzu:DU/1997/483", n
|
||||
assert got[n]["asked"] == ["search?kind=act&jurisdiction=pl&limit=6&q=konstytucja%20rzeczypospolitej%20polskiej"], n
|
||||
|
||||
|
||||
def test_titles_that_matched_before_still_match_and_no_other() -> None:
|
||||
got = _found([
|
||||
"Ustawa z dnia 30 maja 2014 r. o prawach konsumenta", "ustawa o prawach konsumenta",
|
||||
"Ustawa o zmianie ustawy o prawach konsumenta",
|
||||
"Ustawa o świadczeniach rodzinnych",
|
||||
"Kodeks karny skarbowy", "Kodeksu karnego skarbowego", "Kodeks karny wykonawczy",
|
||||
"Kodeks postępowania w sprawach o wykroczenia",
|
||||
])
|
||||
assert got["Ustawa z dnia 30 maja 2014 r. o prawach konsumenta"]["id"] == "dzu:DU/2024/1796"
|
||||
assert got["ustawa o prawach konsumenta"]["id"] == "dzu:DU/2024/1796"
|
||||
assert got["Ustawa o zmianie ustawy o prawach konsumenta"]["id"] is None
|
||||
assert got["Ustawa o świadczeniach rodzinnych"]["id"] == "dzu:DU/2024/323" # not k.r.o.
|
||||
assert got["Kodeks karny skarbowy"]["id"] == "dzu:DU/1999/930" # not k.k.
|
||||
for name, v in got.items():
|
||||
assert not any(a.startswith("resolve") for a in v["asked"]), name
|
||||
|
||||
|
||||
def test_a_cut_rewrite_still_names_its_act() -> None:
|
||||
# 3 of the 20.11 exam's rewrites (Bielik) named the right act and were cut by max_tokens 120 before the "}":
|
||||
# the JSON did not parse and the act was lost with it.
|
||||
got = _run("return rewritten(" + json.dumps([
|
||||
'{"akt": "Kodeks postępowania cywilnego", "q": ["sąd właściwy miejscowo", "powództwo o',
|
||||
'{"akt": "Ustawa o \\"ochronie\\" danych", "q": [',
|
||||
'Nie wiem, której ustawy to dotyczy.',
|
||||
'{"akt": "Kodeks pr',
|
||||
'{"akt": "Kodeks cywilny", "q": ["darczyńca może odwołać darowiznę", "rażącej niewdzięczności"]}',
|
||||
]) + ");")
|
||||
assert [{k: g[k] for k in ("act", "queries")} for g in got] == [
|
||||
{"act": "Kodeks postępowania cywilnego", "queries": []},
|
||||
{"act": 'Ustawa o "ochronie" danych', "queries": []},
|
||||
{"act": "", "queries": []},
|
||||
{"act": "", "queries": []},
|
||||
{"act": "Kodeks cywilny", "queries": ["darczyńca może odwołać darowiznę", "rażącej niewdzięczności"]},
|
||||
]
|
||||
assert {g["max_tokens"] for g in got} == {200}
|
||||
@@ -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,203 @@
|
||||
"""Home chat, step 1c (spec 2026-11-27): a question about the law reaches Insider.
|
||||
|
||||
On the 20.11 exam (287 questions on Polish law) code sent 30 of them to the firm's data, before anything was
|
||||
searched: a weak "firm" word ("kto", "rejestr…", "we", "w umowie", "kancelarii") in the question or its answers
|
||||
A-C. Three more ended as a question back, because "w tej sprawie" / "tej umowy" in a first turn read as a
|
||||
reference to the conversation. The questions are copied here once from `router-q.json` (research notes
|
||||
"Lokalny embedding a błędy czatu"), with firm-data questions that must stay where they are today.
|
||||
|
||||
The chat block runs under Node over the in-memory world of `test_chat_traps_console.py`, with a stub of Insider
|
||||
that records what was asked of it. DB-free and network-free; skipped only where no `node` binary exists.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import test_chat_traps_console as traps
|
||||
|
||||
pytestmark = traps.pytestmark
|
||||
|
||||
# The traps world exports a fixed set of names; this file also needs the router and the record matcher.
|
||||
_NAMES = "'chatCarry'];"
|
||||
assert _NAMES in traps._PRELUDE
|
||||
_PRELUDE = traps._PRELUDE.replace(_NAMES, "'chatCarry', 'chatRoute', 'chatNamed'];") + r"""
|
||||
// Insider: on the account, its Dz.U. index ready, an act search that finds nothing. Every call is recorded.
|
||||
const insider = [];
|
||||
const INSIDER = { 'sources': {}, 'sources/datasets': { datasets: [{ name: 'dzu_md', index: { ready: true }, completed_at: '2026-11-01', documents: 1 }] } };
|
||||
const worldFetch = (url) => {
|
||||
const u = new URL(String(url));
|
||||
const m = /^\/insider\/api\/v1\/(.*)$/.exec(u.pathname);
|
||||
if (!m) return null;
|
||||
insider.push(m[1] + u.search);
|
||||
const body = m[1] === 'search' ? { acts: [] } : INSIDER[m[1]];
|
||||
return body === undefined ? new Response('{}', { status: 404 }) : new Response(JSON.stringify(body), { status: 200 });
|
||||
};
|
||||
"""
|
||||
# The world's fetch is wrapped: Insider first, then the four modules and the model as before.
|
||||
_PRELUDE = _PRELUDE.replace(" const fetch = async (url, o = {}) => {\n",
|
||||
" const fetch = async (url, o = {}) => {\n const ins = worldFetch(url); if (ins) return ins;\n", 1)
|
||||
assert "worldFetch(url); if (ins)" in _PRELUDE
|
||||
|
||||
# The rewrite step's answer (no act named) and a closing one; the law path asks the model first.
|
||||
_REPLIES = ['{"akt": "", "q": []}', "Nie znalazłem [1]."]
|
||||
|
||||
|
||||
def _run(js: str) -> object:
|
||||
old = traps._PRELUDE
|
||||
traps._PRELUDE = _PRELUDE
|
||||
try:
|
||||
return traps._run(js)
|
||||
finally:
|
||||
traps._PRELUDE = old
|
||||
|
||||
|
||||
_A_ROUTED_TO_DATA = [
|
||||
("2024-2",
|
||||
"Zgodnie z Kodeksem karnym, kto w zamiarze, aby inna osoba dokonała czynu zabronionego, swoim zachowaniem ułatwia jego popełnienie dostarczając narzędzie, odpowiada za:\nA) sprawstwo kierownicze,\nB) podżeganie,\nC) pomocnictwo.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-3",
|
||||
"Zgodnie z Kodeksem karnym, kto przekracza granice obrony koniecznej pod wpływem strachu lub wzburzenia usprawiedliwionych okolicznościami zamachu:\nA) nie podlega karze,\nB) nie popełnia przestępstwa,\nC) podlega karze, lecz sąd może zastosować nadzwyczajne złagodzenie kary.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-4",
|
||||
"Zgodnie z Kodeksem karnym, nie popełnia przestępstwa, kto:\nA) działając jako sprawca, dobrowolnie zapobiegł dokonaniu czynu zabronionego,\nB) pozostaje w usprawiedliwionym błędzie co do okoliczności stanowiącej znamię czynu zabronionego,\nC) działając jako sprawca czynu zabronionego w chwili czynu miał ograniczoną zdolność jego rozpoznania w stopniu znacznym.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-15",
|
||||
"Zgodnie z Kodeksem postępowania karnego, w postępowaniu karnym oskarżony musi mieć obrońcę, między innymi, jeżeli nie ukończył 18 lat; wówczas udział obrońcy jest obowiązkowy:\nA) w rozprawie oraz w tych posiedzeniach, w których obowiązkowy jest udział oskarżonego,\nB) wyłącznie w rozprawie,\nC) w rozprawie oraz we wszystkich posiedzeniach.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-23",
|
||||
"Zgodnie z Kodeksem wykroczeń, na zasadach określonych w tym Kodeksie odpowiada ten, kto popełnia czyn zabroniony po ukończeniu lat:\nA) 17,\nB) 15,\nC) 13.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-26",
|
||||
"Zgodnie z Kodeksem postępowania w sprawach o wykroczenia, obrońcą w sprawach o wykroczenia może być:\nA) każda osoba najbliższa dla obwinionego,\nB) adwokat albo radca prawny,\nC) każdy, kto posiada pełnię praw obywatelskich.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-40",
|
||||
"Zgodnie z Kodeksem cywilnym, kto z winy swej wyrządził drugiemu szkodę, obowiązany jest do jej naprawienia; nie ponosi jednak odpowiedzialności – na zasadzie winy – za wyrządzoną szkodę małoletni, który nie ukończył lat:\nA) trzynastu,\nB) siedemnastu,\nC) osiemnastu.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-45",
|
||||
"Zgodnie z Kodeksem cywilnym, jeżeli sposób wynagrodzenia agenta nie został w umowie agencyjnej określony:\nA) nigdy nie należy mu się wynagrodzenie,\nB) należy mu się prowizja,\nC) należy mu się wynagrodzenie ryczałtowe.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-48",
|
||||
"Zgodnie z Kodeksem cywilnym, spadkodawca może w testamencie powołać wykonawcę testamentu; wykonawcą testamentu nie może być:\nA) kto nie ma pełnej zdolności do czynności prawnych,\nB) żaden spadkobierca,\nC) osoba wykonująca zawód adwokata, radcy prawnego, notariusza albo komornika.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-77",
|
||||
"Zgodnie z Kodeksem rodzinnym i opiekuńczym, jeżeli oświadczenie o wstąpieniu w związek małżeński zostało złożone przez osobę, która z jakichkolwiek powodów znajdowała się w stanie wyłączającym świadome wyrażenie woli, unieważnienia małżeństwa z tego powodu, przed upływem sześciu miesięcy od ustania tego stanu, a w każdym wypadku przed upływem lat trzech od zawarcia małżeństwa, może żądać:\nA) każdy, kto ma w tym interes prawny,\nB) każdy z małżonków, nawet jeżeli nie złożył oświadczenia dotkniętego tą wadą,\nC) małżonek, który złożył oświadczenie dotknięte tą wadą.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-82",
|
||||
"Zgodnie z ustawą o przeciwdziałaniu nadmiernym opóźnieniom w transakcjach handlowych, jeżeli strony transakcji handlowej przewidziały w umowie zbadanie towaru lub usługi celem potwierdzenia zgodności towaru lub usługi z umową, ustalony w umowie termin tego badania:\nA) nie może być nieuczciwy wobec wierzyciela i nie może przekraczać 14 dni, licząc od dnia otrzymania towaru lub usługi,\nB) nie może być rażąco nieuczciwy wobec wierzyciela i nie może przekraczać 30 dni, licząc od dnia otrzymania towaru lub usługi,\nC) nie może być nieuczciwy wobec wierzyciela i nie może przekraczać 3 miesięcy, licząc od dnia otrzymania towaru lub usługi.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-83",
|
||||
"Zgodnie z ustawą o zastawie rejestrowym i rejestrze zastawów, zastawem rejestrowym można zabezpieczyć:\nA) wierzytelność niepieniężną,\nB) wierzytelność pieniężną wyrażoną wyłącznie w pieniądzu polskim i wierzytelność niepieniężną,\nC) wierzytelność pieniężną wyrażoną w pieniądzu polskim lub walucie obcej.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-84",
|
||||
"Zgodnie z ustawą o zastawie rejestrowym i rejestrze zastawów, zastaw rejestrowy wygasa i podlega wykreśleniu z rejestru zastawów:\nA) w każdym przypadku po upływie pięciu lat od chwili wpisu,\nB) w każdym przypadku po upływie dziesięciu lat od chwili wpisu,\nC) po upływie dwudziestu lat od chwili wpisu, chyba że strony postanowią o utrzymaniu zastawu na czas dalszy, nie dłuższy niż dziesięć lat, i do rejestru zastawów zostanie złożona zmiana umowy zastawniczej.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-85",
|
||||
"Zgodnie z ustawą o Krajowym Rejestrze Sądowym, Krajowy Rejestr Sądowy składa się między innymi z:\nA) rejestru dłużników niewypłacalnych,\nB) krajowego rejestru zadłużonych,\nC) centralnego rejestru beneficjentów rzeczywistych.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-86",
|
||||
"Zgodnie z ustawą o Krajowym Rejestrze Sądowym, wpisy do Krajowego Rejestru Sądowego podlegają, o ile ustawa nie stanowi inaczej, obowiązkowi ogłoszenia:\nA) w Monitorze Polskim,\nB) w Monitorze Sądowym i Gospodarczym,\nC) w Dzienniku Urzędowym Ministra Sprawiedliwości.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-91",
|
||||
"Zgodnie z ustawą – Prawo przedsiębiorców, spółka kapitałowa w organizacji przed wpisem do rejestru przedsiębiorców:\nA) nie może podjąć działalności gospodarczej,\nB) może podjąć działalność gospodarczą,\nC) nie może podjąć działalności gospodarczej, chyba że sąd rejestrowy wyrazi na to zgodę.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-94",
|
||||
"Zgodnie z Kodeksem spółek handlowych, spółka z ograniczoną odpowiedzialnością w organizacji może we własnym imieniu:\nA) nabywać prawa, ale bez prawa własności nieruchomości, zaciągać zobowiązania, pozywać i być pozywana,\nB) nabywać prawa, w tym własność nieruchomości i inne prawa rzeczowe, zaciągać zobowiązania, pozywać i być pozywana,\nC) nabywać prawa, w tym własność nieruchomości i inne prawa rzeczowe, zaciągać zobowiązania, może być pozywana, ale do czasu wpisu spółki do rejestru przedsiębiorców nie może pozywać.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-97",
|
||||
"Zgodnie z Kodeksem spółek handlowych, spółka komandytowo-akcyjna powstaje z chwilą:\nA) zawarcia umowy,\nB) wpisu do rejestru przedsiębiorców,\nC) złożenia wszystkich wymaganych prawem dokumentów do sądu rejestrowego.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-117",
|
||||
"Zgodnie z Kodeksem postępowania administracyjnego, sprawa administracyjna może być załatwiona milcząco:\nA) zawsze kiedy rozstrzygnięcia wydają organy jednostek samorządu terytorialnego,\nB) jeżeli przepis szczególny tak stanowi,\nC) we wszystkich przypadkach dotyczących wydawania zaświadczeń.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-146",
|
||||
"Zgodnie z ustawą o radcach prawnych, pomoc prawna polegająca na występowaniu przez radcę prawnego w charakterze obrońcy w sprawach o przestępstwa i przestępstwa skarbowe może być świadczona w ramach wykonywania zawodu radcy prawnego:\nA) wyłącznie na podstawie stosunku pracy,\nB) w kancelarii radcy prawnego, pod warunkiem że radca prawny nie pozostaje w stosunku pracy, z wyjątkiem zatrudnienia w urzędzie administracji publicznej,\nC) w kancelarii radcy prawnego, pod warunkiem że radca prawny nie pozostaje w stosunku pracy, z wyjątkiem zatrudnienia w charakterze pracownika badawczego i badawczo-dydaktycznego.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-4",
|
||||
"Zgodnie z Kodeksem karnym, odpowiada za podżeganie, kto:\nA) swoim zachowaniem ułatwia innej osobie popełnienie czynu zabronionego,\nB) chcąc, aby inna osoba dokonała czynu zabronionego, nakłania ją do tego,\nC) udziela pomocy innej osobie po popełnieniu przestępstwa.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-5",
|
||||
"Zgodnie z Kodeksem karnym, nie popełnia przestępstwa, kto w obronie koniecznej odpiera bezpośredni, bezprawny zamach na:\nA) jakiekolwiek dobro chronione prawem,\nB) wyłącznie dobro osobiste chronione prawem,\nC) wyłącznie dobro majątkowe chronione prawem.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-12",
|
||||
"Zgodnie z ustawą o przeciwdziałaniu narkomanii, kto, wbrew przepisom ustawy, uprawia krzew koki, podlega karze pozbawienia wolności do lat 3; jeżeli przedmiotem tego czynu jest uprawa mogąca dostarczyć znacznej ilości liści koki, sprawca podlega karze pozbawienia wolności:\nA) od 3 miesięcy do lat 5,\nB) od 6 miesięcy do lat 5,\nC) od 6 miesięcy do lat 8.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-47",
|
||||
"Zgodnie z Kodeksem cywilnym, uznania spadkobiercy za niegodnego może żądać każdy, kto ma w tym interes; z żądaniem takim może wystąpić:\nA) w ciągu roku od dnia, w którym dowiedział się o przyczynie niegodności, nie później jednak niż przed upływem lat trzech od otwarcia spadku,\nB) w ciągu dwóch lat od dnia, w którym dowiedział się o przyczynie niegodności, nie później jednak niż przed upływem lat pięciu od otwarcia spadku,\nC) w ciągu trzech lat od dnia, w którym dowiedział się o przyczynie niegodności, nie później jednak niż przed upływem lat pięciu od otwarcia spadku.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-68",
|
||||
"Zgodnie z Kodeksem postępowania cywilnego, kto ma interes prawny w tym, aby sprawa została rozstrzygnięta na korzyść jednej ze stron, może w każdym stanie sprawy przystąpić do tej strony (interwencja uboczna) aż do:\nA) zakończenia postępowania dowodowego w pierwszej instancji,\nB) zamknięcia rozprawy w pierwszej instancji,\nC) zamknięcia rozprawy w drugiej instancji.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-85",
|
||||
"Zgodnie z ustawą o przeciwdziałaniu nadmiernym opóźnieniom w transakcjach handlowych, w transakcjach handlowych, w których dłużnikiem jest podmiot publiczny:\nA) wierzycielowi, bez wezwania, przysługują odsetki ustawowe za opóźnienie w transakcjach handlowych, jeżeli wierzyciel spełnił swoje świadczenie i nie otrzymał zapłaty w terminie określonym w umowie,\nB) wierzycielowi, bez wezwania, w każdym przypadku, przysługują odsetki ustawowe za opóźnienie w transakcjach handlowych,\nC) wierzycielowi nigdy nie przysługują odsetki ustawowe za opóźnienie w transakcjach handlowych.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-86",
|
||||
"Zgodnie z ustawą o zastawie rejestrowym i rejestrze zastawów, umowa zastawnicza powinna być zawarta:\nA) pod rygorem nieważności na piśmie; do umów o ustanowienie zastawu rejestrowego na wierzytelnościach i prawach nie stosuje się przepisów o formie pisemnej szczególnej określonej w odrębnych przepisach,\nB) pod rygorem nieważności w formie dokumentowej; do umów o ustanowienie zastawu rejestrowego na wierzytelnościach i prawach stosuje się odpowiednio przepisy o formie pisemnej szczególnej określonej w odrębnych przepisach,\nC) dla celów dowodowych na piśmie; do umów o ustanowienie zastawu rejestrowego na wierzytelnościach i prawach stosuje się odpowiednio przepisy o formie pisemnej szczególnej określonej w odrębnych przepisach.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-87",
|
||||
"Zgodnie z ustawą o zastawie rejestrowym i rejestrze zastawów, przeniesienie zastawu rejestrowego:\nA) może być dokonane tylko wraz z przeniesieniem wierzytelności zabezpieczonej tym zastawem,\nB) zawsze może być dokonane bez przeniesienia wierzytelności zabezpieczonej tym zastawem,\nC) nigdy nie może zostać dokonane.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-88",
|
||||
"Zgodnie z ustawą o Krajowym Rejestrze Sądowym, podmiot obowiązany do złożenia wniosku o wpis do Krajowego Rejestru Sądowego:\nA) może powoływać się wobec osób trzecich działających w dobrej wierze na dane, które nie zostały wpisane do Krajowego Rejestru Sądowego lub uległy wykreśleniu z Krajowego Rejestru Sądowego,\nB) nie może powoływać się wobec osób trzecich działających w dobrej wierze na dane, które nie zostały wpisane do Krajowego Rejestru Sądowego lub uległy wykreśleniu z Krajowego Rejestru Sądowego,\nC) może powoływać się wobec osób trzecich działających zarówno w dobrej wierze, jak i w złej wierze na dane, które nie zostały wpisane do Krajowego Rejestru Sądowego lub uległy wykreśleniu z Krajowego Rejestru Sądowego.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-99",
|
||||
"Zgodnie z Kodeksem spółek handlowych, rozwiązanie spółki z ograniczoną odpowiedzialnością następuje po przeprowadzeniu likwidacji, z chwilą:\nA) zaspokojenia wszystkich jej wierzycieli,\nB) złożenia bilansu likwidacyjnego do rejestru przedsiębiorców,\nC) wykreślenia spółki z rejestru przedsiębiorców.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
]
|
||||
|
||||
_A2_ASKED_BACK = [
|
||||
("2024-17",
|
||||
"Zgodnie z Kodeksem postępowania karnego, prokurator w postępowaniu przygotowawczym:\nA) może uchylić tymczasowe aresztowanie zastosowane przez sąd w tej sprawie, tylko na wniosek tymczasowo aresztowanego,\nB) nie może uchylić tymczasowego aresztowania zastosowanego przez sąd w tej sprawie,\nC) może uchylić tymczasowe aresztowanie zastosowane przez sąd w tej sprawie.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2024-19",
|
||||
"Zgodnie z Kodeksem postępowania karnego, jeżeli oskarżony odmawia wyjaśnień na rozprawie głównej, wolno odczytywać tylko w odpowiednim zakresie:\nA) protokoły jego zeznań złożonych poprzednio w charakterze świadka w tej sprawie,\nB) protokoły jego wyjaśnień złożonych poprzednio w charakterze oskarżonego w tej lub innej sprawie w postępowaniu przygotowawczym lub przed sądem albo w innym postępowaniu przewidzianym przez ustawę,\nC) wszelkie protokoły jego zeznań i wyjaśnień za zgodą jego obrońcy.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
("2025-54",
|
||||
"Zgodnie z ustawą o ochronie praw lokatorów, mieszkaniowym zasobie gminy i o zmianie Kodeksu cywilnego, umowa najmu instytucjonalnego lokalu oraz zmiany tej umowy wymagają formy:\nA) pisemnej pod rygorem nieważności,\nB) pisemnej z podpisami notarialnie poświadczonymi,\nC) aktu notarialnego.\nKtóra odpowiedź jest prawidłowa? Podaj literę i podstawę prawną."),
|
||||
]
|
||||
|
||||
# Firm-data questions: no act named, a strong firm word, a list of the register, or a record named.
|
||||
_FIRM = [
|
||||
"Kto prowadzi sprawę Velmory?",
|
||||
"Co mamy w rejestrze umów?",
|
||||
"Co mamy w rejestrze umów na temat przedawnienia?",
|
||||
"Jakie umowy mamy z firmą Alfa?",
|
||||
"Czy nasza umowa najmu przewiduje karę umowną?",
|
||||
"Jakie terminy ma mój klient według ustawy?",
|
||||
"Jakie sprawy prowadzimy dla klienta Beta S.A. i jakie przepisy prawa mają zastosowanie?",
|
||||
"Jaki jest NIP kontrahenta Kalinowy Dwór?",
|
||||
"Kto w kancelarii prowadzi sprawę 2026/0001?",
|
||||
"What law applies to the contracts we have with Alfa?",
|
||||
"Pokaż wszystkie umowy, które podlegają ustawie o prawach konsumenta",
|
||||
"Ile umów jest w rejestrze z klauzulą o karze umownej?",
|
||||
"Które umowy wygasają w ciągu najbliższych 60 dni?",
|
||||
"Co mówi Kodeks cywilny o wypowiedzeniu umowy UM-2026-0001?",
|
||||
"Czy ustawa o prawach konsumenta dotyczy umowy Najem biura?",
|
||||
]
|
||||
|
||||
# A reference in a first turn, as code answers it on unchanged app.js (7f753f5) with the replies above.
|
||||
_REFS_TODAY = {
|
||||
"Czy ta umowa obowiązuje?": "ask",
|
||||
"Kiedy kończy się ta umowa?": "ask",
|
||||
"Kto jest kontrahentem w tej umowie?": "ask",
|
||||
"Kto prowadzi tę sprawę?": "ask",
|
||||
"Co jest w tej umowie o karze umownej?": "ask",
|
||||
"Ile umów jest w statusie szkic i jakie to umowy?": "fallback",
|
||||
}
|
||||
|
||||
|
||||
def test_a_the_exam_questions_sent_to_the_data_take_the_law_path() -> None:
|
||||
qs = [q for _, q in _A_ROUTED_TO_DATA]
|
||||
assert len(qs) == 30
|
||||
got = _run(f"const s = session(); return {json.dumps(qs, ensure_ascii=False)}.map((q) => s.f.chatRoute(q));")
|
||||
wrong = [i for (i, _), r in zip(_A_ROUTED_TO_DATA, got, strict=True) if r not in ("law_topic", "law_cite")]
|
||||
assert wrong == []
|
||||
|
||||
|
||||
def test_b_a_reference_inside_a_law_question_is_not_asked_back() -> None:
|
||||
qs = [q for _, q in _A2_ASKED_BACK]
|
||||
got = _run(f"""const out = [];
|
||||
for (const q of {json.dumps(qs, ensure_ascii=False)}) {{
|
||||
insider.length = 0; const s = session({json.dumps(_REPLIES)}); const a = await s.ask(q);
|
||||
out.push({{ coded: a.coded || null, searched: insider.some((c) => c.startsWith('search?')) }});
|
||||
}}
|
||||
return out;""")
|
||||
assert len(got) == 3 and all(g["coded"] != "ask" and g["searched"] for g in got), got
|
||||
|
||||
|
||||
def test_c_firm_questions_stay_with_the_data() -> None:
|
||||
# The router as chatTurn asks it: with the number of records the question names.
|
||||
got = _run(f"""const s = session(); const ix = await s.index();
|
||||
return {json.dumps(_FIRM, ensure_ascii=False)}.map((q) => s.f.chatRoute(q, s.f.chatNamed(q, ix.records).length));""")
|
||||
assert dict(zip(_FIRM, got, strict=True)) == {q: "data" for q in _FIRM}
|
||||
|
||||
|
||||
def test_c_a_reference_in_a_firm_question_is_answered_as_today() -> None:
|
||||
qs = list(_REFS_TODAY)
|
||||
got = _run(f"""const out = [];
|
||||
for (const q of {json.dumps(qs, ensure_ascii=False)}) {{ const s = session({json.dumps(_REPLIES)}); out.push((await s.ask(q)).coded || null); }}
|
||||
return out;""")
|
||||
assert dict(zip(qs, got, strict=True)) == _REFS_TODAY
|
||||
|
||||
|
||||
def test_c_after_a_contract_its_provisions_are_that_contracts() -> None:
|
||||
# czat-v2 (provisions-zawada, provisions-kodar, user-ii-thread): a second turn asking about "ta umowa"'s
|
||||
# provisions went to Insider once law questions skipped references in every turn, not just the first.
|
||||
got = _run("""const s = session(['Umowa UM-2026-0001 Najem biura [1].', 'Odpowiedź [1].']);
|
||||
await s.ask('Pokaż umowę UM-2026-0001'); insider.length = 0;
|
||||
const a = await s.ask('Czy przepisy, na które powołuje się ta umowa, są aktualne?');
|
||||
const searched = insider.some((c) => c.startsWith('search?'));
|
||||
// After a turn that failed and named nothing, "ta umowa" is still asked about, as before step 1c.
|
||||
const f = session(['Odpowiedź [1].']); f.turns.push({ role: 'user', content: 'Jaką umowę mamy z Kodar Cloud?' },
|
||||
{ role: 'assistant', content: 'Nie udało się.', failed: true }); insider.length = 0;
|
||||
const b = await f.ask('Czy przepisy, na które powołuje się ta umowa, są aktualne?');
|
||||
return { coded: a.coded || null, mentioned: a.mentioned, after_failed: b.coded || null,
|
||||
searched: searched || insider.some((c) => c.startsWith('search?')) };""")
|
||||
assert got == {"coded": None, "mentioned": ["galena:umowa:c1"], "after_failed": "ask", "searched": False}
|
||||
@@ -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]
|
||||
@@ -168,12 +168,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|workflow)" 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|workflow)" 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|workflow)" in push
|
||||
assert "case $ADD in galena|agora|parafa|workflow)" 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", "workflow")
|
||||
#: 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,workflow\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,workflow_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,7 +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, "
|
||||
"lexicon_app, agora_app, panorama_app, parafa_app, scribe_app, "
|
||||
"workflow_app"}})
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
|
||||
@@ -669,7 +663,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+12 apps x", on.stdout), on.stdout
|
||||
assert re.search(r"budget\s+4 apps x", off.stdout), off.stdout
|
||||
|
||||
|
||||
|
||||
@@ -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) == []
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -254,10 +254,6 @@ 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/"),
|
||||
}
|
||||
|
||||
|
||||
|
||||
+2
-2
@@ -38,10 +38,10 @@ 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
|
||||
# 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),
|
||||
# and Workflow, the approval engine (deploy/RUNBOOK-workflow.md).
|
||||
# COMPOSE_PROFILES=insider,arbiter,lexicon,agora,parafa,scribe,workflow
|
||||
# COMPOSE_PROFILES=insider,arbiter,lexicon,agora,panorama,parafa,scribe,workflow
|
||||
# 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).
|
||||
|
||||
+5
-10
@@ -60,24 +60,19 @@ 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
|
||||
@@ -152,7 +147,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`, `<site>/workflow`; `/` 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
|
||||
```
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -205,6 +213,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
|
||||
|
||||
@@ -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
|
||||
|
||||
+102
-12
@@ -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, /scribe and /workflow 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, /scribe and /workflow: 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).
|
||||
@@ -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, workflow-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, Scribe or Workflow 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,workflow=http://workflow-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,6 +192,7 @@ services:
|
||||
arbiter: {}
|
||||
lexicon: {}
|
||||
agora: {}
|
||||
panorama: {}
|
||||
parafa: {}
|
||||
scribe: {}
|
||||
workflow: {}
|
||||
@@ -527,7 +528,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 +557,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 +607,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 +636,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 +745,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 +902,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 +930,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:
|
||||
@@ -989,6 +1074,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:
|
||||
@@ -1007,7 +1096,7 @@ volumes:
|
||||
# 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),
|
||||
# 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,
|
||||
# workflow-data Workflow's run files and request attachments.
|
||||
# `down` without -v keeps them; to stop the stack, use `docker compose down` or `stop`. Back them up
|
||||
@@ -1020,6 +1109,7 @@ volumes:
|
||||
arbiter-data:
|
||||
lexicon-data:
|
||||
agora-data:
|
||||
panorama-data:
|
||||
parafa-data:
|
||||
scribe-data:
|
||||
workflow-data:
|
||||
|
||||
@@ -105,7 +105,7 @@ 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
|
||||
@@ -145,6 +145,8 @@ 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=
|
||||
@@ -171,6 +173,8 @@ 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
|
||||
|
||||
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
+12
-14
@@ -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, Scribe and Workflow 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
|
||||
@@ -83,23 +83,21 @@ MODEL_PROVIDER_MIGRATOR_ROLES=arbiter_migrator
|
||||
# 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
|
||||
# its run events (dredd_core.workflow_contract), so workflow_app is listed as well.
|
||||
MODULE_EVENT_EMITTER_ROLES=galena_app,agora_app,parafa_app,workflow_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=
|
||||
|
||||
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
# deploy/env/panorama.env — Panorama's backend, on the platform.
|
||||
#
|
||||
# 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/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 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 /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.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 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
|
||||
# IS the single sign-on, and there is no handoff protocol to configure.
|
||||
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=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 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: 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://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
|
||||
DB_MAX_OVERFLOW=8
|
||||
|
||||
CORS_ALLOW_ORIGINS=
|
||||
|
||||
DATA_DIR=/data
|
||||
# A production module seeds no demo content: the platform's people and documents are real.
|
||||
SEED_DEMO=false
|
||||
|
||||
# ── 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
|
||||
LOGIN_MAX_ATTEMPTS=5
|
||||
LOGIN_LOCKOUT_MINUTES=15
|
||||
# Empty = auto-detect from the request scheme (Secure over HTTPS only).
|
||||
SESSION_COOKIE_SECURE=
|
||||
# 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=panorama-backend
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
# 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
|
||||
# (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 panorama_migrator on this box's own PostgreSQL ──────────
|
||||
# Plain role name, the `postgres` service, LOCAL_DB_NAME from deploy/.env, no TLS parameters (see
|
||||
# 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 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
|
||||
# administrator, whom the seed looks up. The PASSWORD is inert on the platform, but push.sh's
|
||||
# preflight refuses an empty, default or short one (12+ characters), so it stays set; init.sh
|
||||
# generates it. Standalone (`./init.sh --standalone`): the seed creates this module's own first
|
||||
# administrator with them when no user has the EMAIL.
|
||||
BOOTSTRAP_ADMIN_EMAIL=admin@example.com
|
||||
BOOTSTRAP_ADMIN_PASSWORD=
|
||||
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
|
||||
|
||||
|
||||
+32
-33
@@ -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, /workflow, 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,8 +19,9 @@
|
||||
# ./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)
|
||||
@@ -28,7 +29,7 @@
|
||||
# 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, Scribe and Workflow 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
|
||||
@@ -41,7 +42,7 @@
|
||||
# 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
|
||||
# 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 +101,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 workflow"
|
||||
# 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 workflow"
|
||||
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\}//'; }
|
||||
|
||||
@@ -428,28 +429,19 @@ write_app_files() {
|
||||
# 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 ;;
|
||||
# step of a run, dredd_core.workflow_contract); 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,"$ROLE_PREFIX"workflow_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"
|
||||
@@ -483,9 +475,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,11 +490,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" ;;
|
||||
set_key "$runtime" GALENA_URL "$PUBLIC/galena" ;;
|
||||
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
|
||||
@@ -539,11 +534,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, Parafa and Workflow take part in the shared event log (push.sh checks them with --events).
|
||||
case $ADD in galena|agora|parafa|workflow)
|
||||
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 +713,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,13 +41,13 @@ 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,
|
||||
- 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, Scribe's and Workflow's data volumes survived the merge
|
||||
|
||||
Standard library only. Exit 0 = every property holds, 1 = a property failed (each one printed),
|
||||
@@ -59,14 +59,14 @@ import json
|
||||
import sys
|
||||
|
||||
HUB = "atrium"
|
||||
MODULES = ("galena", "sygna", "counsel", "insider", "arbiter", "lexicon", "agora",
|
||||
MODULES = ("galena", "sygna", "counsel", "insider", "arbiter", "lexicon", "agora", "panorama",
|
||||
"parafa", "scribe", "workflow")
|
||||
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",
|
||||
"lexicon": "/data", "agora": "/data", "panorama": "/data", "parafa": "/data",
|
||||
"scribe": "/data", "workflow": "/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
|
||||
@@ -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, Workflow) 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, Scribe and Workflow from `${MODULES_DIR}/lexicon`, `/agora`, `/panorama`, `/parafa`, `/scribe` and `/workflow`),
|
||||
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...ea1e8ea26c
+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
+1
-1
Submodule deploy/modules/workflow updated: d379ce2288...4adfacaa7e
+25
-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 workflow; 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 workflow; 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 WORKFLOW; 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 --profile workflow "$@"
|
||||
}
|
||||
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 --profile workflow "$@"
|
||||
}
|
||||
# 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 workflow-backend workflow-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 workflow-backend workflow-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" \n "$tmp/env/workflow.env" "$tmp/env/workflow.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-"*|*" workflow-"*) 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" \n "$tmp/env-aside/workflow.env" "$tmp/env-aside/workflow.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 --profile workflow \
|
||||
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 workflow; 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 workflow; 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,27 @@ 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, Scribe and Workflow (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,workflow
|
||||
sed -e 's/^IDENTITY_READER_ROLES=.*/&,lexicon_app,agora_app,panorama_app,parafa_app,scribe_app,workflow_app/' \
|
||||
-e 's/^IDENTITY_MIGRATOR_ROLES=.*/&,lexicon_migrator,agora_migrator,panorama_migrator,parafa_migrator,scribe_migrator,workflow_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"
|
||||
&& grep -q "^ budget 12 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, panorama, parafa, scribe and workflow, and the budget counts twelve 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, Scribe and Workflow 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
-34
@@ -8,11 +8,11 @@
|
||||
# [--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] [workflow]
|
||||
#
|
||||
# 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,
|
||||
# panorama, 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, panorama,
|
||||
# parafa, scribe, workflow).
|
||||
#
|
||||
# 1. preflight before anything connects, for EVERY selected app: the platform admin's URL is
|
||||
@@ -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 workflow"
|
||||
# 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 workflow"
|
||||
# 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|workflow) 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_*|WORKFLOW_*)
|
||||
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, Scribe and Workflow 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,19 @@ 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' ;;
|
||||
workflow) printf 'https://github.com/Alpaq92/Workflow' ;;
|
||||
esac
|
||||
}
|
||||
|
||||
@@ -389,14 +390,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,7 +404,8 @@ 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.
|
||||
@@ -466,23 +467,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), and Workflow (its runs' events; it pins 0.24.0).
|
||||
case $slug in galena|agora|parafa|workflow)
|
||||
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 +492,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 +744,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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Atrium on a managed PostgreSQL provider (the family's shared database): an override for docker-compose.yml.
|
||||
#
|
||||
# DREDD_CORE_TOKEN=<read-only Gitea token> \
|
||||
# DREDD_CORE_TOKEN=github_pat_... \
|
||||
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
|
||||
#
|
||||
# The database is the family's shared managed database (one database for Atrium, Galena, Sygna and
|
||||
|
||||
+1
-1
@@ -65,6 +65,6 @@ secrets:
|
||||
# Used only by the build stage's one `pip install`; no running container gets it. Compose resolves
|
||||
# the variable from the shell OR the project .env (shell wins) — keep it in the shell, because every
|
||||
# service here also loads .env at runtime and would receive the token:
|
||||
# DREDD_CORE_TOKEN=<read-only Gitea token> docker compose up -d --build
|
||||
# DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build
|
||||
dredd_core_token:
|
||||
environment: DREDD_CORE_TOKEN
|
||||
|
||||
+6
-10
@@ -1,4 +1,4 @@
|
||||
# Co dalej (stan na 25.11.2026)
|
||||
# Co dalej (stan na 24.11.2026)
|
||||
|
||||
Jedno miejsce z tym, co czeka i w jakiej kolejności.
|
||||
|
||||
@@ -77,13 +77,9 @@ Dwa plany ciągną Parafę w różne strony:
|
||||
Atrium#53 wspomina też trzy problemy bezpieczeństwa średniej wagi w Parafie, znalezione przy
|
||||
kopiowaniu szkieletu do Workflow. Warto zapisać je w zgłoszeniu w repo Parafy, żeby nie zginęły.
|
||||
|
||||
## 4. Przeglądy pozostałych modułów
|
||||
## 4. Poza zasięgiem konta `piotrchojnacki`
|
||||
|
||||
Od 25.11 konto `piotrchojnacki` ma dostęp z prawem zapisu do wszystkich modułów platformy
|
||||
([Atrium#55](https://github.com/Alpaq92/Atrium/issues/55)). Dotąd przegląd bezpieczeństwa (tylko kod)
|
||||
i przegląd dostępności konsol objęły Atrium, Sygnę, Parafę, Counsel Scorecard i `dredd-core`.
|
||||
|
||||
- [ ] Przegląd bezpieczeństwa i dostępności **Galeny i Workflow**: najważniejsze, bo Galena jest
|
||||
włączona wszędzie, a Workflow właśnie wchodzi na platformę.
|
||||
- [ ] Ten sam przegląd dla **Arbitra, Lexiconu, Scribe, Agory, Panoramy i Insidera**. Warto ustalić
|
||||
kolejność z planem w #53: moduły, które się łączą albo znikają (Panorama), mogą poczekać.
|
||||
To konto nie ma dostępu do repozytoriów Galena, Workflow, Arbiter, Lexicon, Scribe, Agora,
|
||||
Panorama i Insider. Przeglądy (bezpieczeństwo, dostępność) objęły tylko Atrium, Sygnę, Parafę,
|
||||
Counsel Scorecard i `dredd-core`. Jeśli pozostałe moduły mają przejść ten sam przegląd, potrzebny
|
||||
jest dostęp.
|
||||
|
||||
@@ -1,224 +0,0 @@
|
||||
# Idea 01: osiem propozycji rozwoju Dredd
|
||||
|
||||
Stan na 27.11.2026. Status: do dyskusji.
|
||||
|
||||
Propozycje funkcji uporządkowane według wartości dla kancelarii i wysiłku. Odnoszą się do planu modułów
|
||||
z Atrium#53 i do PR-ów z 27.11 (Atrium#65 i pozostałe).
|
||||
|
||||
| # | Propozycja | Gdzie | Wysiłek | Zależy od |
|
||||
|---|---|---|---|---|
|
||||
| 1 | Przegląd zbiorczy: skill na wielu plikach, wynik w tabeli | „Umowy” (czat) | L | Plan 3 skilli, treść umowy z Galeny, usługa wykonawcza z repo Arbitra |
|
||||
| 2 | Sprawdzenie umocowania podpisujących w KRS | Parafa, karta umowy | M | Parafa jako bramka (Parafa#7), kartoteka kontrahentów |
|
||||
| 3 | Zmiany w rejestrach u kontrahentów | Sygna, strona główna | M | Sygna jako emitent zdarzeń |
|
||||
| 4 | Zakres wyszukiwania w czacie | Atrium (czat), Insider | S | wspólny kontrakt czatu |
|
||||
| 5 | Obserwowane przepisy w sprawie | Insider, Sygna, strona główna | M–L | Insider jako emitent zdarzeń |
|
||||
| 6 | Odpowiedź do akt sprawy | Atrium (czat), Galena, Scribe | S–M | decyzja o Galenie (Galena#19) |
|
||||
| 7 | Procedura widoczna w odpowiedzi | Atrium (czat), Skille i agenci | S | Plan 3 skilli |
|
||||
| 8 | Nowe źródła w Insiderze | Insider | L | warunki ponownego wykorzystania danych |
|
||||
|
||||
**Wygląd we wszystkich punktach:** „Atrium UI v1” w trybie narzędzia pracy (Operate), tylko dopracowanie
|
||||
istniejącego stylu.
|
||||
- Istniejące tokeny: `--surface`, `--border`, `--accent`, `--ok/--warn/--err` z tłami `-bg`, `--mono`.
|
||||
- Istniejące klasy: `.card`, `.chip`, `.btn sm ghost`, `.banner`, `.modal wide`, `.review-panel`, `.stack`.
|
||||
- Standardowe kontrolki. Stan zawsze nazwany słowem, nie samym kolorem.
|
||||
- Dostępność jak po ostatnich przeglądach: `aria-pressed`, `aria-live`, fokus i Esc w oknach.
|
||||
|
||||
## 1. Przegląd zbiorczy (L)
|
||||
|
||||
**Po co.** Due diligence spółki (kilkaset umów w data roomie), audyt umów klienta pod nowe przepisy,
|
||||
seryjne dokumenty korporacyjne. Dziś sprawdzenie skillem obejmuje jedną umowę: czat zamawia je w
|
||||
Arbiterze, raport otwiera się w panelu obok, a prawnik akceptuje analizę.
|
||||
|
||||
**Propozycja.**
|
||||
- Ten sam skill, z wersją i standardami, uruchomiony na wielu plikach z Galeny albo ze sprawy.
|
||||
- Do tego opcjonalne kolumny-pytania, np. zmiana kontroli, okres wypowiedzenia, wysokość kar umownych.
|
||||
- Wynik to tabela: wiersz to plik, kolumna to pytanie. Każda komórka ma cytat i miejsce w pliku.
|
||||
- Przed uruchomieniem całości próba na pierwszym pliku, tak jak próba skilla.
|
||||
- Gotowy przegląd idzie do akceptacji analizy w Workflow. Eksport XLSX i DOCX.
|
||||
|
||||
**Wygląd.**
|
||||
- Start z czatu („sprawdź te 40 umów skillem X”: asystent proponuje przegląd i podaje liczbę plików)
|
||||
albo z zakładki w „Umowach”.
|
||||
- Lista przeglądów to zwykła tabela. Status to `.chip` ze słowem: „W toku 12/40”, „Gotowe”, „2 pliki z
|
||||
błędem”, na `--ok-bg`/`--warn-bg`/`--err-bg`. Liczby w `--mono`.
|
||||
- Wynik to tabela z sortowanymi nagłówkami. Klik w komórkę otwiera istniejący `.review-panel` z cytatem.
|
||||
- Kolumny ustawia się w `.modal wide`, listą `.field`.
|
||||
|
||||
**Tajemnica adwokacka.**
|
||||
- Tylko dostawcy modeli firmy (`model_provider`, także lokalny serwer).
|
||||
- Każdy przegląd zapisuje zdarzenie w `module_event`.
|
||||
- Wynik widzą tylko osoby z dostępem do sprawy.
|
||||
- Limit kosztu na przegląd przy kluczu firmowym.
|
||||
|
||||
**Zależności.** Plan 3 skilli (#53, sekcja 2), treść umowy z Galeny (#53, sekcja 5), wykonanie w usłudze z
|
||||
repo Arbitra (#53, ustalenie 5). Nazwa „przegląd zbiorczy”, żeby nie mylić z Workflow, czyli silnikiem
|
||||
akceptacji.
|
||||
|
||||
## 2. Sprawdzenie umocowania podpisujących w KRS (M)
|
||||
|
||||
**Po co.** Wadliwa reprezentacja to klasyczna wada umowy. Typowe przypadki:
|
||||
- działanie bez umocowania (art. 39 i 103 k.c.);
|
||||
- domyślna reprezentacja łączna (art. 205 i 373 k.s.h.);
|
||||
- umowa spółki z członkiem zarządu (art. 210 k.s.h.).
|
||||
|
||||
Najtaniej wyłapać ją tuż przed podpisem.
|
||||
|
||||
**Co już mamy.** Sygna pobiera odpis aktualny KRS (rejestry P i S) i dane z białej listy
|
||||
(`integrations/registers.py`). dredd-core 0.21 ma wspólną kartotekę kontrahentów. Parafa przygotowuje
|
||||
podpis.
|
||||
|
||||
**Propozycja.**
|
||||
- Przed wysłaniem do dostawcy podpisu Parafa pobiera aktualny odpis KRS strony i sprawdza, czy osoby
|
||||
wskazane do podpisu mogą ją razem reprezentować. Czy są w zarządzie albo są prokurentami i czy jest ich
|
||||
tylu, ilu wymaga zasada reprezentacji zapisana w odpisie.
|
||||
- Reguły są zwykłym kodem, bo odpis podaje zasadę reprezentacji wprost. Model tylko odczytuje z umowy, kto
|
||||
ma podpisać i w jakim charakterze, jeśli nie ma tego na karcie umowy.
|
||||
- Kontrola doradza i nie blokuje, jak test standardów (#53, ustalenie 6). Wynik trafia na kartę umowy.
|
||||
|
||||
**Wygląd.**
|
||||
- Nad listą podpisujących `.banner` „Umocowanie według KRS (odpis z dnia …)”.
|
||||
- Pod nim tabela: osoba, funkcja w KRS, wynik.
|
||||
- Wynik to `.chip` ze słowem: „zgodne”, „potrzebna druga osoba”, „brak w KRS”, „pełnomocnictwo: dołącz
|
||||
dokument”. Obok link do odpisu.
|
||||
|
||||
**Zależności.** Parafa jako bramka (Parafa#7). Do decyzji: odczyt KRS z Sygny przez API albo przeniesienie
|
||||
integracji do dredd-core.
|
||||
|
||||
## 3. Zmiany w rejestrach u kontrahentów (M)
|
||||
|
||||
**Po co.**
|
||||
- **AML:** bieżące monitorowanie stosunków gospodarczych (art. 34 ust. 1 pkt 4 ustawy AML) przy
|
||||
czynnościach objętych ustawą. Zmiana zarządu albo wspólników klienta to sygnał do ponownej oceny
|
||||
ryzyka.
|
||||
- **Konflikty interesów:** przeciwnik przejmuje spółkę albo zmienia nazwę.
|
||||
- **Doręczenia:** nowy adres strony w toczącej się sprawie.
|
||||
- **VAT:** status i rachunki z białej listy przy fakturach w KSeF i płatnościach powyżej 15 tys. zł.
|
||||
|
||||
**Co już mamy.** Sygna pobiera na żądanie odpis KRS i dane z białej listy, pisze do kartoteki kontrahentów
|
||||
i ma powiadomienia (`models/notification.py`). Brakuje cyklicznego sprawdzania i historii.
|
||||
|
||||
**Propozycja.**
|
||||
- W karcie kontrahenta przełącznik „Powiadamiaj o zmianach w KRS i na białej liście”. Domyślnie jest
|
||||
włączony dla klientów z aktywną sprawą i kontrahentów z oceną AML.
|
||||
- Zadanie dzienne w Sygnie porównuje odpis z poprzednim i zapisuje różnice w tym, co ważne dla kancelarii:
|
||||
zarząd, prokura, wspólnicy, adres, likwidacja i upadłość.
|
||||
- CEIDG później, bo jego API wymaga tokenu.
|
||||
|
||||
**Wygląd.**
|
||||
- Zakładka „Historia zmian” w karcie kontrahenta: lista `.stack`, data w `--mono`, „było → jest”.
|
||||
- Zmiany ważne dla AML i umocowania mają `--warn-bg` i podpis słowem.
|
||||
- Na stronie głównej jedna `.card` „Zmiany u kontrahentów (3)” z odnośnikami do spraw.
|
||||
- Powiadomienie w Sygnie, bez maili.
|
||||
|
||||
**Zależności.**
|
||||
- Sygna musi emitować zdarzenia do `module_event`. Po Atrium#65 emitują Galena, Agora, Parafa, Workflow
|
||||
i Arbiter; Sygny na tej liście nie ma.
|
||||
- Strona główna po Panoramie (#53, ustalenie 2).
|
||||
- Dzienny limit zapytań do API MS i MF.
|
||||
|
||||
## 4. Zakres wyszukiwania w czacie (S)
|
||||
|
||||
**Po co.** Prawnik ma widzieć i decydować, czy pytanie o dokument klienta zostaje w aktach, czy idzie też do
|
||||
Insidera. Dziś chipy „Szuka w:” (`.home-scope`) tylko informują.
|
||||
|
||||
**Propozycja.**
|
||||
- Chipy stają się przełącznikami.
|
||||
- Chip Insidera rozwija listę źródeł: Dz.U. i M.P., EUR-Lex, orzeczenia (SAOS), biblioteka Lexiconu.
|
||||
- Zakres obowiązuje do „Nowej rozmowy” i jest przekazywany modułom w zapytaniu.
|
||||
- Wyszukiwania w sieci nie dodajemy bez polityki firmy. Jeśli kiedyś, to wyłączone domyślnie i z blokadą
|
||||
administratora w *Ogólne*.
|
||||
|
||||
**Wygląd.**
|
||||
- `.home-scope-mod` jako `<button aria-pressed>`. Wyłączony chip ma `--text-faint` i przekreśloną ikonę.
|
||||
- Przy wyłączonych źródłach krótki tekst „Bez: Insider”.
|
||||
- Lista źródeł Insidera w małym popoverze (`.card`, checkboxy w `.field`), z fokusem i Esc jak w oknach.
|
||||
|
||||
**Zależności.** Wspólny kontrakt czatu w dredd-core (#53, sekcja 3).
|
||||
|
||||
## 5. Obserwowane przepisy w sprawie (M–L)
|
||||
|
||||
**Po co.** Sprawy trwają latami. Prawnik musi wiedzieć o nowelizacji, nowym tekście jednolitym albo wyroku
|
||||
TK, który dotyczy przepisu, na którym stoi pozew, umowa czy opinia. Data wejścia w życie to też termin.
|
||||
|
||||
**Co już mamy.** Insider ma:
|
||||
- indeks ELI (Dz.U. i M.P., z polami `changeDate` i `inForce` oraz odnośnikami do tekstów jednolitych);
|
||||
- EUR-Lex/Cellar i SAOS;
|
||||
- graf przepisów (`legalgraph`).
|
||||
|
||||
Subskrypcji zmian nie ma.
|
||||
|
||||
**Propozycja.**
|
||||
- „Obserwuj” przy artykule, w odpowiedzi czatu i w Insiderze, z wyborem sprawy z Sygny.
|
||||
- Zadanie dzienne w Insiderze sprawdza w ELI zmiany obserwowanego aktu: nowe akty zmieniające, nowy tekst
|
||||
jednolity, zmianę stanu obowiązywania. Wyroki TK są ogłaszane w Dz.U., więc też są w ELI.
|
||||
- Zmiana daje zdarzenie, kartę na stronie głównej i wpis w sprawie.
|
||||
- Bez modelu: wykrycie zmiany i porównanie brzmienia są deterministyczne. Streszczenie modelem tylko na
|
||||
żądanie.
|
||||
|
||||
**Wygląd.**
|
||||
- `.btn sm ghost` „Obserwuj”.
|
||||
- Na stronie głównej `.card` „Zmiany w obserwowanych przepisach”.
|
||||
- Po kliknięciu porównanie brzmienia w `.prose` (`<del>`/`<ins>` na `--err-bg`/`--ok-bg`, z opisem
|
||||
słownym dla czytników ekranu).
|
||||
- Pod porównaniem data wejścia w życie z przyciskiem „Dodaj termin w sprawie”.
|
||||
|
||||
**Zależności.** Insider jako emitent zdarzeń (jego też nie ma na liście), strona główna po Panoramie, terminy
|
||||
w Sygnie.
|
||||
|
||||
## 6. Odpowiedź do akt sprawy (S–M)
|
||||
|
||||
**Po co.** Notatka dla klienta albo memorandum powstaje w czacie, a musi trafić do akt, z historią wersji.
|
||||
|
||||
**Co już mamy.** `chatDraft` zakłada projekt pisma w Scribe, a `chatGalena` czyta teksty z Galeny. Zapisu
|
||||
odpowiedzi nie ma.
|
||||
|
||||
**Propozycja.**
|
||||
- Pod każdą odpowiedzią trzy akcje: „Zapisz w aktach sprawy” (Galena, wybór sprawy), „Przenieś do Scribe
|
||||
jako projekt”, „Pobierz DOCX”.
|
||||
- Po zapisie w rozmowie zostaje linia „Zapisano: <nazwa> w sprawie <sygnatura>”.
|
||||
- DOCX ma w stopce źródła i adnotację, że projekt powstał z pomocą AI i wymaga weryfikacji.
|
||||
|
||||
**Wygląd.** Rząd `.btn sm ghost` pod `.ha-turn`. Wybór sprawy w `.modal` z wyszukiwaniem.
|
||||
|
||||
**Zależności.** Decyzja o Galenie (#53, sekcja 5; Galena#19), generator DOCX w Scribe.
|
||||
|
||||
## 7. Procedura widoczna w odpowiedzi (S)
|
||||
|
||||
**Po co.** Rozliczalność: prawnik i klient widzą, według jakiej procedury i której jej wersji powstała
|
||||
odpowiedź. Dziś skill i wersję podaje tylko odpowiedź po sprawdzeniu umowy.
|
||||
|
||||
**Propozycja.**
|
||||
- Każda odpowiedź, która użyła skilla, ma krótką linię z nazwą, wersją i stanem (firmowy albo osobisty,
|
||||
zatwierdzony).
|
||||
- W kompozytorze „/” albo przycisk otwiera listę firmowych skilli filtrowaną pisaniem. Wybór wstawia chip
|
||||
skilla nad polem tekstowym.
|
||||
|
||||
**Wygląd.**
|
||||
- Nad odpowiedzią `.ha-sub` w `--text-muted`: „Procedura: Umowa najmu, standard kancelarii, v3 (firmowa,
|
||||
zatwierdzona)”, z linkiem do `#/skills/skill/<id>?v=3`.
|
||||
- Lista skilli jak w *Skille i agenci*, obsługiwana klawiaturą.
|
||||
|
||||
**Zależności.** Plan 3 skilli (#53, sekcja 2).
|
||||
|
||||
## 8. Nowe źródła w Insiderze (L)
|
||||
|
||||
**Propozycja.** Dodawać po kolei, każde dopiero po sprawdzeniu warunków ponownego wykorzystania i
|
||||
robots.txt, jak przy SAOS:
|
||||
1. Rejestr klauzul niedozwolonych UOKiK. To mały zbiór, praktycznie bez nowych wpisów od reformy z 2016 r.,
|
||||
więc import jest jednorazowy. Nowe klauzule pojawiają się już tylko w decyzjach Prezesa UOKiK. Od razu
|
||||
przydaje się „Umowom” przy umowach konsumenckich (art. 385¹ k.c.).
|
||||
2. Orzeczenia NSA i WSA (CBOSA).
|
||||
3. Wyroki KIO.
|
||||
4. Decyzje Prezesa UODO i Prezesa UOKiK.
|
||||
5. Interpretacje indywidualne KIS (Eureka).
|
||||
|
||||
**Wygląd.** Nowe pozycje na liście źródeł z punktu 4 i filtr w Insiderze. Bez nowego ekranu.
|
||||
|
||||
## Kolejność
|
||||
|
||||
1. Po scaleniu Atrium#65: punkty 4 i 7, małe i w czacie.
|
||||
2. Punkt 2 razem z przebudową Parafy na bramkę.
|
||||
3. Punkt 3 w Sygnie, razem z emitowaniem zdarzeń, którego potrzebuje też strona główna.
|
||||
4. Punkt 6 po decyzji o Galenie.
|
||||
5. Punkt 1 jako osobny spec, po module „Umowy” i Planie 3 skilli.
|
||||
6. Punkty 5 i 8 w Insiderze, po sprawdzeniu warunków każdego źródła.
|
||||
@@ -1,197 +0,0 @@
|
||||
# Idea 02: bezpieczeństwo konta, standardy, jakość i koszty
|
||||
|
||||
Stan na 27.11.2026. Status: do dyskusji.
|
||||
|
||||
Sześć propozycji i uzupełnienia do `idea01.md`. Odnoszą się do planu modułów z Atrium#53 i do PR-ów
|
||||
z 27.11 (Atrium#65 i pozostałe).
|
||||
|
||||
| # | Propozycja | Gdzie | Wysiłek | Zależy od |
|
||||
|---|---|---|---|---|
|
||||
| 1 | Weryfikacja dwuetapowa dla konta platformy | dredd-core, Atrium | M | wydanie dredd-core |
|
||||
| 2 | Standardy z firmowej instrukcji negocjacyjnej | Skille i agenci, Arbiter | M | Plan 3 skilli, Workflow |
|
||||
| 3 | Zestaw wzorcowy dla skilli i modeli | Skille i agenci, Dostawcy modeli | M–L | skille (dredd-core 0.25), usługa z repo Arbitra |
|
||||
| 4 | Koszt AI w sprawie i u użytkownika | Atrium, Sygna | M | zapis zużycia w `call_target`, cennik dostawcy |
|
||||
| 5 | Propozycje wpisów czasu pracy | Sygna | M–L | zdarzenia modułów z identyfikatorem sprawy |
|
||||
| 6 | Zapis tylko po kliknięciu (narzędzia agentów) | Skille i agenci, czat | S | narzędzia zapisujące u agentów |
|
||||
|
||||
**Wygląd we wszystkich punktach:** jak w `idea01.md`: „Atrium UI v1” w trybie narzędzia pracy
|
||||
(Operate), tylko dopracowanie istniejącego stylu, istniejące tokeny i klasy, stan nazwany słowem.
|
||||
|
||||
## 1. Weryfikacja dwuetapowa dla konta platformy (M)
|
||||
|
||||
**Po co.**
|
||||
- Jedno konto otwiera wszystkie moduły: sprawy, akta, umowy, podpis. Jedno hasło chroni więc całą
|
||||
tajemnicę zawodową kancelarii.
|
||||
- RODO (art. 32) wymaga środków bezpieczeństwa odpowiednich do ryzyka.
|
||||
- Klienci z sektora finansowego pytają o drugi składnik w ankietach bezpieczeństwa dostawców.
|
||||
|
||||
**Co już mamy.**
|
||||
- dredd-core: hasła w Argon2id i sesje po stronie serwera.
|
||||
- Token aplikacji może wydać tylko sesja z logowania (`require_session_credential`). Drugi składnik
|
||||
przy logowaniu chroni więc także wydawanie tokenów.
|
||||
- Weryfikacji dwuetapowej nie ma w dredd-core na żadnej gałęzi (sprawdzone 27.11).
|
||||
|
||||
**Propozycja.**
|
||||
- Kody jednorazowe z aplikacji uwierzytelniającej (TOTP) i kody zapasowe pokazane raz. Później klucze
|
||||
sprzętowe i passkeys (WebAuthn).
|
||||
- Administrator w *Ogólne* wybiera: „Wymagaj od administratorów” albo „Wymagaj od wszystkich”.
|
||||
- Zresetować drugi składnik może tylko inny administrator. Reset zapisuje się w dzienniku zdarzeń.
|
||||
- Sekret TOTP jest szyfrowany tak jak klucze dostawców modeli (Argon2id i AES-256-GCM).
|
||||
|
||||
**Wygląd.**
|
||||
- *Ustawienia → Bezpieczeństwo konta*: `.card` ze stanem („Włączona od 27.11.2026” albo „Wyłączona”)
|
||||
i przycisk „Włącz”.
|
||||
- `.modal` z kodem QR i jednym polem na sześć cyfr (`inputmode="numeric"`,
|
||||
`autocomplete="one-time-code"`).
|
||||
- Kody zapasowe pokazane raz, tak jak sekret tokenu w *Połączonych aplikacjach*.
|
||||
- Logowanie dostaje drugi krok z tym samym polem.
|
||||
|
||||
**Zależności.** Wydanie dredd-core (sekrety w schemacie tożsamości) i ekran logowania w Atrium. Moduły
|
||||
nic nie zmieniają, bo sesja jest jedna.
|
||||
|
||||
## 2. Standardy z firmowej instrukcji negocjacyjnej (M)
|
||||
|
||||
**Po co.** Kancelarie i klienci korporacyjni mają gotowe zasady negocjacji umów: stanowisko preferowane,
|
||||
dopuszczalne ustępstwo, stanowisko nie do przyjęcia. Ręczne przepisanie takiego dokumentu do skilla
|
||||
zajmuje dni i gubi odniesienie do źródła.
|
||||
|
||||
**Co już mamy.**
|
||||
- Skill jest źródłem procedury i standardów sprawdzania umów (#53, ustalenie 5).
|
||||
- Edytor skilli obsługuje pliki, wersje, próbę i zatwierdzanie.
|
||||
- Standardy przechodzą z Lexiconu do skilli (#53, sekcja 2, Plan 3).
|
||||
|
||||
**Propozycja.**
|
||||
- „Utwórz skill z dokumentu”: prawnik wgrywa DOCX albo PDF, a model proponuje tabelę standardów.
|
||||
- Każdy wiersz ma kwestię, stanowisko preferowane, dopuszczalne ustępstwo, stanowisko nie do przyjęcia,
|
||||
uzasadnienie i osobę do decyzji przy odstępstwie.
|
||||
- Każdy wiersz musi wskazywać akapit dokumentu źródłowego. Wiersz bez źródła nie przechodzi.
|
||||
- Prawnik poprawia tabelę i wysyła skill do zatwierdzenia jak każdy inny.
|
||||
- Przy sprawdzaniu umowy wynik podaje cytat, miejsce w umowie, ocenę i proponowane brzmienie. Analiza
|
||||
pamięta wersję skilla, z którą ruszyła (jak dziś).
|
||||
- Ustawienie skilla mówi, co zrobić z dopuszczalnym ustępstwem: zgłosić albo przyjąć z adnotacją.
|
||||
- Odstępstwo od standardu może uruchomić obieg akceptacji w Workflow, np. zgodę partnera.
|
||||
|
||||
**Wygląd.**
|
||||
- Tabela standardów w edytorze skilla. Kolumny: kwestia, preferowane, dopuszczalne, nie do przyjęcia,
|
||||
źródło.
|
||||
- Link w kolumnie „źródło” otwiera akapit w `.review-panel`.
|
||||
- Wiersz bez źródła ma `.chip` „brak źródła” na `--err-bg`.
|
||||
- Import w `.modal wide` z komunikatem postępu w `aria-live`.
|
||||
|
||||
**Zależności.** Plan 3 skilli, usługa sprawdzania z repo Arbitra, Workflow (zgoda na odstępstwo).
|
||||
|
||||
## 3. Zestaw wzorcowy dla skilli i modeli (M–L)
|
||||
|
||||
**Po co.** Dziś próba skilla sprawdza tylko, czy model i mechanizm działają (#53). Zatwierdzający nie
|
||||
widzi, czy nowa wersja standardów albo zmiana modelu, np. na lokalny, nie pogorszyła wyników. Przy
|
||||
odpowiedzialności zawodowej potrzebny jest dowód, że narzędzie sprawdzono.
|
||||
|
||||
**Co już mamy.**
|
||||
- Wersje skilli, próba i zatwierdzanie.
|
||||
- Plan pomiaru czytnika PDF na 12 plikach z zestawu wzorcowego (#53, sekcja 3).
|
||||
- Weryfikacja cytatów w czacie (`chatClaims`).
|
||||
|
||||
**Propozycja.**
|
||||
- Do skilla dołącza się zestaw wzorcowy: umowy i oczekiwane ustalenia zapisane jako sprawdzalne
|
||||
kryteria, np. „wskazano § 7 ust. 2 jako karę umowną powyżej 10% wynagrodzenia”.
|
||||
- Uruchomienie dla wybranej wersji skilla i modelu daje wynik dla każdego kryterium.
|
||||
- Najpierw kryteria deterministyczne: czy cytat istnieje w pliku i czy jednostka redakcyjna się zgadza
|
||||
(mechanizm jak w `chatClaims`). Ocena modelem jest tylko uzupełnieniem i jest tak opisana.
|
||||
- Wynik widać na ekranie „Do zatwierdzenia”, obok różnic między wersjami.
|
||||
- Zmiana modelu w *Dostawcach modeli* proponuje uruchomienie zestawów dla skilli, które z niego korzystają.
|
||||
|
||||
**Wygląd.**
|
||||
- Zakładka „Zestaw wzorcowy” w skillu. Tabela: kryterium, wynik, dowód.
|
||||
- Wynik to `.chip`: „spełnione”, „niespełnione” albo „do oceny”.
|
||||
- Dwie wersje obok siebie w `.stats`.
|
||||
|
||||
**Zależności.** Skille (dredd-core 0.25), usługa z repo Arbitra, budżet na wywołania modeli.
|
||||
|
||||
## 4. Koszt AI w sprawie i u użytkownika (M)
|
||||
|
||||
**Po co.** Klucze firmowe kosztują. Partner chce wiedzieć, ile AI kosztuje w danej sprawie i czy ten koszt
|
||||
przenieść na klienta; to decyzja kancelarii i umowy z klientem. Przy kluczu osobistym użytkownik widzi
|
||||
swój własny koszt.
|
||||
|
||||
**Co już mamy.** Wywołania modeli idą przez `call_target`, a dziennik zapisuje wpis `model.ask` z
|
||||
`key_source`. Zużycia tokenów i kosztu nikt nie zapisuje.
|
||||
|
||||
**Propozycja.**
|
||||
- Zapisywać zużycie z odpowiedzi dostawcy (tokeny wejścia i wyjścia) i liczyć koszt z cennika ustawionego
|
||||
przy dostawcy.
|
||||
- Przypisywać koszt do użytkownika i modułu, a gdy rozmowa dotyczy sprawy, także do sprawy.
|
||||
- Pokazywać go w *Moich kluczach modeli* (bieżący miesiąc), u administratora (według dostawcy i modułu)
|
||||
i w Sygnie przy sprawie (suma).
|
||||
- Eksport do rozliczeń jako wydatek tylko wtedy, gdy kancelaria tak postanowi.
|
||||
- Lokalny model kosztuje 0 albo tyle, ile ustali administrator.
|
||||
|
||||
**Wygląd.** `.stats` z `.stat` (ten miesiąc, poprzedni) i tabela według modułów. Liczby w `--mono`. Przy
|
||||
odpowiedzi w czacie opcjonalnie koszt w `.ha-sub`.
|
||||
|
||||
**Zależności.** Zapis zużycia w `services/providers.call_target`, nowe pole cennika w `model_provider`,
|
||||
API Sygny dla sumy w sprawie.
|
||||
|
||||
## 5. Propozycje wpisów czasu pracy (M–L)
|
||||
|
||||
**Po co.** Prawnicy nie zapisują części czasu, a odtwarzanie dnia z pamięci jest nieprecyzyjne. Przy
|
||||
rozliczeniu godzinowym to wprost utracony przychód.
|
||||
|
||||
**Co już mamy.** Sygna ma czas pracy (`timelog`), stawki i rozliczenia. Dziennik `module_event` zbiera
|
||||
zdarzenia modułów.
|
||||
|
||||
**Propozycja.**
|
||||
- Sygna proponuje szkice wpisów na podstawie zdarzeń użytkownika powiązanych ze sprawą: akceptacji
|
||||
analizy, rundy negocjacji, projektu pisma, korespondencji.
|
||||
- Czas jest szacowany z odstępów między zdarzeniami i zawsze do poprawienia.
|
||||
- Szkice widzi tylko autor. Nic nie zapisuje się samo: autor przyjmuje, poprawia albo odrzuca.
|
||||
- Funkcję włącza sam użytkownik, bo to dane o jego aktywności (RODO, prawo pracy). Administrator szkiców
|
||||
nie widzi.
|
||||
|
||||
**Wygląd.** W „Czasie pracy” Sygny sekcja „Propozycje (5)”: lista `.stack` z datą, sprawą, opisem i
|
||||
minutami w `--mono` oraz przyciskami „Przyjmij”, „Popraw”, „Odrzuć”.
|
||||
|
||||
**Zależności.** Moduły muszą emitować zdarzenia z identyfikatorem sprawy, a Sygna musi je czytać z
|
||||
`module_event`.
|
||||
|
||||
## 6. Zapis tylko po kliknięciu: zasada dla narzędzi agentów (S)
|
||||
|
||||
**Po co.** Dokument drugiej strony albo e-mail może zawierać ukryte polecenie. Zapis wykonany przez model
|
||||
na podstawie takiej treści działa w imieniu prawnika.
|
||||
|
||||
**Co już mamy.**
|
||||
- Dziś czat wykonuje akcje (sprawdzenie w Arbiterze, projekt pisma w Scribe) tylko na podstawie słów
|
||||
użytkownika, a nie decyzji modelu.
|
||||
- Spec skilli ma test ukrytego polecenia, a listę narzędzi agenta nadaje platforma.
|
||||
|
||||
**Propozycja.**
|
||||
- Gdy agenci dostaną narzędzia zapisujące, każdy zapis zatrzymuje odpowiedź i pokazuje kartę „Asystent
|
||||
chce: <akcja>” z argumentami.
|
||||
- „Wykonaj” uruchamia dokładnie tę akcję, raz. „Odrzuć” mówi modelowi, że akcji nie wykonano.
|
||||
- Administrator ma przełącznik „tylko odczyt” dla wszystkich narzędzi agentów.
|
||||
- Każda decyzja trafia do dziennika zdarzeń.
|
||||
|
||||
**Wygląd.** `.card` w rozmowie z `.btn` „Wykonaj” i `.btn ghost` „Odrzuć”, argumenty w `--mono`.
|
||||
|
||||
**Zależności.** Narzędzia zapisujące u agentów (spec skilli i agentów).
|
||||
|
||||
## Uzupełnienia do idea01
|
||||
|
||||
**Do punktu 1 (przegląd zbiorczy).**
|
||||
- Odróżniać stany komórki. „Nie ma w dokumencie” to wynik. „Do sprawdzenia”, „błąd” i „nieaktualne”
|
||||
wynikiem nie są.
|
||||
- Ponawiać tylko komórki z błędem, bez ruszania dobrych.
|
||||
- Zmiana pliku, pytania, wersji skilla albo modelu oznacza komórki jako nieaktualne.
|
||||
- Komórka pamięta skrót SHA-256 wersji pliku. Cytat z innej wersji to błąd, a nie wynik.
|
||||
- Pytania mają typy (tak/nie, wybór z listy, data, kwota, tekst), które łatwo sprawdzać i filtrować.
|
||||
- Zestawy pytań mają wersje. Przegląd zachowuje kopię pytań, z którymi wystartował.
|
||||
|
||||
**Do punktu 5 (obserwowane przepisy).** Gdy przepis się zmienia, opinie i pisma w Galenie, które go cytują,
|
||||
dostają znacznik „do ponownego sprawdzenia”, z datą stanu prawnego, na którą je napisano. Wysiłek L:
|
||||
potrzebny jest indeks przepisów cytowanych w dokumentach.
|
||||
|
||||
## Kolejność
|
||||
|
||||
1. Punkt 1: bezpieczeństwo i niezależny od #53.
|
||||
2. Punkt 6: zasadę ustalić, zanim agenci dostaną narzędzia zapisujące.
|
||||
3. Punkt 2 razem z Planem 3 skilli, potem punkt 3.
|
||||
4. Punkty 4 i 5 w dowolnej kolejności, po ustaleniu zdarzeń modułów.
|
||||
@@ -1,110 +0,0 @@
|
||||
# Etap 4 planu naprawczego (Atrium#53): kontrahenci i Archiwum umów
|
||||
|
||||
Spec do review. Decyzje właściciela są oznaczone **[D]**. Część A jest zbudowana; część B czeka na kod.
|
||||
|
||||
## Część A. Wspólna kartoteka kontrahentów
|
||||
|
||||
### Stan dzisiaj
|
||||
|
||||
- **dredd-core 0.21.0** (`dredd_core/counterparties.py`) ma kartotekę z trzema tabelami: `counterparty`, `counterparty_alias` i `counterparty_contact`.
|
||||
- Moduły ją czytają, ale nikt jej nie kopiuje.
|
||||
- Powiązanie z kontrahentem to klucz obcy w module.
|
||||
- Tabele zakłada hub (Atrium, rewizja 0012). Dostęp ma trzy poziomy: czytelnik, piszący i migrator.
|
||||
- Rekordy są deduplikowane po NIP, potem po KRS, potem po nazwie. Niejednoznaczne dopasowanie nigdy nie jest zgadywane.
|
||||
- **Sygna** jest dziś jedynym piszącym. Wpisuje tylko **organizacje**, a osoby fizyczne zostają w Sygnie (RODO art. 5 ust. 1 lit. c).
|
||||
- **Galena** trzyma kontrahenta na karcie umowy jako wolny tekst (`document_card.counterparty`). Tekst może wymieniać kilka stron.
|
||||
- **Agora i Parafa** nie trzymają żadnej tożsamości drugiej strony.
|
||||
|
||||
### Decyzje
|
||||
|
||||
- **[D] Piszą Galena i Sygna.** Galena zostaje drugim piszącym i, tak jak Sygna, wpisuje tylko organizacje: po NIP, KRS albo nazwie, przez `link_or_create` z core. Agora i Parafa tylko czytają. Dzięki temu kartoteka działa też tam, gdzie Sygny nie ma.
|
||||
- **[D] Karta ma wiele powiązań i zachowuje tekst.** Karta umowy łączy się z jednym albo wieloma kontrahentami. Pole tekstowe zostaje na to, czego nie da się powiązać.
|
||||
|
||||
### Zmiany
|
||||
|
||||
1. **Atrium (wdrożenie):** `galena_app` trafia do `COUNTERPARTY_WRITER_ROLES`, a `galena_migrator` do `COUNTERPARTY_MIGRATOR_ROLES`. `agora_app` i `parafa_app` trafiają do `COUNTERPARTY_READER_ROLES`, a ich migratorzy do `COUNTERPARTY_MIGRATOR_ROLES`, bo potrzebują REFERENCES. Zmiana obejmuje też `init.sh` z prefiksem ról oraz sprawdzenie `--counterparties` w `push.sh`.
|
||||
2. **Galena:**
|
||||
- Nowa tabela `document_card_counterparty` (karta, kontrahent, kolejność, rola strony) z kluczem obcym do `counterparty` z ON DELETE RESTRICT. Kontrahenci są tylko archiwizowani, nigdy usuwani.
|
||||
- Wersja samodzielna ma lokalne kopie tabel, tak jak Sygna.
|
||||
- Wybór kontrahenta to wyszukiwarka po `search_key`. Gdy nic nie pasuje, użytkownik może utworzyć organizację (NIP, KRS albo nazwa) albo zostawić tekst.
|
||||
- Lista rejestru, eksport i filtry pokazują nazwy z kartoteki, a w razie ich braku tekst.
|
||||
- Jednorazowe powiązanie istniejących kart: `plan_import` łączy tylko jednoznaczne nazwy, resztę zostawia jako tekst i wypisuje raport do ręcznego przejrzenia. Uruchamia się je najpierw na próbę, potem z `--commit`, tak jak import obiegów.
|
||||
3. **Agora:** pokój może wskazać kontrahenta. Zaproszenie gościa pokazuje jego nazwę z kartoteki. Kontakty drugiej strony z `counterparty_contact` nie są pokazywane gościowi.
|
||||
4. **Parafa:** wniosek o podpis może wskazać kontrahenta (stronę umowy), ale tylko do odczytu i do archiwum. Podpisujący nadal są opisani wyłącznie podmiotem certyfikatu.
|
||||
|
||||
### Poza zakresem
|
||||
|
||||
- **Osoby fizyczne we wspólnej kartotece.** Zostają w Sygnie. Jeśli zajdzie potrzeba, decyzja wymaga osobnej podstawy prawnej i retencji.
|
||||
- **Sprawdzanie w GUS, KRS i na białej liście VAT.** Kolumny `vat_*` i `registry_snapshot` są gotowe, ale integracja to osobny pakiet prac.
|
||||
|
||||
## Część B. Archiwum umów w Galenie
|
||||
|
||||
**[D] 27.11 (Tobiasz): Archiwum nie jest osobnym modułem, tylko częścią Galeny.** Galena trzyma już rejestr, karty umów i dokumenty, a Archiwum ma być też zbiorem żywych umów. Dla użytkownika to „Archiwum” albo „Rejestr umów” (link na stronie głównej Atrium); w kodzie zostaje nazwa Galena, modułu nie przemianowujemy.
|
||||
|
||||
### Po co
|
||||
|
||||
Dziś nic nie chroni podpisanej umowy przed usunięciem: Galena usuwa projekt razem z repozytorium git. Nie ma retencji ani blokady prawnej, a dowody jednej umowy są rozproszone po czterech modułach.
|
||||
|
||||
### Paczka archiwalna
|
||||
|
||||
Jedna paczka na jedną kartę umowy, z **kopiami**, nie odnośnikami:
|
||||
|
||||
| Składnik | Źródło |
|
||||
|---|---|
|
||||
| Podpisany PDF, sha256, raport weryfikacji podpisów | Parafa (`signed_*`) albo skan z Workflow (`paper_scan`) |
|
||||
| Migawka karty: pola, kontrahenci, numer, commit dokumentu | Galena, lokalnie |
|
||||
| Oś czasu obiegu, szablon, etapy | Workflow |
|
||||
| Rundy negocjacji z sha256 | Agora |
|
||||
| Zaakceptowana analiza: identyfikator, odcisk karty, raport | Arbiter |
|
||||
|
||||
- **Manifest:** pliki z sha256, źródło każdego (moduł, identyfikator, commit), czas i autor. Hash manifestu to odcisk paczki.
|
||||
- **Braki** („obiegu nie było”) trafiają do manifestu i nie blokują archiwizacji.
|
||||
- **Poprawka** (aneks, dosłany raport) to nowa wersja paczki; poprzednia zostaje.
|
||||
|
||||
### Kiedy
|
||||
|
||||
- **Automatycznie po podpisie:** Galena odbiera już `document.signed` i `workflow.signed_on_paper`. Przy zdarzeniu nie ma tokenu osoby, więc składniki z Parafy, Workflow, Agory i Arbitra Galena zbiera **kontem technicznym tylko do odczytu** (zakłada je hub; token w sekretach wdrożenia Galeny; każde użycie w audycie modułu, który je obsłużył). Gdy zebranie się nie uda, karta trafia na listę „Do zarchiwizowania” do ponowienia.
|
||||
- **Ręcznie:** moderator Galeny archiwizuje dowolną kartę, także starą papierową (skan + metadane). Składniki zbierane są tokenem tej osoby.
|
||||
|
||||
### Niezmienność — zapewnia baza
|
||||
|
||||
- Tabele paczek, plików paczek i protokołów likwidacji są w `APPEND_ONLY_TABLES` Galeny: rola runtime nie ma na nich UPDATE ani DELETE. Pliki paczek leżą osobno od repozytoriów git dokumentów.
|
||||
- Jedyna ścieżka usunięcia plików to likwidacja (niżej). Wiersze paczek zostają na zawsze.
|
||||
- **Galena nie usunie projektu, którego karta ma paczkę:** 409 `archived_contract`.
|
||||
|
||||
### Retencja i likwidacja
|
||||
|
||||
- **Termin retencji liczy się z żywej karty umowy, nie z migawki w paczce:** koniec obowiązywania z karty + okres przedawnienia + okres retencji, oba ustawiane przez moderatora dla typu umowy. Aneks zmieniający datę końca sam przesuwa termin. Bez daty końca karta nie trafia na listę „Po terminie retencji”.
|
||||
- Domyślnych okresów nie ma: dopóki moderator ich nie ustawi, nic nie jest po terminie.
|
||||
- Lista „Po terminie retencji” jest liczona przy odczycie. Nic nie jest likwidowane automatycznie.
|
||||
- **Likwidacja za zgodą dwóch różnych moderatorów.** Pliki paczki znikają; protokół (co, kiedy, kto, podstawa, odcisk paczki) zostaje na zawsze.
|
||||
- **Blokada prawna** na karcie albo kontrahencie wstrzymuje likwidację; zakładana i zdejmowana z uzasadnieniem, w audycie.
|
||||
|
||||
### Dostęp
|
||||
|
||||
- Paczkę czyta ten, kto może czytać kartę w Galenie, i moderatorzy Galeny. Brak dostępu to 404.
|
||||
- Otwarcie i eksport paczki trafiają do audytu (`archive.viewed`, `archive.exported`).
|
||||
|
||||
### Eksport
|
||||
|
||||
ZIP z plikami paczki, `manifest.json` i `manifest.json.p7s` (manifest podpisany pieczęcią operatora przez Parafę, nowy endpoint CMS/CAdES dla małego pliku). Odbiorca sprawdza go `sha256sum` i dowolnym weryfikatorem CMS.
|
||||
|
||||
### Poza zakresem
|
||||
|
||||
- Pełnotekstowe szukanie w treści umów.
|
||||
- Kwalifikowany znacznik czasu i PDF/A.
|
||||
|
||||
## Kolejność PR-ów
|
||||
|
||||
Kroki 1–3 (kontrahenci) są zrobione. Archiwum:
|
||||
|
||||
4. **Atrium:** konto techniczne Galeny tylko do odczytu w Parafie, Workflow, Agorze i Arbitrze, jego token w hubie.
|
||||
5. **Parafa:** pieczęć manifestu (CMS).
|
||||
6. **Galena:** paczki, retencja, blokady, likwidacja, eksport, odmowa usunięcia; ekrany „Do zarchiwizowania”, „Po terminie retencji”, „Blokady”, „Likwidacje”.
|
||||
|
||||
Odpadają: repo `Alpaq92/Archive`, osobny moduł we wdrożeniu, zdarzenia `archive.*` w dredd-core.
|
||||
|
||||
## Decyzje
|
||||
|
||||
- 26.11: archiwizacja po podpisie kontem technicznym tylko do odczytu; retencja od wygaśnięcia roszczeń.
|
||||
- 27.11: Archiwum jest częścią Galeny; termin retencji z żywej karty; niezmienność paczek zapewnia baza.
|
||||
@@ -467,22 +467,3 @@ a.modchip:hover { text-decoration: none; background: var(--at-surface-hover); }
|
||||
/* The sidebar's "Dostosuj listę": a quiet last entry of the Aplikacje section. */
|
||||
.nav-item.nav-tune { width: 100%; border: 0; background: none; font: inherit; cursor: pointer; text-align: left; color: var(--at-text-muted); }
|
||||
.nav-item.nav-tune:hover { color: var(--at-text); }
|
||||
|
||||
/* The contract review panel beside the chat (chatReview / reviewOpen in app.js). Off-canvas on the
|
||||
right; `transform` transitions, `visibility` flips at once (a delayed `visibility` sticks when
|
||||
frames are throttled). Full width on a phone. */
|
||||
.review-panel {
|
||||
position: fixed; top: 0; right: 0; bottom: 0; z-index: 40; width: min(560px, 100vw);
|
||||
display: flex; flex-direction: column; background: var(--at-surface);
|
||||
border-left: 1px solid var(--at-border); box-shadow: -8px 0 24px rgba(0, 0, 0, .08);
|
||||
transform: translateX(100%); visibility: hidden; transition: transform .2s ease;
|
||||
}
|
||||
.review-panel.open { transform: none; visibility: visible; }
|
||||
.review-panel .rp-head {
|
||||
display: flex; align-items: flex-start; justify-content: space-between; gap: 12px;
|
||||
padding: 14px 16px; border-bottom: 1px solid var(--at-border);
|
||||
}
|
||||
.review-panel .rp-body { flex: 1; display: flex; flex-direction: column; gap: 12px; padding: 12px 16px; min-height: 0; overflow: auto; }
|
||||
.review-panel .rp-report { flex: 1; min-height: 320px; width: 100%; border: 1px solid var(--at-border); border-radius: 8px; background: #fff; }
|
||||
.review-panel .rp-accept { display: flex; flex-direction: column; gap: 8px; }
|
||||
.ha-turn .ha-report { margin-top: 8px; }
|
||||
|
||||
+54
-452
@@ -323,32 +323,6 @@ const I18N = {
|
||||
'Anuluj': 'Cancel',
|
||||
'Usuń': 'Delete',
|
||||
'Zamknij': 'Close',
|
||||
'Rejestr umów': 'Contract register',
|
||||
'Dokumenty': 'Documents',
|
||||
'Raport analizy': 'Analysis report',
|
||||
'Pokaż raport': 'Show the report',
|
||||
'Analiza trwa': 'The analysis is running',
|
||||
'Analiza trwa dłużej niż zwykle. Panel przestał czekać; otwórz go później z tej odpowiedzi w czacie.': 'The analysis is taking longer than usual. The panel stopped waiting; open it later from this answer in the chat.',
|
||||
'Analiza skończyła się bez raportu': 'The analysis ended without a report',
|
||||
'Analiza zaakceptowana': 'Analysis accepted',
|
||||
'Notatka (nie da się jej później zmienić ani usunąć; nie wpisuj numerów PESEL, dowodu ani paszportu)': 'Note (it cannot be changed or deleted later; do not enter PESEL, identity card or passport numbers)',
|
||||
'Akceptacja jest jednorazowa i nie da się jej cofnąć ani poprawić.': 'An acceptance is given once and cannot be withdrawn or corrected.',
|
||||
'Akceptuj analizę': 'Accept the analysis',
|
||||
'Zdarzenia modułów': 'Module events',
|
||||
'umowy, obiegi, podpisy i negocjacje, ostatnie 30 dni': 'contracts, approvals, signatures and negotiations, last 30 days',
|
||||
'Zdarzenia według rodzaju': 'Events by kind',
|
||||
'ostatnie 30 dni': 'last 30 days',
|
||||
'Czas obsługi dokumentu': 'Document turnaround',
|
||||
'dni': 'days',
|
||||
'dni (mediana)': 'days (median)',
|
||||
'Zmierzono dokumentów': 'Documents measured',
|
||||
'od pierwszej wersji do zatwierdzenia': 'from the first version to approval',
|
||||
'od zatwierdzenia do podpisu': 'from approval to signature',
|
||||
'Nowe wersje dokumentów': 'New document versions',
|
||||
'Zatwierdzone obiegi': 'Approved workflows',
|
||||
'Podpisane dokumenty': 'Signed documents',
|
||||
'Rundy negocjacji': 'Negotiation rounds',
|
||||
'Zaakceptowane analizy': 'Accepted analyses',
|
||||
'Zapisano.': 'Saved.',
|
||||
'Tej operacji nie da się cofnąć.': 'This cannot be undone.',
|
||||
'Moduły': 'Modules',
|
||||
@@ -407,7 +381,6 @@ const I18N = {
|
||||
'Do podpisu prawnika': 'Awaiting lawyer sign-off',
|
||||
'Wygasa w 60 dni': 'Expiring within 60 days',
|
||||
'Obowiązujące umowy': 'Contracts in force',
|
||||
'Umowy': 'Contracts',
|
||||
'Do zrobienia': 'To do',
|
||||
// The modules' own tiles (dredd-core's stats contract): the label comes in the module's language and
|
||||
// the contract has no second one, so the module's words are translated here, on Home's shelf.
|
||||
@@ -881,9 +854,6 @@ const I18N = {
|
||||
'Ta sama karta': 'Same tab',
|
||||
'Wnioski o dostęp dozwolone': 'Allow access requests',
|
||||
'Domyślna dostępność nowego modułu': 'Default availability for a new module',
|
||||
'Pokazuj w menu i katalogu': 'Show in the menu and catalogue',
|
||||
'Odznaczony moduł działa jako usługa: dostęp, odnośniki i kafle zostają, znika tylko pozycja w menu.': 'Unticked, the module runs as a service: access, links and tiles stay; only its menu entry goes.',
|
||||
'Usługa': 'Service',
|
||||
'Pokazywana w pasku bocznym i tytule strony.': 'Shown in the sidebar and the page title.',
|
||||
'Zwykły tekst nad listą aplikacji.': 'Plain text above the list of apps.',
|
||||
'Pokazywany w katalogu jako tekst, nie link.': 'Shown in the marketplace as text, never a link.',
|
||||
@@ -1276,7 +1246,7 @@ function renderNav() {
|
||||
+ (frame.slug === m.slug && !modCol ? '<div class="modnav" id="modNav" data-no-i18n></div>' : '');
|
||||
$('nav').innerHTML = NAV.map((n) => navItem(n, cur)).join('')
|
||||
+ (mods.length || state.launcher.some(embeddable)
|
||||
? navGroup('apps', 'Aplikacje', contractsNavItem(cur) + mods.map(modItem).join('')
|
||||
? navGroup('apps', 'Aplikacje', mods.map(modItem).join('')
|
||||
+ `<button type="button" class="nav-item nav-tune" onclick="openNavPrefs()">${svg(ICN.settings)}<span>Dostosuj listę</span></button>`, !!frame.slug)
|
||||
: '');
|
||||
$('navFoot').innerHTML = SECTIONS.filter((s) => !s.admin || isAdmin()).map((s) =>
|
||||
@@ -1351,7 +1321,6 @@ async function router() {
|
||||
else if (!seg.length) await refreshLauncher(); // Home is the launcher: always show it current
|
||||
try {
|
||||
if (!seg.length) await viewHome(C);
|
||||
else if (seg[0] === 'umowy') await viewHome(C); // „Umowy” is the chat (CONTRACTS)
|
||||
else if (seg[0] === 'marketplace' && seg[1]) await viewModule(C, seg[1]);
|
||||
else if (seg[0] === 'marketplace') await viewMarketplace(C, q);
|
||||
else if (seg[0] === 'requests') await viewMyRequests(C);
|
||||
@@ -1667,13 +1636,6 @@ function chatRender(toEnd) {
|
||||
else el.textContent = shown.content;
|
||||
if (shown !== t) el.appendChild(chatTableEl(t.table));
|
||||
if (t.review && !t.status) renderReview(el, t.review);
|
||||
if (t.analysis && !t.status) { // an order in Arbiter (chatReview): its report reopens in the panel
|
||||
const b = document.createElement('button');
|
||||
b.className = 'btn ha-report';
|
||||
b.textContent = _tr('Pokaż raport');
|
||||
b.onclick = () => reviewOpen(t.analysis);
|
||||
el.appendChild(b);
|
||||
}
|
||||
if (t.trace && t.trace.length && !t.status) { // what the model actually looked at, in order
|
||||
const det = document.createElement('details');
|
||||
det.className = 'ha-trace faint tiny';
|
||||
@@ -1756,7 +1718,6 @@ function chatReset() {
|
||||
chat.busy = null; // or the send button stays a stop button for an answer that is gone
|
||||
chat.turns = [];
|
||||
chat.index = null; // the next question reads the modules again
|
||||
chat.clauseDocs = new Map();
|
||||
chatSave();
|
||||
chatRender();
|
||||
}
|
||||
@@ -1833,220 +1794,6 @@ async function arbiter(method, path, body) {
|
||||
return data;
|
||||
}
|
||||
|
||||
/* ── Contract review from the chat ──────────────────────────────────
|
||||
"Sprawdź umowę UM-2026-0017" is an ACTION, routed by code like every other turn (no model tools,
|
||||
see above): code picks the contract (named in the question, or the one the last answer was about),
|
||||
its document file in Galena and the skill to check it by, and orders an `agent` analysis in Arbiter
|
||||
with the asker's own session. The report then opens in a panel beside the chat, framed sandboxed
|
||||
(Arbiter has no console: this panel is the only screen for it), and the lawyer accepts the analysis there
|
||||
(`POST /analyses/{id}/acceptance`: Arbiter says `analysis.accepted`, Galena's card keeps it).
|
||||
Whatever is missing - no Arbiter, no skill, several files or skills - is asked back, never guessed. */
|
||||
// The verb takes the contract as its object ("Sprawdź umowę UM-…", "przeanalizuj tę umowę"). "Sprawdź, kiedy
|
||||
// kończy się umowa UM-…" asks about the contract and stays a data question: it never orders an analysis.
|
||||
const CHAT_REVIEW = /(?:^|[^\p{L}])(?:sprawdź|sprawdz|przeanalizuj|zweryfikuj|przejrzyj|zbadaj|review|check|analy[sz]e)\s+(?:(?:tę|tą|ta|tej|naszą|moją|this|the|our)\s+)?(?:umow|kontrakt|contract|agreement|UM-\d)/iu;
|
||||
const CHAT_REVIEW_POLL_MS = 3000;
|
||||
// The wait doubles up to 30 s, and the panel stops asking after 20 minutes (an agent run that long is
|
||||
// reopened from its chat answer, not followed by a panel left open).
|
||||
const CHAT_REVIEW_POLL_MAX_MS = 30000;
|
||||
const CHAT_REVIEW_GIVE_UP_MS = 20 * 60 * 1000;
|
||||
// A Galena project's document file: not a signed scan (`podpisane/`), not a hidden path (Galena's `workflow_export.main_file`).
|
||||
const reviewFiles = (tree) => (Array.isArray(tree) ? tree : (tree && tree.entries) || [])
|
||||
.filter((n) => ['file', 'blob'].includes(n.type || n.kind) && n.path
|
||||
&& !n.path.split('/').some((p) => p.startsWith('.')) && !n.path.startsWith('podpisane/'));
|
||||
const reviewWords = (s) => (String(s).toLowerCase().match(/[\p{L}\d]{4,}/gu) || []);
|
||||
|
||||
/* The one contract this turn is about: named in the question, else the only one the last answer named. */
|
||||
function reviewContract(named, prev, index) {
|
||||
const own = named.filter((r) => r && r.contract);
|
||||
if (own.length) return own.length === 1 ? { contract: own[0].contract } : { several: own.map((r) => r.contract) };
|
||||
const back = ((prev && prev.mentioned) || []).map((k) => index.byKey.get(k)).filter((r) => r && r.contract);
|
||||
return back.length === 1 ? { contract: back[0].contract } : back.length ? { several: back.map((r) => r.contract) } : {};
|
||||
}
|
||||
|
||||
/* The skill to judge by: a FIRM skill (its current version is the approved one; a personal skill's follows
|
||||
its newest, unapproved version), the only one, or the one whose name the question uses. */
|
||||
function reviewSkill(skills, question) {
|
||||
const live = skills.filter((s) => s.scope === 'firm' && s.status !== 'archived' && s.current_version_id);
|
||||
if (live.length <= 1) return { skill: live[0] || null, all: live };
|
||||
const words = new Set(reviewWords(question));
|
||||
const hit = live.filter((s) => reviewWords(s.name).some((w) => words.has(w)));
|
||||
return hit.length === 1 ? { skill: hit[0], all: live } : { skill: null, all: live };
|
||||
}
|
||||
|
||||
/* The turn: [answer text, extra fields of the answer]. Every refusal is a sentence, never a throw. */
|
||||
async function chatReview({ question, named, prev, index, en }) {
|
||||
const say = (pl, eng, extra = {}) => [en ? eng : pl, { coded: 'review', ...extra }];
|
||||
// Access is Arbiter's answer, not the catalogue's: a service module (Arbiter is one on the
|
||||
// platform) is left out of `/marketplace` for everyone but administrators.
|
||||
const noAccess = () => say('Sprawdzanie umów jest w module Arbiter, a nie masz do niego dostępu.',
|
||||
'Contract review lives in the Arbiter module, and you have no access to it.');
|
||||
const pick = reviewContract(named, prev, index);
|
||||
if (pick.several) {
|
||||
return say(`Którą umowę mam sprawdzić: ${pick.several.slice(0, 6).map((c) => c.number + ' ' + c.name).join('; ')}? Podaj jej numer.`,
|
||||
`Which contract should I check: ${pick.several.slice(0, 6).map((c) => c.number + ' ' + c.name).join('; ')}? Give its number.`,
|
||||
{ coded: 'ask', mentioned: pick.several.map((c) => 'galena:umowa:' + c.id) });
|
||||
}
|
||||
if (!pick.contract) {
|
||||
return say('Którą umowę mam sprawdzić? Podaj jej numer z rejestru, np. UM-2026-0017.',
|
||||
'Which contract should I check? Give its register number, e.g. UM-2026-0017.', { coded: 'ask' });
|
||||
}
|
||||
const c = pick.contract;
|
||||
const files = reviewFiles(await askerGet('galena', `projects/${c.project_id}/tree?recursive=true`));
|
||||
if (files.length !== 1) {
|
||||
return say(files.length
|
||||
? `Umowa ${c.number} ma w Galenie ${files.length} plików (${files.slice(0, 5).map((f) => f.path).join(', ')}). Sprawdzam tylko umowę z jednym plikiem; zostaw w projekcie jeden plik umowy.`
|
||||
: `Umowa ${c.number} nie ma w Galenie pliku, który dałoby się sprawdzić.`,
|
||||
files.length
|
||||
? `Contract ${c.number} has ${files.length} files in Galena (${files.slice(0, 5).map((f) => f.path).join(', ')}). I only check a contract with one file; keep one contract file in the project.`
|
||||
: `Contract ${c.number} has no file in Galena that could be checked.`, { mentioned: ['galena:umowa:' + c.id] });
|
||||
}
|
||||
const { skill, all } = reviewSkill(await api('GET', '/skills'), question);
|
||||
if (!skill) {
|
||||
return all.length
|
||||
? say(`Według którego skilla sprawdzić umowę ${c.number}: ${all.map((s) => s.name).join('; ')}? Napisz jego nazwę w pytaniu.`,
|
||||
`Which skill should check contract ${c.number}: ${all.map((s) => s.name).join('; ')}? Name it in the question.`, { coded: 'ask' })
|
||||
: say('Nie ma jeszcze opublikowanego skilla do sprawdzania umów. Dodaj go w Skillach.',
|
||||
'There is no published skill for checking contracts yet. Add one under Skills.');
|
||||
}
|
||||
const n = ((await api('GET', '/skills/' + encodeURIComponent(skill.id))).versions || [])
|
||||
.find((v) => v.id === skill.current_version_id);
|
||||
if (!n) return say('Nie mogę odczytać aktualnej wersji skilla ' + skill.name + '.', 'I cannot read the current version of skill ' + skill.name + '.');
|
||||
try {
|
||||
const subject = await arbiter('POST', 'subjects/document', { document_id: c.project_id, path: files[0].path, title: (c.number + ' ' + c.name).slice(0, 200) });
|
||||
const run = await arbiter('POST', 'analyses', { subject_id: subject.id, mode: 'agent', skill_id: skill.id, skill_n: n.n });
|
||||
const analysis = { id: run.id, number: c.number, name: c.name, skill: skill.name, n: n.n };
|
||||
reviewOpen(analysis);
|
||||
return say(`Zleciłem sprawdzenie umowy ${c.number} (${files[0].path}) skillem ${skill.name} w wersji ${n.n}. Raport otworzy się w panelu obok, gdy analiza się skończy; tam możesz ją zaakceptować.`,
|
||||
`I ordered a check of contract ${c.number} (${files[0].path}) by skill ${skill.name}, version ${n.n}. The report opens in the panel beside the chat once the analysis is done; you can accept it there.`,
|
||||
{ analysis, mentioned: ['galena:umowa:' + c.id] });
|
||||
} catch (ex) {
|
||||
if ([401, 403].includes(ex.status)) return noAccess(); // refused at the module's door
|
||||
return say(`Arbiter nie przyjął zlecenia: ${ex.message}`, `Arbiter refused the order: ${ex.message}`, { failed: true });
|
||||
}
|
||||
}
|
||||
|
||||
/* What a named contract SAYS: the card holds fields, not the text, so a question
|
||||
about content ("jaka kara umowna w UM-2026-0017", "co mówi § 5") reads the contract's one document file from
|
||||
Galena now, as the asker (`GET projects/{id}/text`, nothing stored), and code picks the paragraphs that share
|
||||
the question's words. They go to the model as sources like any record, so the answer cites them. Only for a
|
||||
question about content, only for the first named contract with exactly one document file. */
|
||||
const CHAT_CLAUSE = /klauzul|zapis|postanowie|paragraf|§|treść|tekst|brzmi|mówi|stanowi|przewiduj|kar[aąy]|odsetk|wypowiedz|odstąpi|termin|poufno|odpowiedzialno|gwarancj|rękojm|zabezpiecz|clause|provision|says|penalt|terminat|liabil/iu;
|
||||
const CHAT_CLAUSE_TOP = 4;
|
||||
// Question words that say nothing about which paragraph is meant (chatStems keeps 5-letter stems).
|
||||
const CHAT_CLAUSE_STOP = ['jest', 'jaka', 'jaki', 'jakie', 'jakim', 'jakic', 'czy', 'kiedy', 'gdzie', 'który', 'która',
|
||||
'które', 'mówi', 'umowa', 'umowy', 'umowi', 'umowę', 'umową', 'what', 'which', 'does', 'the', 'contr'];
|
||||
async function chatClauses(question, named) {
|
||||
const rec = named.find((r) => r && r.contract);
|
||||
if (!rec || !CHAT_CLAUSE.test(question)) return [];
|
||||
const c = rec.contract;
|
||||
try {
|
||||
// Read once per conversation: a follow-up about the same contract reuses its text.
|
||||
if (!chat.clauseDocs) chat.clauseDocs = new Map();
|
||||
let got = chat.clauseDocs.get(c.project_id);
|
||||
if (got === undefined) {
|
||||
const files = reviewFiles(await askerGet('galena', `projects/${c.project_id}/tree?recursive=true`));
|
||||
got = null;
|
||||
if (files.length === 1) {
|
||||
const doc = await askerGet('galena', `projects/${c.project_id}/text?path=${encodeURIComponent(files[0].path)}`);
|
||||
got = { path: files[0].path, paras: (doc && doc.paragraphs) || [] };
|
||||
}
|
||||
chat.clauseDocs.set(c.project_id, got);
|
||||
}
|
||||
if (!got) return [];
|
||||
const paras = got.paras;
|
||||
const words = chatStems(question.replace(new RegExp(c.number.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), ''));
|
||||
for (const w of CHAT_CLAUSE_STOP) words.delete(w); // "jest", "jaka": every paragraph has them
|
||||
const scored = paras.map((p, i) => ({ p, i, s: [...chatStems(p)].filter((w) => words.has(w)).length }))
|
||||
.filter((x) => x.s > 0).sort((a, b) => b.s - a.s || a.i - b.i).slice(0, CHAT_CLAUSE_TOP)
|
||||
.sort((a, b) => a.i - b.i);
|
||||
return scored.map(({ p, i }) => ({ slug: 'galena', kind: 'zapis', key: `galena:zapis:${c.id}:${i}`,
|
||||
title: `${c.number}: ${p.slice(0, 80)}`, inner: 'card/' + c.project_id, labels: [c.number],
|
||||
text: `Fragment umowy ${c.number} „${c.name}” (plik ${got.path}, akapit ${i + 1}): ${p.slice(0, 2000)}` }));
|
||||
} catch (ex) {
|
||||
if (ex.name === 'AbortError') throw ex;
|
||||
return []; // no text (a scan, another format, no access): the card's fields still answer what they can
|
||||
}
|
||||
}
|
||||
|
||||
/* The panel beside the chat: the run's state while it runs, then its report framed with no rights
|
||||
(`sandbox=""`, Arbiter's own CSP on the response too) and the acceptance under it. One panel, one
|
||||
run at a time; a later order replaces it. Polls only while the panel is open. */
|
||||
const reviewPanel = { analysis: null, timer: null };
|
||||
function reviewOpen(analysis) {
|
||||
reviewPanel.analysis = { ...analysis, since: Date.now(), polls: 0 };
|
||||
let el = $('reviewPanel');
|
||||
if (!el) {
|
||||
el = document.createElement('aside');
|
||||
el.id = 'reviewPanel';
|
||||
el.className = 'review-panel';
|
||||
el.setAttribute('aria-label', _tr('Raport analizy'));
|
||||
document.body.appendChild(el);
|
||||
}
|
||||
el.classList.add('open');
|
||||
reviewPoll();
|
||||
}
|
||||
function reviewClose() {
|
||||
clearTimeout(reviewPanel.timer);
|
||||
reviewPanel.analysis = null;
|
||||
const el = $('reviewPanel');
|
||||
if (el) el.classList.remove('open');
|
||||
}
|
||||
const REVIEW_DONE = ['done', 'partial'];
|
||||
const REVIEW_OVER = ['done', 'partial', 'failed', 'unreadable', 'interrupted', 'cancelled'];
|
||||
async function reviewPoll() {
|
||||
clearTimeout(reviewPanel.timer);
|
||||
const a = reviewPanel.analysis;
|
||||
const el = $('reviewPanel');
|
||||
if (!a || !el) return;
|
||||
let run;
|
||||
try { run = await arbiter('GET', 'analyses/' + encodeURIComponent(a.id)); } catch (ex) { run = { status: 'error', error: ex.message }; }
|
||||
if (reviewPanel.analysis !== a) return; // closed, or replaced by a later order, while this ran
|
||||
const wait = Math.min(CHAT_REVIEW_POLL_MAX_MS, CHAT_REVIEW_POLL_MS * 2 ** a.polls++);
|
||||
const tooLong = Date.now() - a.since > CHAT_REVIEW_GIVE_UP_MS;
|
||||
const head = `<div class="rp-head"><div><strong data-no-i18n>${esc(a.number)}</strong> <span data-no-i18n>${esc(a.name)}</span>
|
||||
<div class="faint tiny"><span>Skill</span> <span data-no-i18n>${esc(a.skill)} v${esc(String(a.n))}</span></div></div>
|
||||
<button class="btn icon" onclick="reviewClose()" aria-label="${esc(_tr('Zamknij'))}">${svg(ICN.x, 16)}</button></div>`;
|
||||
let body;
|
||||
if (tooLong && (run.status === 'error' || !REVIEW_OVER.includes(run.status))) {
|
||||
body = '<div class="banner warn"><span>Analiza trwa dłużej niż zwykle. Panel przestał czekać; otwórz go później z tej odpowiedzi w czacie.</span></div>';
|
||||
} else if (run.status === 'error') { // a network blip: say so and try again
|
||||
body = `<div class="banner warn" data-no-i18n>${esc(run.error)}</div>`;
|
||||
reviewPanel.timer = setTimeout(reviewPoll, wait);
|
||||
} else if (!REVIEW_OVER.includes(run.status)) {
|
||||
body = `<div class="faint"><span>Analiza trwa</span> (<span data-no-i18n>${esc(run.status)}</span>)…</div>`;
|
||||
reviewPanel.timer = setTimeout(reviewPoll, wait);
|
||||
} else if (!REVIEW_DONE.includes(run.status)) {
|
||||
body = `<div class="banner warn"><span>Analiza skończyła się bez raportu</span>: <span data-no-i18n>${esc(run.status)}</span></div>`;
|
||||
} else {
|
||||
const accepted = run.signoff;
|
||||
body = `<iframe class="rp-report" sandbox="" referrerpolicy="no-referrer" title="Raport"
|
||||
src="${esc(new URL('../arbiter/api/v1/analyses/' + encodeURIComponent(a.id) + '/report', document.baseURI).href)}"></iframe>
|
||||
<div class="rp-accept">${accepted
|
||||
? `<div class="banner ok"><span>Analiza zaakceptowana</span> <span data-no-i18n>${esc(String(accepted.created_at || '').slice(0, 10))}</span></div>`
|
||||
: `<label class="field"><span>Notatka (nie da się jej później zmienić ani usunąć; nie wpisuj numerów PESEL, dowodu ani paszportu)</span>
|
||||
<textarea id="rpNote" rows="2" maxlength="4000"></textarea></label>
|
||||
<div class="faint tiny">Akceptacja jest jednorazowa i nie da się jej cofnąć ani poprawić.</div>
|
||||
<div id="rpErr" class="banner warn hidden" data-no-i18n></div>
|
||||
<button class="btn primary" onclick="reviewAccept()">${svg(ICN.check, 16)}<span>Akceptuj analizę</span></button>`}</div>`;
|
||||
}
|
||||
el.innerHTML = head + `<div class="rp-body">${body}</div>`;
|
||||
localize(el);
|
||||
}
|
||||
async function reviewAccept() {
|
||||
const a = reviewPanel.analysis;
|
||||
if (!a) return;
|
||||
const note = ($('rpNote') && $('rpNote').value.trim()) || null;
|
||||
try {
|
||||
await arbiter('POST', 'analyses/' + encodeURIComponent(a.id) + '/acceptance', { note });
|
||||
toast(_tr('Analiza zaakceptowana'));
|
||||
if (reviewPanel.analysis === a) reviewPoll();
|
||||
} catch (ex) {
|
||||
if (reviewPanel.analysis !== a) return; // the panel shows another run now
|
||||
const err = $('rpErr');
|
||||
if (err) { err.textContent = ex.message; err.classList.remove('hidden'); }
|
||||
}
|
||||
}
|
||||
|
||||
/* An Atrium GET answered as text, not JSON: a skill file's bytes as the editor reads them. */
|
||||
async function apiText(path) {
|
||||
const res = await fetch(API + path, { credentials: 'same-origin' });
|
||||
@@ -2310,99 +2057,6 @@ async function chatGalena(names) {
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
/* Scribe and Lexicon have no console any more (Atrium#53): the chat is where their templates, drafts, sources and
|
||||
library are read, with the asker's own session like every other module. Templates are read by every user of
|
||||
Scribe; drafts are the asker's own (a moderator's: all); Lexicon answers only the sources this account may read. */
|
||||
async function chatScribe(names) {
|
||||
const templates = await askerGet('scribe', 'templates');
|
||||
if (templates === null) return null;
|
||||
const tpl = Object.fromEntries(templates.map((t) => [t.id, t.name]));
|
||||
const out = templates.map((t) => ({ slug: 'scribe', kind: 'szablon', title: `Szablon dokumentu ${t.name}`, inner: null,
|
||||
key: 'scribe:szablon:' + t.id, labels: [t.name], template: t,
|
||||
text: `Szablon dokumentu „${t.name}” w Scribe: ${t.description || 'bez opisu'}. Pól do wypełnienia ${t.field_count}, miejsc na klauzule ${t.slot_count}.` }));
|
||||
for (const d of (await askerGet('scribe', 'drafts')) || []) {
|
||||
out.push({ slug: 'scribe', kind: 'szkic', title: `Projekt pisma ${d.title || 'bez tytułu'}`, inner: null, key: 'scribe:szkic:' + d.id,
|
||||
labels: d.title ? [d.title] : [], at: d.created_at, did: 'utworzony', draft: d,
|
||||
text: `Projekt pisma (szkic w Scribe) „${d.title || 'bez tytułu'}”, ${d.from_scratch ? 'pisany od zera, bez szablonu' : `z szablonu ${d.template_name || tpl[d.template_id] || 'usuniętego'}`}, ` +
|
||||
`status ${d.status}, ${chatWho(names, d.owner_id, 'autor', 'autor nie wpisany')}, utworzony ${(d.created_at || '').slice(0, 10)}.`,
|
||||
...(d.template_id ? { members: ['scribe:szablon:' + d.template_id] } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function chatLexicon() {
|
||||
const sources = await askerGet('lexicon', 'sources?status=active');
|
||||
if (sources === null) return null;
|
||||
const out = sources.map((s) => ({ slug: 'lexicon', kind: 'źródło', title: `Wzorzec w bibliotece klauzul: ${s.title}`, inner: null,
|
||||
key: 'lexicon:zrodlo:' + s.id, labels: [s.title], source: s,
|
||||
text: `Wzorzec (źródło) „${s.title}” w bibliotece klauzul Lexicon, ${s.kind === 'document' ? 'dokument z Galeny' : 'plik ' + (s.name || '')}, ` +
|
||||
`${s.shared ? 'udostępniony wszystkim' : 'prywatny'}, klauzul w bibliotece ${(s.library && s.library.count) || 0}. ${s.note || ''}` }));
|
||||
const shelves = ((await askerGet('lexicon', 'library/shelves')) || []).filter((x) => x.count);
|
||||
if (shelves.length) out.push({ slug: 'lexicon', kind: 'zestawienie', title: 'Biblioteka klauzul Lexicon: typy klauzul i ich liczba', inner: null,
|
||||
key: 'lexicon:polki', members: out.map((r) => r.key),
|
||||
text: `Biblioteka klauzul Lexicon, liczba klauzul według typu: ${shelves.map((x) => `${x.type ? x.label : 'bez typu'} ${x.count}`).join('; ')}.` });
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Library clauses whose words the question uses, read now (Lexicon's own full-text search), when it asks about the
|
||||
library's clauses or wordings ("jaką klauzulę poufności mamy w bibliotece"). [] otherwise, or without access. */
|
||||
const CHAT_LIBRARY = /bibliot|lexicon|wzorc|wzorów|wzory|wzór|library|template clause/iu;
|
||||
async function chatLibrary(question) {
|
||||
if (!CHAT_LIBRARY.test(question) || !/klauzul|zapis|postanowie|brzmieni|clause|wording/iu.test(question)) return [];
|
||||
const words = [...chatStems(question)].filter((w) => !CHAT_CLAUSE_STOP.includes(w) && !/^(?:bibli|lexic|wzor|wzór|klauz|libra|claus|mamy|jaką|which|what)/u.test(w)); // chatStems: 5-letter stems
|
||||
if (!words.length) return [];
|
||||
try {
|
||||
const hits = (await askerGet('lexicon', 'library/clauses?q=' + encodeURIComponent(words.slice(0, 8).join(' ')))) || [];
|
||||
return hits.slice(0, CHAT_CLAUSE_TOP).map((c) => ({ slug: 'lexicon', kind: 'klauzula',
|
||||
key: `lexicon:klauzula:${c.source_id}:${c.position}`, title: `${c.source_title}: ${c.label || String(c.text).slice(0, 80)}`, inner: null,
|
||||
labels: [c.source_title], text: `Klauzula z biblioteki Lexicon, wzorzec „${c.source_title}”${c.numbering ? ', ' + c.numbering : ''}` +
|
||||
`${(c.types || []).length ? ', typ ' + c.types.join(', ') : ''}: ${String(c.text).slice(0, 2000)}` }));
|
||||
} catch (ex) {
|
||||
if (ex.name === 'AbortError') throw ex;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/* "Utwórz projekt pisma z szablonu Najem" / "…od zera": an ACTION in Scribe, routed by code like contract review.
|
||||
Code picks the template (the only one whose name the question uses), or writes from scratch when asked to;
|
||||
anything unclear is asked back, never guessed. Scribe decides who may (the asker's own session). */
|
||||
const CHAT_DRAFT = /(?:^|[^\p{L}])(?:utwórz|utworz|załóż|zaloz|zacznij|przygotuj|create|start)\s+(?:nowy\s+|new\s+|a\s+)?(?:projekt\s+pisma|projekt\s+dokumentu|szkic|draft)/iu;
|
||||
const CHAT_SCRATCH = /od\s+zera|bez\s+szablonu|from\s+scratch|without\s+a?\s*template/iu;
|
||||
async function scribeWrite(method, path, body) {
|
||||
const r = await fetch(new URL('../scribe/api/v1/' + path, document.baseURI), { method, credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
||||
const data = jsonOf(await r.text());
|
||||
if (!r.ok) throw httpError(r, data);
|
||||
return data;
|
||||
}
|
||||
async function chatDraft({ question, index, en }) {
|
||||
const say = (pl, eng, extra = {}) => [en ? eng : pl, { coded: 'draft', ...extra }];
|
||||
const templates = index.records.filter((r) => r.kind === 'szablon');
|
||||
const title = ((question.match(/[„"«]([^”"»]{1,300})[”"»]/u) || [])[1] || '').trim();
|
||||
let tpl = null;
|
||||
if (!CHAT_SCRATCH.test(question)) {
|
||||
const words = new Set(reviewWords(question));
|
||||
const hit = templates.filter((r) => reviewWords(r.template.name).some((w) => words.has(w)));
|
||||
if (hit.length !== 1) {
|
||||
const list = (hit.length ? hit : templates).slice(0, 8).map((r) => r.template.name).join('; ');
|
||||
return say(templates.length ? `Z którego szablonu mam utworzyć projekt: ${list}? Napisz jego nazwę albo „od zera”.` : 'Nie widzę żadnego szablonu w Scribe. Napisz „od zera”, a utworzę projekt bez szablonu.',
|
||||
templates.length ? `Which template should the draft use: ${list}? Name it, or say "from scratch".` : 'I see no template in Scribe. Say "from scratch" and I will create a draft without one.',
|
||||
{ coded: 'ask', mentioned: (hit.length ? hit : templates).map((r) => r.key) });
|
||||
}
|
||||
tpl = hit[0].template;
|
||||
}
|
||||
try {
|
||||
const d = await scribeWrite('POST', 'drafts', { template_id: tpl ? tpl.id : null, title: title || (tpl ? tpl.name : '') });
|
||||
return say(`Utworzyłem w Scribe projekt pisma „${d.title || 'bez tytułu'}”${tpl ? ` z szablonu ${tpl.name}` : ' od zera'}.`,
|
||||
`I created the draft "${d.title || 'untitled'}" in Scribe${tpl ? ` from the template ${tpl.name}` : ' from scratch'}.`, { mentioned: ['scribe:szkic:' + d.id] });
|
||||
} catch (ex) {
|
||||
if (ex.name === 'AbortError') throw ex;
|
||||
if ([401, 403, 404].includes(ex.status)) return say('Tworzenie pism jest w module Scribe, a nie masz do niego dostępu.', 'Drafting lives in the Scribe module, and you have no access to it.');
|
||||
return say(`Scribe nie utworzył projektu: ${(ex.problem && ex.problem.detail) || ex.message}.`, `Scribe did not create the draft: ${(ex.problem && ex.problem.detail) || ex.message}.`);
|
||||
}
|
||||
}
|
||||
|
||||
// What Insider's resolve takes: an article of a code or a named EU act, a Dz.U. reference, a case number, a CELEX.
|
||||
// A topic question without a citation ("kara umowna") goes to chatTopic, and only once Insider's own index
|
||||
// of the acts' texts is built: its live mode matches titles and finds junk.
|
||||
@@ -2474,12 +2128,25 @@ async function chatLaw(question, index) {
|
||||
// A question about the law itself, not the firm's data: legal words, and nothing of ours named or implied.
|
||||
// "Termin" alone is a Sygna deadline, "kto" a person here, "w umowie z X" one of our contracts.
|
||||
const CHAT_TOPICWORD = /przepis|\bustaw|kodeks|\bprawo\b|prawn|przedawn|kar[aęy]\s+umown|wypowiedz|odstąpi|rękojm|odszkodowan|zadat|pracodawc|urlop|spadk|zachowek|orzecznictw|\blaws?\b|statut|case law/i;
|
||||
const CHAT_FIRMWORD = /(?:^|[^\p{L}])(?:mamy|mam|nasz\p{L}*|moj\p{L}*|mój|kontrahent\p{L}*|klien\p{L}*|kancelari\p{L}*|kto|sygn[aiy]e?|rejestr\p{L}*|w umowie|our|we)(?![\p{L}])/iu;
|
||||
// Strong firm words always mean our data. Weak ones read as ours only while no act is named: on the 20.11
|
||||
// exam (2026-11-27 count) 30 of 287 law questions went to the data on a weak word in the question or its
|
||||
// answers A-C ("kto" 13, "rejestr…" 10 for the acts on the pledge register and the KRS, "we" 3, "w umowie" 3,
|
||||
// "kancelarii" 1). "We" is a Polish preposition ("we wszystkich"), so it counts only in an English question.
|
||||
const CHAT_FIRMSTRONG = /(?:^|[^\p{L}])(?:mamy|mam|nasz\p{L}*|moj\p{L}*|mój|kontrahent\p{L}*|klien\p{L}*|sygn[aiy]e?|our)(?![\p{L}])/iu;
|
||||
const CHAT_FIRMWEAK = /(?:^|[^\p{L}])(?:kancelari\p{L}*|kto|rejestr\p{L}*|w umowie)(?![\p{L}])/iu;
|
||||
const CHAT_WE = /(?:^|[^\p{L}])we(?![\p{L}])/iu;
|
||||
// An act named: "Kodeksem…", "ustawą o …", "ustawą – Prawo przedsiębiorców", the Constitution, a regulation,
|
||||
// a code's abbreviation (k.c., k.p.c., k.s.h., k.r.o. …).
|
||||
const CHAT_ACTNAME = /kodeks|(?:^|[^\p{L}])ustaw\p{L}*\s+(?:o|[–-])\s|konstytucj|rozporządzeni|(?:^|[^\p{L}])k\.\s?[ckpswr]\./iu;
|
||||
// "Które umowy przewidują kary umowne?", "Który prawnik prowadzi najwięcej spraw?": our records as the subject.
|
||||
const CHAT_FIRMLIST = /(?:^|[^\p{L}])(?:któr|jaki|ile|pokaż|wymień)\p{L}*\s+(?:z\s+|wszystkie\s+)?(?:umowy|umów|sprawy|spraw|prawni\p{L}*)(?![\p{L}])/iu;
|
||||
function chatRoute(question, named = 0) {
|
||||
if (chatCites(question).length) return 'law_cite';
|
||||
return !named && CHAT_TOPICWORD.test(question) && !CHAT_FIRMWORD.test(question) && !CHAT_FIRMLIST.test(question) ? 'law_topic' : 'data';
|
||||
if (named || CHAT_FIRMSTRONG.test(question) || CHAT_FIRMLIST.test(question)) return 'data';
|
||||
// An act's name is a law question even without a topic word ("Konstytucja").
|
||||
if (CHAT_ACTNAME.test(question)) return 'law_topic';
|
||||
const weak = CHAT_FIRMWEAK.test(question) || (chatIsEn(question) && CHAT_WE.test(question));
|
||||
return CHAT_TOPICWORD.test(question) && !weak ? 'law_topic' : 'data';
|
||||
}
|
||||
const chatActName = (d) => (!d ? '' : /^Dz\.\s?U/.test(d.signature || '') ? d.signature : String(d.title || '').replace(/\s+z dnia[\s\S]*$/, ''));
|
||||
const chatOff = (d) => !!d && ((d.extra || {}).in_force === 'NOT_IN_FORCE' || /uchylon|nieobowiązuj|wygaśnięcie/i.test(d.status || ''));
|
||||
@@ -2574,9 +2241,13 @@ const CHAT_REWRITE = 'To krok pomocniczy przed wyszukaniem źródeł: źródeł
|
||||
const CHAT_REWRITE_MS = 3000;
|
||||
// Codes resolve by abbreviation to their current consolidated text; any other act is found by its title.
|
||||
// Anchored on "kodeks": a bare /rodzinny/ sent "o świadczeniach rodzinnych" to k.r.o.
|
||||
const CHAT_CODE_ABBR = [[/kodeks\p{L}* postępowania cywilnego/iu, 'k.p.c.'], [/kodeks\p{L}* postępowania karnego/iu, 'k.p.k.'],
|
||||
[/kodeks\p{L}* postępowania administracyjnego/iu, 'k.p.a.'], [/kodeks\p{L}* spółek handlowych/iu, 'k.s.h.'], [/kodeks rodzinny/i, 'k.r.o.'],
|
||||
[/kodeks pracy/i, 'k.p.'], [/kodeks cywilny/i, 'k.c.'], [/kodeks wykroczeń/i, 'k.w.'], [/kodeks karny(?! (?:skarbowy|wykonawczy))/i, 'k.k.'],
|
||||
// Any case of both words: Qwen 3.5 9B named "Kodeks postępowania cywilny" 10 times on the 20.11 exam and none
|
||||
// of them reached k.p.c. while only "…cywilnego" was known (split of 2026-11-27). The k.k. stem stops at the
|
||||
// word's end, or "Kodeks karn|y skarbowy" would pass the lookahead.
|
||||
const CHAT_CODE_ABBR = [[/kodeks\p{L}* postępowania cywiln/iu, 'k.p.c.'], [/kodeks\p{L}* postępowania karn/iu, 'k.p.k.'],
|
||||
[/kodeks\p{L}* postępowania administracyjn/iu, 'k.p.a.'], [/kodeks\p{L}* spółek handlowych/iu, 'k.s.h.'], [/kodeks\p{L}* rodzinn/iu, 'k.r.o.'],
|
||||
[/kodeks\p{L}* pracy/iu, 'k.p.'], [/kodeks\p{L}* cywiln/iu, 'k.c.'], [/kodeks\p{L}* wykroczeń/iu, 'k.w.'],
|
||||
[/kodeks\p{L}* karn\p{L}*(?!\p{L}| (?:skarbow|wykonawcz))/iu, 'k.k.'],
|
||||
[/\bRODO\b|2016\/679|ogólne rozporządzenie o ochronie danych/i, 'RODO']];
|
||||
const chatTextPath = (d) => (/^(?:eurlex|cellar):/.test(d.id) ? 'acts/eu/' : 'acts/') + chatBare(d) + '/text';
|
||||
const chatSup = (n) => String(n).replace(/\^(\d+)/, (_, d) => [...d].map((c) => '⁰¹²³⁴⁵⁶⁷⁸⁹'[c]).join(''));
|
||||
@@ -2597,8 +2268,16 @@ async function chatRewrite(model, question, onStatus) {
|
||||
arm(true);
|
||||
try {
|
||||
const got = await chatRound(model, [{ role: 'user', content: CHAT_REWRITE + question }], { content: '' }, onUpdate,
|
||||
{ temperature: 0, max_tokens: 120, signal: AbortSignal.any([chat.ctl.signal, ctl.signal]) });
|
||||
const j = JSON.parse(got.text.slice(got.text.indexOf('{'), got.text.lastIndexOf('}') + 1));
|
||||
{ temperature: 0, max_tokens: 200, signal: AbortSignal.any([chat.ctl.signal, ctl.signal]) });
|
||||
let j;
|
||||
try {
|
||||
j = JSON.parse(got.text.slice(got.text.indexOf('{'), got.text.lastIndexOf('}') + 1));
|
||||
} catch {
|
||||
// max_tokens 120 cut 3 of Bielik's rewrites on the 20.11 exam after a right "akt" and before the "}"; 200
|
||||
// leaves room, and a reply cut anyway still names its act. Its queries may be cut mid-word: none are kept.
|
||||
const m = /"akt"\s*:\s*("(?:[^"\\]|\\.)*")/.exec(got.text);
|
||||
return { act: m ? String(JSON.parse(m[1])) : '', queries: [] };
|
||||
}
|
||||
return { act: String(j.akt || ''), queries: (Array.isArray(j.q) ? j.q : []).map(String).slice(0, 4) };
|
||||
} catch (ex) {
|
||||
if (chat.ctl.signal.aborted || ex.refusal) throw ex;
|
||||
@@ -2612,7 +2291,12 @@ async function chatActDoc(name) {
|
||||
if (code) return ((await askerGet('insider', 'resolve?citation=' + encodeURIComponent('art. 1 ' + code)) || {}).documents || [])[0] || null;
|
||||
// "Ustawa z dnia 30 maja 2014 r. o prawach konsumenta" is the t.j. "Ustawa o prawach konsumenta (tekst jednolity)";
|
||||
// the same words are no match for "o zmianie ustawy o prawach konsumenta".
|
||||
const bare = (t) => t.toLowerCase().replace(/\s*\(.*$/, '').replace(/^ustawa\s*(?:z dnia .*? r\.)?\s*[-–]?\s*/, '').trim();
|
||||
// Konstytucja is titled "Konstytucja Rzeczypospolitej Polskiej z dnia 2 kwietnia 1997 r." (DU/1997/483), so the
|
||||
// model's name missed it 8 times (Qwen) and 9 (Bielik) on the 20.11 exam: a trailing date is cut from both sides.
|
||||
// Cut here, not added to CHAT_CODE_ABBR, because nothing showed that Insider's `resolve` takes the constitution
|
||||
// by an abbreviation; the act search has it (2026-11-27). "Konstytucja (RP)" is its short name.
|
||||
const bare = (t) => t.toLowerCase().replace(/\s*\(.*$/, '').replace(/^ustawa\s*(?:z dnia .*? r\.)?\s*[-–]?\s*/, '').trim()
|
||||
.replace(/\s+z dnia [^)]*? r\.$/, '').replace(/^konstytucj\p{L}*(?: rp)?$/u, 'konstytucja rzeczypospolitej polskiej');
|
||||
const want = bare(name);
|
||||
if (want.length < 6) return null;
|
||||
const s = await askerGet('insider', 'search?kind=act&jurisdiction=pl&limit=6&q=' + encodeURIComponent(want.slice(0, 300)));
|
||||
@@ -2788,13 +2472,12 @@ async function chatIndex() {
|
||||
const register = chatRegister(today);
|
||||
const parts = [['Rejestr umów (Galena)', () => register], ['Sygna (sprawy, terminy, klienci)',
|
||||
async () => chatSygna(today, names, ((await register) || []).filter((r) => r.contract).map((r) => r.contract))],
|
||||
['Counsel Scorecard (kancelarie zewnętrzne, oceny)', chatCounsel], ['Galena (dokumenty, opinie)', () => chatGalena(names)],
|
||||
['Scribe (szablony, projekty pism)', () => chatScribe(names)], ['Lexicon (wzorce, biblioteka klauzul)', chatLexicon]];
|
||||
['Counsel Scorecard (kancelarie zewnętrzne, oceny)', chatCounsel], ['Galena (dokumenty, opinie)', () => chatGalena(names)]];
|
||||
const [got, law] = await Promise.all([Promise.all(parts.map(([, read]) => read())), askerGet('insider', 'sources')]);
|
||||
const blind = parts.filter((_, i) => got[i] === null).map(([name]) => name);
|
||||
// "Do you have access to Insider?" is a question about the chat itself: answered from this record.
|
||||
const seen = parts.filter((_, i) => got[i] !== null).map(([name]) => name);
|
||||
const access = { slug: 'atrium', kind: 'dostęp', key: 'atrium:dostep', title: 'Dostęp czatu: moduły i dane widoczne na Twoim koncie (Insider, Sygna, Counsel, Galena z rejestrem umów, Scribe, Lexicon)', inner: null,
|
||||
const access = { slug: 'atrium', kind: 'dostęp', key: 'atrium:dostep', title: 'Dostęp czatu: moduły i dane widoczne na Twoim koncie (Insider, Sygna, Counsel, Galena z rejestrem umów)', inner: null,
|
||||
text: `Czat czyta dane na koncie pytającego. Ma dostęp do: ${seen.join(', ') || 'żadnego modułu'}. Nie ma dostępu do: ${blind.join(', ') || 'brak takich modułów'}. ` +
|
||||
(law === null ? 'Insider (przepisy i orzeczenia): brak dostępu na tym koncie.'
|
||||
: 'Insider (przepisy i orzeczenia): dostęp jest. Czat pobiera tekst przepisu, akt albo orzeczenie, gdy pytanie podaje konkretne odwołanie, np. art. 471 k.c., art. 6 RODO, Dz.U. 2018 poz. 1000, sygnaturę II C 2145/25. Szuka też przepisów po samym temacie pytania.') };
|
||||
@@ -4437,20 +4120,11 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
|
||||
const named = chatNamed(question, index.records).map(([k]) => index.byKey.get(k));
|
||||
// A party hit never takes a law question off Insider unless the question is about a contract.
|
||||
if (!named.length && (!CHAT_TOPICWORD.test(question) || /umow|kontrakt|contract|agreement/iu.test(question))) named.push(...chatByParty(question, index.records));
|
||||
// "Sprawdź umowę …": an action in Arbiter, not a question to the model (chatReview).
|
||||
// Only about a contract of the register: one named, or "tę umowę" after an answer that named one. "Sprawdź, czy
|
||||
// umowa o dzieło wymaga formy pisemnej" names none and stays a question about the law.
|
||||
if (CHAT_REVIEW.test(question) && chatRoute(question) !== 'law_cite'
|
||||
&& (named.some((r) => r && r.contract) || chatAnaphora(question).demonstrative)) {
|
||||
const [text, extra] = await chatReview({ question, named, prev: at >= 0 ? turns[at] : null, index, en });
|
||||
return done(text, extra);
|
||||
}
|
||||
// "Utwórz projekt pisma z szablonu …": an action in Scribe (chatDraft).
|
||||
if (CHAT_DRAFT.test(question)) {
|
||||
const [text, extra] = await chatDraft({ question, index, en });
|
||||
return done(text, extra);
|
||||
}
|
||||
const ana = chatAnaphora(question);
|
||||
// "w tej sprawie" in a question about a provision means the case the question itself describes, not a record of
|
||||
// this conversation: the 20.11 exam asked 3 such first-turn questions back (2024-17, 2024-19, 2025-54, 27.11).
|
||||
// Only in a first turn: after a contract, "przepisy, na które powołuje się ta umowa" means that contract, and
|
||||
// after a failed turn it is still asked about (3 of 56 czat-v2 turns went to Insider instead, 27.11).
|
||||
const ana = turns.length || chatRoute(question) === 'data' ? chatAnaphora(question) : {};
|
||||
// "ta druga" right after the map asked which firm: the second candidate as the question listed them. Resolved
|
||||
// through the anchors' records instead, it missed when the two anchors were of different kinds.
|
||||
const asked = graf && !named.length && ana.ordinal && prev && prev.coded === 'ask' && prev.graf && prev.graf.order;
|
||||
@@ -4536,8 +4210,6 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
|
||||
topic = t.records;
|
||||
}
|
||||
const law = await chatLaw(question, index);
|
||||
// A question about what a named contract SAYS: its best paragraphs, read now from Galena (chatClauses).
|
||||
const clauses = [...await chatClauses(question, [...named, ...resolved]), ...await chatLibrary(question)];
|
||||
// A fault in the law graph leaves the turn as without it.
|
||||
let lawGraph = { near: [] };
|
||||
if (prawo) {
|
||||
@@ -4563,7 +4235,7 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
|
||||
// The entity's card right after law and topic; a one-record link card behind its record, so [1] stays the record.
|
||||
const pool = [...(istnienie && !pick && !named.length && !resolved.length && !card && !law.length ? chatExistence(question, index) : []),
|
||||
...(pick ? [pick.rec] : []), ...law, ...topic, ...lawGraph.near,
|
||||
...(card && card.rec.kind === 'karta' ? [card.rec] : []), ...named, ...clauses, ...resolved,
|
||||
...(card && card.rec.kind === 'karta' ? [card.rec] : []), ...named, ...resolved,
|
||||
...(card && card.rec.kind !== 'karta' ? [card.rec] : []), ...backSum, ...back, ...chatCarry(prev, index),
|
||||
...(card ? card.lead : []), ...found]
|
||||
.filter((r) => !seen.has(r.key) && seen.add(r.key));
|
||||
@@ -4575,7 +4247,7 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
|
||||
const listHit = (r) => (r.list || []).some((g) => g.re && g.re.test(question));
|
||||
const hitFams = new Set(pool.filter(listHit).map(fam));
|
||||
const sources = pool.filter((r) => !(r.list && hitFams.has(fam(r))) || listHit(r))
|
||||
.slice(0, CHAT_TOP + law.length + topic.length + lawGraph.near.length + clauses.length);
|
||||
.slice(0, CHAT_TOP + law.length + topic.length + lawGraph.near.length);
|
||||
const name = (slug) => (chatModules().find((m) => m.slug === slug) || { name: slug }).name;
|
||||
const toRef = (r, i) => ({ n: i + 1, key: r.key, kind: r.kind, slug: r.slug, module: name(r.slug), title: r.title, text: r.text,
|
||||
data: !['przepis', 'akt', 'orzeczenie'].includes(r.kind), inner: r.inner, url: r.url });
|
||||
@@ -4991,7 +4663,6 @@ async function viewHome(C) {
|
||||
</form>
|
||||
<div id="homeResults" class="home-results hidden" aria-live="polite"></div>` : '')
|
||||
+ '<div id="homeKeys"></div>'
|
||||
+ homeGalenaLinks()
|
||||
+ '<div id="homeStats" class="home-stats" aria-live="polite"></div>'
|
||||
+ '<div id="homeModStats" class="home-stats" aria-live="polite"></div>'
|
||||
/* Your apps are the sidebar; the home page mentions them only when there are none. */
|
||||
@@ -5025,20 +4696,9 @@ async function loadHomeKeys() {
|
||||
|
||||
/* The home page's numbers: yours for everybody, the platform's for an administrator. Loaded after
|
||||
the page is drawn, so a slow query never holds up the search box; a failure just leaves it out. */
|
||||
/* Galena has no menu entry (a service module), so its two screens people go to on their own get a
|
||||
way in here: the documents and the contract register, opened in the frame. Only for somebody with access. */
|
||||
function homeGalenaLinks() {
|
||||
const g = (state.launcher || []).find((m) => m.slug === 'galena' && m.has_access);
|
||||
if (!g) return '';
|
||||
return `<div class="home-label"><span>Dokumenty</span></div><div class="row" style="gap:8px;flex-wrap:wrap;margin-bottom:12px">
|
||||
<a class="btn" href="${esc(frameHash('galena', ''))}">${moduleIcon(g, 16)}<span>Dokumenty</span></a>
|
||||
<a class="btn" href="${esc(frameHash('galena', 'cards'))}">${moduleIcon(g, 16)}<span>Rejestr umów</span></a></div>`;
|
||||
}
|
||||
|
||||
async function loadHomeStats() {
|
||||
const box = $('homeStats');
|
||||
if (!box) return;
|
||||
const trends = state.user && state.user.is_admin ? homeTrendCards() : Promise.resolve([]);
|
||||
let st;
|
||||
try { st = await api('GET', '/home/stats'); } catch { return; }
|
||||
if (!$('homeStats')) return; // navigated away meanwhile
|
||||
@@ -5065,45 +4725,11 @@ async function loadHomeStats() {
|
||||
<a class="chart-more" href="#/admin/audit">Dziennik zdarzeń</a></div>`);
|
||||
}
|
||||
}
|
||||
if (p) charts.push(...await trends);
|
||||
if (!$('homeStats')) return;
|
||||
box.innerHTML = `<div class="home-label"><span>W skrócie</span></div><div class="stats">${tiles.join('')}</div>`
|
||||
+ `<div class="charts">${charts.join('')}</div>`;
|
||||
localize(box);
|
||||
}
|
||||
|
||||
/* The platform's trends from the event log: events per day
|
||||
across the modules, and how long documents take from their first version to approval and to
|
||||
signature. Platform-wide sums, so administrators only; no log (standalone) shows nothing. */
|
||||
const TREND_SEGMENT = { przygotowanie: 'od pierwszej wersji do zatwierdzenia', podpisanie: 'od zatwierdzenia do podpisu' };
|
||||
async function homeTrendCards() {
|
||||
let t;
|
||||
try { t = await api('GET', '/home/trends'); } catch { return []; }
|
||||
const out = [];
|
||||
const a = t.activity;
|
||||
if (a && a.status === 'ok' && a.days.length) {
|
||||
const series = a.days.map((d) => ({ day: d.date, n: Object.values(d.counts).reduce((s, n) => s + n, 0) }));
|
||||
out.push(chartCard('Zdarzenia modułów', 'umowy, obiegi, podpisy i negocjacje, ostatnie 30 dni', series));
|
||||
if (a.kinds.length) {
|
||||
const max = Math.max(...a.kinds.map((k) => k.total));
|
||||
out.push(`<div class="card chart"><div class="chart-h"><b>Zdarzenia według rodzaju</b><span>ostatnie 30 dni</span></div>
|
||||
<div class="hbars">${a.kinds.map((k) => `<div class="hbar"><span>${esc(k.label)}</span>
|
||||
<span class="hbar-t"><i style="width:${Math.max(4, Math.round(k.total / max * 100))}%"></i></span><b>${esc(String(k.total))}</b></div>`).join('')}</div></div>`);
|
||||
}
|
||||
}
|
||||
const d = t.durations;
|
||||
if (d && d.status === 'ok' && d.measured) {
|
||||
const max = Math.max(1, ...d.bands.map((b) => b.count));
|
||||
const band = (b) => (b.to == null ? `${b.from}+` : `${b.from}–${b.to}`) + ' ' + _tr('dni');
|
||||
out.push(`<div class="card chart"><div class="chart-h"><b>Czas obsługi dokumentu</b><span>${esc(d.segments.map((s) => _tr(TREND_SEGMENT[s] || s)).join(', '))}</span></div>
|
||||
<div class="chart-v">${esc(String(d.median_days))} <span class="tiny faint">${esc(_tr('dni (mediana)'))}</span></div>
|
||||
<div class="hbars">${d.bands.map((b) => `<div class="hbar"><span>${esc(band(b))}</span>
|
||||
<span class="hbar-t"><i style="width:${Math.max(4, Math.round(b.count / max * 100))}%"></i></span><b>${esc(String(b.count))}</b></div>`).join('')}</div>
|
||||
<div class="tiny faint">${esc(_tr('Zmierzono dokumentów'))}: ${esc(String(d.measured))}</div></div>`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Numbers from the modules themselves, read from the dashboards they already serve: one origin
|
||||
and one account, so the browser asks each module directly with the same session cookie and
|
||||
Atrium's backend is not involved. Each figure is the module's own permission-filtered count —
|
||||
@@ -5204,7 +4830,6 @@ const CATALOG_EN = {
|
||||
'Ocena i ankiety': 'Reviews and surveys',
|
||||
'Prawo': 'Law',
|
||||
'Umowy': 'Contracts',
|
||||
'Analiza umów, biblioteka klauzul i projekty umów — w czacie.': 'Contract analysis, the clause library and contract drafts, in the chat.',
|
||||
'Pulpit': 'Dashboard',
|
||||
// galena
|
||||
'Dysk w chmurze z pełną historią zmian w repozytoriach git.': 'A cloud drive with the full history of every change, in git repositories.',
|
||||
@@ -5228,9 +4853,6 @@ const CATALOG_EN = {
|
||||
"Arbiter analyses contracts: a queue of jobs, an analysis engine run on the server or on a workstation, red lines and data masking, and at the end a lawyer's sign-off on the analysis and a frozen contract card as the record.",
|
||||
// lexicon
|
||||
'Biblioteka klauzul i standardów.': 'The clause library and standards.',
|
||||
'Biblioteka klauzul.': 'The clause library.',
|
||||
'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).':
|
||||
'Lexicon cuts contract templates into clauses, indexes them for full-text search and sorts them by type. The standards for checking contracts live in skills (Atrium → Skills).',
|
||||
'Lexicon tnie wzory umów na klauzule, indeksuje je do wyszukiwania pełnotekstowego, porządkuje według typów i przechowuje standardy (reguła, wzorcowe brzmienie, stanowisko rezerwowe), według których Arbiter sprawdza umowy.':
|
||||
'Lexicon cuts contract templates into clauses, indexes them for full-text search, sorts them by type and keeps the standards (the rule, the model wording, the fallback position) that Arbiter checks contracts against.',
|
||||
// agora
|
||||
@@ -5260,7 +4882,7 @@ function accessChip(m) {
|
||||
}
|
||||
|
||||
function marketCard(m) {
|
||||
return `<a class="mcard" href="${m === CONTRACTS_ENTRY ? '#/umowy' : '#/marketplace/' + enc(m.slug)}">
|
||||
return `<a class="mcard" href="#/marketplace/${enc(m.slug)}">
|
||||
<div class="mtop">${moduleIcon(m, 44)}<div class="mtxt">
|
||||
<div class="mname">${dat(m.name)}</div>
|
||||
${m.category ? `<div class="tiny faint">${dat(catalogText(m.category))}</div>` : ''}</div></div>
|
||||
@@ -5272,11 +4894,6 @@ function marketCard(m) {
|
||||
async function viewMarketplace(C, q) {
|
||||
const d = await api('GET', withQuery('/marketplace', { q: q.q, category: q.category }));
|
||||
setCrumb([{ label: 'Moduły' }]);
|
||||
// One card for the three contract modules (CONTRACTS), which open as the chat, not one each.
|
||||
const umowy = hasContracts() && (!q.category || q.category === CONTRACTS_ENTRY.category)
|
||||
&& (!q.q || `Umowy
|
||||
${CONTRACTS_ENTRY.tagline}`.toLowerCase().includes(q.q.trim().toLowerCase()));
|
||||
const cards = (umowy ? [CONTRACTS_ENTRY] : []).concat(d.modules.filter((m) => !CONTRACTS.includes(m.slug)));
|
||||
|
||||
const catHref = (c) => withQuery('#/marketplace', { q: q.q, category: c });
|
||||
const contact = setting('support_contact');
|
||||
@@ -5287,8 +4904,8 @@ ${CONTRACTS_ENTRY.tagline}`.toLowerCase().includes(q.q.trim().toLowerCase()));
|
||||
<a class="chip ${!q.category ? 'on' : ''}" href="${esc(catHref(''))}">Wszystkie</a>
|
||||
${d.categories.map((c) => `<a class="chip ${q.category === c ? 'on' : ''}" href="${esc(catHref(c))}">${dat(catalogText(c))}</a>`).join('')}
|
||||
</div></div>`
|
||||
+ (cards.length
|
||||
? `<div class="mcards">${cards.map(marketCard).join('')}</div>`
|
||||
+ (d.modules.length
|
||||
? `<div class="mcards">${d.modules.map(marketCard).join('')}</div>`
|
||||
: '<div class="empty">Brak modułów.</div>')
|
||||
+ (contact ? `<div class="faint tiny" style="margin-top:16px"><span>Potrzebujesz dostępu? Kontakt:</span> ${dat(contact)}</div>` : '');
|
||||
|
||||
@@ -6685,7 +6302,7 @@ async function viewAdminModules(C) {
|
||||
</tr></thead><tbody>${rows.map((m) => `<tr class="click" onclick="location.hash='#/admin/modules/${enc(m.slug)}'">
|
||||
<td><div class="cell">${moduleIcon(m, 28)}<div><a href="#/admin/modules/${enc(m.slug)}" onclick="event.stopPropagation()">${dat(m.name)}</a><div class="mono tiny faint">${esc(m.slug)}</div></div></div></td>
|
||||
<td${lbl('Status')}>${statusChip(m.status) || `<span class="chip">${esc(STATUS_LABEL.live)}</span>`}</td>
|
||||
<td${lbl('Dostępność')}>${availChip(m.availability)}${m.in_menu === false ? ' <span class="chip">Usługa</span>' : ''}</td>
|
||||
<td${lbl('Dostępność')}>${availChip(m.availability)}</td>
|
||||
<td${lbl('Adres')}>${m.url ? `<span class="chip ok">${svg(ICN.check, 12)}</span>` : '<span class="chip warn">brak</span>'}</td>
|
||||
<td class="num col-opt"${lbl('Przypisania')}>${esc(String(m.assignments))}</td>
|
||||
<td class="num"${lbl('Wnioski o dostęp')}>${m.pending_requests ? `<span class="chip err">${esc(String(m.pending_requests))}</span>` : '0'}</td>
|
||||
@@ -6745,8 +6362,6 @@ function moduleForm(m, creating) {
|
||||
${creating ? `<label class="field">Dostępność${choice('mfAvail', AVAIL_LABEL, setting('default_availability') || 'everyone')}</label>` : ''}
|
||||
<label class="field">Kolejność<input id="mfOrder" type="number" min="0" max="10000" value="${esc(String(m.sort_order ?? 100))}" /></label>
|
||||
</div>
|
||||
<label class="check"><input id="mfInMenu" type="checkbox" ${m.in_menu === false ? '' : 'checked'} /> <span>Pokazuj w menu i katalogu</span></label>
|
||||
<div class="faint tiny">Odznaczony moduł działa jako usługa: dostęp, odnośniki i kafle zostają, znika tylko pozycja w menu.</div>
|
||||
<div class="identity">${identityPicker(m.hue || 'grape', m.glyph || 'grid')}</div>`;
|
||||
}
|
||||
|
||||
@@ -6765,7 +6380,6 @@ function readModuleForm() {
|
||||
description: $('mfDescription').value, url: $('mfUrl').value, health_url: $('mfHealth').value,
|
||||
status: $('mfStatus').value,
|
||||
sort_order: orderValue(),
|
||||
in_menu: $('mfInMenu').checked,
|
||||
hue: $('mfHue').value, glyph: $('mfGlyph').value,
|
||||
};
|
||||
}
|
||||
@@ -7666,21 +7280,9 @@ const innerOf = (win) => (win.location.hash || '').replace(/^#\/?/, '');
|
||||
function navHidden() {
|
||||
try { return JSON.parse(localStorage.getItem(NAV_HIDDEN_KEY) || '[]'); } catch { return []; }
|
||||
}
|
||||
/* A service module (`in_menu` false, e.g. Galena) is in the launcher — its links, frame and stats
|
||||
tiles work — but has no sidebar entry of its own; nor does it appear in "Customise the list". */
|
||||
const inMenu = (m) => m.in_menu !== false;
|
||||
/* Decision 1 of 18.11 (issue #53): the chat is the only screen for contracts. Arbiter, Lexicon and
|
||||
Scribe are service modules the chat calls, shown together as ONE entry, „Umowy”, which opens the
|
||||
chat — in the sidebar and in the catalogue, for whoever may use at least one of the three. */
|
||||
const CONTRACTS = ['arbiter', 'lexicon', 'scribe'];
|
||||
const CONTRACTS_ENTRY = { slug: 'umowy', name: 'Umowy', hue: 'indigo', glyph: 'shield', category: 'Umowy', status: 'live', launchable: true,
|
||||
tagline: 'Analiza umów, biblioteka klauzul i projekty umów — w czacie.' };
|
||||
const hasContracts = () => state.launcher.some((m) => CONTRACTS.includes(m.slug));
|
||||
const contractsNavItem = (cur) => (hasContracts()
|
||||
? `<a class="nav-item ${cur === '#/umowy' ? 'on' : ''}" href="#/umowy">${moduleIcon(CONTRACTS_ENTRY, 18)}<span>Umowy</span></a>` : '');
|
||||
// The open module stays listed even when hidden: its nav lives only under its own entry.
|
||||
const navModules = () => state.launcher.filter((m) => embeddable(m)
|
||||
&& (m.slug === frame.slug || (inMenu(m) && !navHidden().includes(m.slug))));
|
||||
&& (m.slug === frame.slug || !navHidden().includes(m.slug)));
|
||||
const basePath = (m) => new URL(safeUrl(m.url), document.baseURI).pathname;
|
||||
/* mirror-prefix:begin — a path is under a module only at a segment boundary: `/galena` must not
|
||||
claim `/galena-x`. Both sides get a trailing slash, so `/galena` itself still matches `/galena/`. */
|
||||
@@ -7944,7 +7546,7 @@ function openFrameSearch() {
|
||||
|
||||
function openNavPrefs() {
|
||||
const hidden = navHidden();
|
||||
const rows = state.launcher.filter((m) => embeddable(m) && inMenu(m)).map((m) => `<label class="navpref" data-no-i18n>
|
||||
const rows = state.launcher.filter(embeddable).map((m) => `<label class="navpref" data-no-i18n>
|
||||
<input type="checkbox" value="${esc(m.slug)}" ${hidden.includes(m.slug) ? '' : 'checked'} />
|
||||
${moduleIcon(m, 22)}<span>${esc(m.name)}</span></label>`).join('');
|
||||
modal('Moduły w pasku bocznym', 'Odznaczone znikną z paska bocznego. W katalogu zostają.',
|
||||
|
||||
Reference in New Issue
Block a user