Compare commits

..
Author SHA1 Message Date
adminandClaude Opus 5.5 0eefd90b40 Submodules: point at the Gitea repositories
The GitHub repositories are gone with the suspended account (or are
mirrored on Gitea). Relative URLs (../<repo>.git) resolve against wherever
this repository is cloned from.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:37:52 +01:00
adminandClaude Opus 5.5 e2babc1591 Submodules: point at the Gitea repositories
The GitHub repositories are gone with the suspended account (or are
mirrored on Gitea). Relative URLs (../<repo>.git) resolve against wherever
this repository is cloned from.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:36:32 +01:00
tobayahandClaude Opus 5.5 c610e1b008 test: chat.komplet console tests
Case alternations as a closed list read only under komplet, a firm in another case,
the limit of 20 with the entity's records first, the namesake firm kept by the filter,
a matter by number left unfiltered, two parties without the filter, the asker's records,
one step from a record named by number, the matters summary, off by default.
The filter test's harness takes chatTurn switches and exports block functions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJVsYuC3PHxoZRMsk3
2026-11-28 15:07:58 +01:00
tobayahandClaude Opus 5.5 05e699e38c chat: under komplet the filter spares namesakes and numbered matters
The filter keeps found records that mention the asked party's distinguishing word
(the namesake firm, the matter where it is the other side), cuts nothing when the root
is a matter named by number, treats one name on several entities as one party, and
reads "Fundacja Ostoja" by its second word. Dry gates 2026-11-28: battery gold misses
31 -> 7 (target 8, passed); filter cuts gold on 4 turns (target 0, not passed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJVsYuC3PHxoZRMsk3
2026-11-28 15:00:15 +01:00
tobayahandClaude Opus 5.5 a30de3a9dc chat: komplet of the named entity's records behind chat.komplet (WIP, gates not passed)
Behind chat.komplet (off by default): the map's records for one named entity, the
asker or up to three entities join the sources ahead of search hits, the limit rises
to 20 on that path, a record named by number brings its matter, client, deadlines and
orders, names are read with a closed list of consonant alternations, and Sygna gets a
matters-by-status summary. Dry gates on 2026-11-28: battery gold misses 31 -> 11
(target 8); the filter still cuts gold on 16 turns (target 0). Not measured with a model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJVsYuC3PHxoZRMsk3
2026-11-28 14:45:19 +01:00
tobayahandClaude Opus 5.5 3a60ac7882 chat: the entity filter keeps every record the map ties to the entity
Rank-0 edges alone cut the asked firm's own contracts that the map ties by
name only (Ortolan in the bateria, Kalinowy Dwór in zestaw 9 and 10). The
dry gate, with gold keys now translated to the fixture's ids, cuts no gold
record of the asked entity on bateria and zestaw 9; on zestaw 10 and 11 it
cuts only records the map does not tie to it at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJVsYuC3PHxoZRMsk3
2026-11-28 11:08:47 +01:00
tobayahandClaude Opus 5.5 16bf069604 chat: filtr podmiotu behind chat.filtr, off by default
A question naming exactly one outside entity in full (chatGraphFind: one root,
not a partial hit, not a team member) keeps, of what search found, only that
entity's rank-0 records. Named and resolved records, cards, "z nich", law and
the prompt are unchanged; an ambiguous name, two entities, a partial name, a
card already cutting, or an empty result leave the turn as it was.

Spec: lw-platform/specs/2026-11-28-czat-filtr-podmiotu.md. Dry gate (bateria,
zestaw 9 and 10, filter off vs on): the filter fires on 12/112, 8/36, 8/36
turns, cuts no gold key, and changes nothing outside those turns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJVsYuC3PHxoZRMsk3
2026-11-28 10:48:46 +01:00
32 changed files with 497 additions and 686 deletions
+19 -34
View File
@@ -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:
-126
View File
@@ -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
-1
View File
@@ -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"
+3 -3
View File
@@ -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,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
View File
@@ -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
+3 -3
View File
@@ -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
+2 -2
View File
@@ -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))
+167
View File
@@ -0,0 +1,167 @@
"""Home chat's filter of one entity (spec lw-platform/specs/2026-11-28-czat-filtr-podmiotu.md, `chat.filtr`).
Signed with their owner, small models still gave another firm's record to the firm asked about. With the filter, a
question naming exactly one outside entity in full keeps, of what search found, only the records the map ties to that entity.
An ambiguous name, two entities, a partial name and an empty result leave the turn as it was; named records stay.
The chat block of `frontend/app.js` is built under Node, as in `test_chat_traps_console.py`, with a model stub.
DB-free and network-free; skipped only where no `node` binary exists.
"""
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")
APP = ROOT / "frontend" / "app.js"
pytestmark = pytest.mark.skipif(NODE is None, reason="needs node on PATH")
# The world on a frozen day (2026-11-12). The asker is u1. Pairs that must be told apart: Miedziak Energia S.A.
# and sp. z o.o. (two NIPs), Velmora Pompy and Velmora Serwis, contract UM-2026-0109 and matter 2026/0109.
# Pairs that must NOT be: Kalinowy Dwór written "Sp. z o.o." and in full, two unrelated foundations.
_PRELUDE = r"""
const fs = require('fs');
const src = fs.readFileSync(APP, 'utf8');
const BLOCK = src.slice(src.indexOf('// Code finds, the model reads'), src.indexOf("// A module's screen"));
const TODAY = '2026-11-12';
const NOW = Date.parse(TODAY + 'T12:00:00Z');
class FixedDate extends Date { constructor(...a) { super(...(a.length ? a : [NOW])); } static now() { return NOW; } }
const party = (id, name, nip, kind = 'organisation') => ({ id, name, nip, address: null, kind });
const matter = (id, reference, name, client, clientId, lawyer) => ({ id, reference, name, client_name: client, client_party_id: clientId,
practice_area: null, status: 'open', responsible_lawyer_id: lawyer, opened_at: '2026-03-01', closed_at: null, description: '' });
const card = (id, number, name, cp, matterRef, created = '2026-02-01T09:00:00Z') => ({ id, project_id: 'p-' + id, number, name,
counterparty: cp ? cp.name : null, counterparties: cp ? [cp] : [], matter_ref: matterRef, status: 'obowiazuje',
value_amount: 1000, value_currency: 'PLN', concluded_on: '2026-01-02', ends_on: '2027-06-30', created_at: created });
const order = (id, firmId, reference, title, notes, created = '2026-11-10T08:00:00Z') => ({ id, firm_id: firmId, reference, title,
billing_notes: notes, status: 'in_progress', budget_estimate: 5000, budget_currency: 'PLN', matter_owner_id: null, created_at: created });
const WORLD = {
'sygna/users': [{ id: 'u1', full_name: 'Anna Nowak' }, { id: 'u2', full_name: 'Piotr Zając' }],
'sygna/parties': [
party('s1', 'Miedziak Energia S.A.', '6340001110'),
party('s2', 'Miedziak Energia sp. z o.o.', '6340005550'),
party('s3', 'Velmora Pompy sp. z o.o.', '5250001111'),
party('s4', 'Velmora Serwis sp. z o.o.', '5250002222'),
party('s5', 'Fundacja Ostoja', null),
party('s6', 'Fundacja Zielony Las', null),
party('s7', 'Kalinowy Dwór sp. z o.o.', null)],
'sygna/matters': [
matter('m1', '2026/0107', 'Spór o dostawy pomp', 'Velmora Pompy sp. z o.o.', 's3', 'u1'),
matter('m2', '2026/0109', 'Windykacja należności', 'Miedziak Energia sp. z o.o.', 's2', 'u2')],
'sygna/deadlines?days=365': [
{ id: 'd1', title: 'Odpowiedź na pozew', kind: 'procedural', due_date: '2026-11-20', days_left: 8, completed_at: null, matter_id: 'm1',
matter_reference: '2026/0107', matter_name: 'Spór o dostawy pomp', basis: null, owner_id: 'u1', source: 'court' },
{ id: 'd2', title: 'Wezwanie do zapłaty', kind: 'internal', due_date: '2026-11-25', days_left: 13, completed_at: null, matter_id: 'm2',
matter_reference: '2026/0109', matter_name: 'Windykacja należności', basis: null, owner_id: 'u2', source: 'internal' }],
'galena/cards?limit=200&offset=0': [
// Same digits as matter 2026/0109, pinned to no matter.
card('c1', 'UM-2026-0109', 'Dostawa energii', { id: 'k1', name: 'Miedziak Energia S.A.', nip: '6340001110' }, null),
// Pinned to a matter the asker sees.
card('c2', 'UM-2026-0110', 'Serwis pomp', { id: 'k2', name: 'Velmora Serwis sp. z o.o.', nip: '5250002222' }, 'm1', '2026-11-11T09:00:00Z'),
// Pinned to a matter this account does not see.
card('c3', 'UM-2026-0111', 'Najem magazynu', { id: 'k3', name: 'Kalinowy Dwór Sp. z o.o.', nip: null }, 'm-hidden'),
card('c4', 'UM-2026-0112', 'Dzierżawa gruntu', { id: 'k4', name: 'Kalinowy Dwór spółka z ograniczoną odpowiedzialnością', nip: null }, null),
card('c5', 'UM-2026-0113', 'Darowizna', { id: 'k5', name: 'Fundacja Ostoja', nip: null }, null),
card('c6', 'UM-2026-0114', 'Sprzedaż energii', { id: 'k6', name: 'Miedziak Energia sp. z o.o.', nip: '6340005550' }, null)],
'counsel/firms': [
{ id: 'f1', name: 'Hofmann Legal', legal_name: 'Hofmann Legal sp.k.', status: 'active', contact_person: null, notes: '' },
{ id: 'f2', name: 'Lis i Wspólnicy', legal_name: 'Lis i Wspólnicy sp.p.', status: 'active', contact_person: null, notes: '' }],
'counsel/matters': [
order('o1', 'f1', 'ZK/2026/058', 'Opinia do umowy UM-2026-0109', ''),
order('o2', 'f2', 'ZK/2026/059', 'Reprezentacja w sporze', 'Klient: Velmora Pompy sp. z o.o., sprawa 2026/0107'),
order('o3', 'f1', 'ZK/2026/060', 'Analiza ogólna', '')],
'counsel/review-cycles': [],
'galena/drive/home': { workspaces: [{ id: 'pr1', kind: 'project', name: 'Pisma procesowe', path: '/Kancelaria/Pisma procesowe', review_policy: 'required' }] },
'galena/drive/shared': [],
'galena/projects/pr1/tree?recursive=true': [],
'galena/projects/pr1/drafts': [
{ id: 'w1', title: 'Opinia o karach umownych', status: 'pending', author_id: 'u1', created_at: '2026-11-09T10:00:00Z' },
{ id: 'w2', title: 'Projekt pozwu', status: 'pending', author_id: 'u2', created_at: '2026-11-08T10:00:00Z' }],
};
const fetch = async (url) => {
const u = new URL(String(url));
if (u.pathname === '/atrium/api/v1/models/ask') return new Response('data: ' + JSON.stringify({ choices: [{ delta: { content: 'Odpowiedź [1].' } }] }) +
'\n\ndata: [DONE]\n\n', { status: 200, headers: { 'Content-Type': 'text/event-stream' } });
const m = /^\/([^/]+)\/api\/v1\/(.*)$/.exec(u.pathname);
const body = m && WORLD[m[1] + '/' + m[2] + u.search];
return body === undefined ? new Response('{}', { status: 404 }) : new Response(JSON.stringify(body), { status: 200 });
};
// The block's functions by name; `patch` rewrites the block first.
function fns(names, patch = (b) => b) {
const load = new Function('fetch', 'document', 'state', 'chat', '_tr', 'moduleHref', 'coreRefusal', 'Date', 'console',
patch(BLOCK) + `\nreturn { ${names.join(', ')} };`);
const quiet = { ...console, warn: () => {} };
return load(fetch, { baseURI: 'http://t.local/atrium/' }, { user: { id: 'u1' }, launcher: [] }, { ctl: new AbortController() },
(s) => s, (slug, inner) => slug + '/#/' + inner, (p) => p.detail, FixedDate, quiet);
}
// One turn on the default arm (team member's card, asker's card), the filter on or off; `opts` adds chatTurn's switches.
async function turn(question, filtr, patch = (b) => b, opts = {}) {
const f = fns(['chatIndex', 'chatTurn'], patch);
const index = await f.chatIndex();
const a = await f.chatTurn({ model: 'm', question, turns: [], index, graf: 'osoba', ja: true, prawo: false, filtr, ...opts });
const names = (key) => (index.graph.of.get(key) || []).map((id) => index.graph.ent.get(id).name);
return { refs: a.refs.map((r) => r.key), filtr: a.filtr || null, komplet: a.komplet || null, root: a.filtr ? index.graph.ent.get(a.filtr.root).name : null,
owners: Object.fromEntries(a.refs.map((r) => [r.key, names(r.key)])) };
}
const both = async (q, patch) => ({ on: await turn(q, true, patch), off: await turn(q, false, patch) });
"""
def _run(js: str) -> object:
script = f"const APP = {json.dumps(str(APP))};\n" + _PRELUDE + \
f"\n(async () => {{ const out = await (async () => {{ {js} }})(); console.log(JSON.stringify(out)); }})()" \
".catch((e) => { console.error(e && e.stack || e); process.exit(1); });"
r = subprocess.run([NODE, "-"], input=script, capture_output=True, text=True, timeout=120, encoding="utf-8")
assert r.returncode == 0, r.stderr
return json.loads(r.stdout)
def test_one_firm_named_in_full_keeps_only_its_own_records() -> None:
# Velmora Serwis: its party and its contract stay; Velmora Pompy's party and matter, another firm's order,
# the activity list and the 30/60/90-day windows that search brought on the shared words drop.
got = _run("return both('Jakie umowy ma Velmora Serwis sp. z o.o.?');")
on, off = got["on"], got["off"]
assert on["root"] == "Velmora Serwis sp. z o.o."
assert on["refs"] == ["sygna:strona:s4", "galena:umowa:c2"]
assert {"sygna:strona:s3", "sygna:sprawa:m1", "atrium:aktywnosc", "galena:wygasajace:30"} <= set(off["refs"])
assert set(on["filtr"]["kept"]) | set(on["filtr"]["cut"]) == set(off["refs"])
assert off["filtr"] is None # off by default: chatTurn without the flag is the turn of today
def test_a_named_record_of_another_firm_stays() -> None:
# UM-2026-0109 is Miedziak Energia's: named in the question, it stays first; the filter cuts only what search found.
got = _run("return both('Czy umowa UM-2026-0109 dotyczy Velmora Serwis sp. z o.o.?');")
assert got["on"]["root"] == "Velmora Serwis sp. z o.o."
assert got["on"]["refs"][0] == "galena:umowa:c1" and got["off"]["refs"][0] == "galena:umowa:c1"
assert "sygna:strona:s3" in got["off"]["refs"] and "sygna:strona:s3" not in got["on"]["refs"]
@pytest.mark.parametrize("question", [
"Co mamy z Velmora?", # ambiguous: two Velmoras
"Porównaj umowy Velmora Serwis sp. z o.o. i Fundacja Ostoja", # two entities
"Jakie umowy ma Ostoja?", # one word of the name only
"Co mam na głowie?", # the asker's own card cuts already
"Co prowadzi Piotr Zając?", # a team member's card cuts already
])
def test_no_filter_where_the_spec_leaves_the_turn_as_it_was(question: str) -> None:
got = _run(f"return both({json.dumps(question)});")
assert got["on"]["filtr"] is None
assert got["on"]["refs"] == got["off"]["refs"]
def test_an_entity_with_none_of_its_records_found_is_never_left_with_an_empty_list() -> None:
got = _run("return both('Jakie umowy ma Velmora Serwis sp. z o.o.?', "
"(b) => b.replace('e.recs.has(r.key)', 'false'));")
assert got["on"]["filtr"] is None
assert got["on"]["refs"] == got["off"]["refs"] and got["on"]["refs"]
def test_a_fault_in_the_filter_leaves_the_turn_as_it_was() -> None:
got = _run("return both('Jakie umowy ma Velmora Serwis sp. z o.o.?', "
"(b) => b.replace('const cuts = e && e.type', 'const cuts = e.nope.x && e.type'));")
assert got["on"]["filtr"] is None and got["on"]["refs"] == got["off"]["refs"]
+116
View File
@@ -0,0 +1,116 @@
"""Home chat's komplet of the entity asked about (spec lw-platform/specs/2026-11-28-czat-komplet-podmiotu.md, `chat.komplet`).
With the filter, small models stopped borrowing another firm's record and said "not found" instead: the right record
was in the map but not among the twelve search hits. Under komplet the map's records for the named party, the asker
or up to three parties join the sources first (limit 20), a record named by number brings its matter, client,
deadlines and orders, names are read in their cases, and Sygna gets a matters-by-status summary.
Reuses the world and harness of `test_chat_filter_console.py`. DB-free and network-free; skipped where no `node`.
"""
from __future__ import annotations
import json
import pytest
from test_chat_filter_console import NODE, _run
pytestmark = pytest.mark.skipif(NODE is None, reason="needs node on PATH")
K = "undefined, { komplet: true }"
def _pair(question: str, setup: str = "") -> dict:
q = json.dumps(question)
return _run(f"{setup}\nreturn {{ on: await turn({q}, true, {K}), off: await turn({q}, true) }};")
@pytest.mark.parametrize(("asked", "name", "same"), [
("logistyce", "logistyka", True), # k → c
("velmorze", "velmora", True), # r → rz
("ostoi", "ostoja", True), # j → i
("sowinca", "sowiniec", True), # -iec → -ńca (words arrive folded, chatFold)
("sowincem", "sowiniec", True),
("pradze", "praga", True), # g → dz
("kodax", "kodar", False), # a prefix is not a case: the reason it is a list
("velmorek", "velmora", False),
("ostrowie", "ostoja", False),
])
def test_case_alternations_are_a_closed_list_read_only_when_wide(asked: str, name: str, same: bool) -> None:
got = _run(f"const {{ chatSameWord }} = fns(['chatSameWord']);"
f"return [chatSameWord({json.dumps(asked)}, {json.dumps(name)}, true),"
f" chatSameWord({json.dumps(asked)}, {json.dumps(name)})];")
assert got == [same, False] # without komplet (`wide`) the reading of names is today's
def test_a_firm_in_another_case_gets_its_records_and_an_unknown_name_none() -> None:
got = _pair("Co mamy o Ostoi?")
assert got["off"]["refs"] == []
assert got["on"]["refs"] == ["sygna:strona:s5", "galena:umowa:c5"]
assert _pair("Co mamy o Ostrowie?")["on"]["refs"] == []
def test_the_entity_s_records_come_first_and_the_limit_is_twenty() -> None:
many = ("WORLD['galena/cards?limit=200&offset=0'].push(...Array.from({ length: 25 }, (_, i) => card('x' + i, "
"'UM-2026-02' + String(i).padStart(2, '0'), 'Umowa najmu ' + i, { id: 'kx', name: 'Fundacja Zielony Las', nip: null }, null)));")
got = _pair("Jakie umowy ma Fundacja Zielony Las?", many)
on = got["on"]["refs"]
assert len(on) == 20 and len(got["off"]["refs"]) <= 12
assert on[0] == "sygna:strona:s6" and all(k.startswith("galena:umowa:x") for k in on[1:])
def test_the_namesake_firm_and_its_matter_stay_under_komplet_only() -> None:
# Miedziak S.A. asked: the sp. z o.o.'s contract and matter mention "Miedziak" and stay, for "that one is the other firm's".
got = _pair("Jakie umowy ma Miedziak Energia S.A.?")
assert got["on"]["root"] == got["off"]["root"] == "Miedziak Energia S.A."
assert {"sygna:strona:s2", "galena:umowa:c6", "sygna:sprawa:m2"} <= set(got["on"]["refs"])
assert "galena:umowa:c6" not in got["off"]["refs"]
def test_a_matter_named_by_number_is_not_filtered() -> None:
got = _pair("Jaka umowa jest przypięta do sprawy 2026/0109?")
assert got["off"]["filtr"] is not None and got["on"]["filtr"] is None
assert got["on"]["refs"][:3] == ["sygna:sprawa:m2", "sygna:termin:d2", "sygna:strona:s2"]
def test_two_parties_get_both_komplets_and_no_filter() -> None:
got = _pair("Kto ma więcej umów, Kalinowy Dwór czy Velmora Pompy?")
on = got["on"]["refs"]
assert got["on"]["filtr"] is None
assert {"sygna:strona:s3", "sygna:strona:s7", "sygna:sprawa:m1", "galena:umowa:c3", "galena:umowa:c4",
"sygna:termin:d1", "counsel:zlecenie:o2"} <= set(on[:8])
assert "counsel:zlecenie:o2" not in got["off"]["refs"]
def test_the_asker_s_records_join_on_a_question_about_mine() -> None:
got = _pair("Jakie terminy są w moich sprawach?")
assert got["on"]["refs"][:3] == ["sygna:termin:d1", "sygna:sprawa:m1", "galena:wersja:w1"]
assert "galena:wersja:w1" not in got["off"]["refs"]
@pytest.mark.parametrize(("question", "first"), [
# A contract by number → its matter, the matter's client and deadline.
("Kto prowadzi sprawę z umowy UM-2026-0110?", ["galena:umowa:c2", "sygna:sprawa:m1", "sygna:strona:s3", "sygna:termin:d1"]),
# An order by number → its firm, and the matter its note names.
("Która kancelaria realizuje ZK/2026/059?", ["counsel:zlecenie:o2", "counsel:kancelaria:f2", "sygna:sprawa:m1"]),
# A contract by number → the orders that name it, with their firm.
("Czy przy UM-2026-0109 korzystaliśmy z kancelarii zewnętrznej?", ["galena:umowa:c1", "counsel:zlecenie:o1", "counsel:kancelaria:f1"]),
])
def test_a_record_named_by_number_brings_one_step_of_the_map(question: str, first: list[str]) -> None:
got = _pair(question)
assert got["on"]["refs"][: len(first)] == first
assert got["off"]["refs"][: len(first)] != first
def test_the_matters_by_status_summary_exists_under_komplet_only() -> None:
got = _pair("Ile spraw mamy otwartych, a ile zamkniętych?")
assert got["on"]["refs"][0] == "sygna:sprawy"
assert "sygna:sprawy" not in got["off"]["refs"]
def test_off_by_default_and_a_fault_leaves_the_turn_as_it_was() -> None:
q = json.dumps("Kto prowadzi sprawę z umowy UM-2026-0110?")
got = _run(f"return {{ def: await turn({q}, true), off: await turn({q}, true, undefined, {{ komplet: false }}),"
f" bad: await turn({q}, true, (b) => b.replace('const ext = chatKomplet(', 'const ext = nope.x('), {{ komplet: true }}) }};")
assert got["def"] == got["off"] and got["def"]["komplet"] is None
assert got["bad"]["komplet"] is None and got["bad"]["refs"]
+1 -1
View File
@@ -359,7 +359,7 @@ 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": {
+1 -1
View File
@@ -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
+18 -6
View File
@@ -527,7 +527,9 @@ services:
profiles: ["arbiter"]
build:
context: ${MODULES_DIR:-./modules}/arbiter/apps/arbiter/backend
# No console (Atrium#53): the chat is its only screen, so no `frontend` context.
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
additional_contexts:
frontend: ${MODULES_DIR:-./modules}/arbiter/apps/arbiter/frontend
secrets: [dredd_core_token]
image: dredd-family/arbiter-backend:local
# `required: false` for Insider's reason: a missing env_file breaks the whole PROJECT, and the
@@ -554,7 +556,9 @@ services:
profiles: ["arbiter"]
build:
context: ${MODULES_DIR:-./modules}/arbiter/apps/arbiter/backend
# No console (Atrium#53): the chat is its only screen, so no `frontend` context.
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
additional_contexts:
frontend: ${MODULES_DIR:-./modules}/arbiter/apps/arbiter/frontend
secrets: [dredd_core_token]
image: dredd-family/arbiter-backend:local
env_file:
@@ -602,7 +606,9 @@ services:
profiles: ["lexicon"]
build:
context: ${MODULES_DIR:-./modules}/lexicon/backend
# No console (Lexicon b2c998e, Atrium#53): the chat is its only screen, so no `frontend` context.
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
additional_contexts:
frontend: ${MODULES_DIR:-./modules}/lexicon/frontend
secrets: [dredd_core_token]
image: dredd-family/lexicon-backend:local
# `required: false` for Insider's reason: a missing env_file breaks the whole PROJECT, and the
@@ -629,7 +635,9 @@ services:
profiles: ["lexicon"]
build:
context: ${MODULES_DIR:-./modules}/lexicon/backend
# No console (Lexicon b2c998e, Atrium#53): the chat is its only screen, so no `frontend` context.
# The module's console ships in its image (its Dockerfile: COPY --from=frontend).
additional_contexts:
frontend: ${MODULES_DIR:-./modules}/lexicon/frontend
secrets: [dredd_core_token]
image: dredd-family/lexicon-backend:local
env_file:
@@ -821,7 +829,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 +857,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:
+2 -4
View File
@@ -493,11 +493,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
-6
View File
@@ -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():
+3 -5
View File
@@ -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.
#
@@ -246,8 +246,7 @@ else
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/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"
@@ -262,8 +261,7 @@ else
"$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/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"
+11 -11
View File
@@ -352,18 +352,18 @@ STRIP=${STRIP# } FAMILY_ROLES=${FAMILY_ROLES# }
module_repo() {
case $1 in
atrium) printf 'http://77.216.148.202:3000/Haski/Atrium' ;;
galena) printf 'http://77.216.148.202:3000/Haski/Galena' ;;
sygna) printf 'http://77.216.148.202:3000/Haski/Sygna' ;;
counsel) printf 'http://77.216.148.202:3000/Haski/CounselScorecard' ;;
insider) printf 'http://77.216.148.202:3000/Haski/Insider' ;;
atrium) printf 'https://github.com/Alpaq92/Atrium' ;;
galena) printf 'https://github.com/Alpaq92/Galena' ;;
sygna) printf 'https://github.com/Alpaq92/Sygna' ;;
counsel) printf 'https://github.com/Alpaq92/CounselScorecard' ;;
insider) printf 'https://github.com/Alpaq92/Insider' ;;
# Arbiter's repository also carries the analysis engine (packages/*): the app is apps/arbiter in it.
arbiter) printf 'http://77.216.148.202:3000/Haski/Arbiter' ;;
lexicon) printf 'http://77.216.148.202:3000/Haski/Lexicon' ;;
agora) printf 'http://77.216.148.202:3000/Haski/Agora' ;;
parafa) printf 'http://77.216.148.202:3000/Haski/Parafa' ;;
scribe) printf 'http://77.216.148.202:3000/Haski/Scribe' ;;
workflow) printf 'http://77.216.148.202:3000/Haski/Workflow' ;;
arbiter) printf 'https://github.com/Alpaq92/Arbiter' ;;
lexicon) printf 'https://github.com/Alpaq92/Lexicon' ;;
agora) printf 'https://github.com/Alpaq92/Agora' ;;
parafa) printf 'https://github.com/Alpaq92/Parafa' ;;
scribe) printf 'https://github.com/Alpaq92/Scribe' ;;
workflow) printf 'https://github.com/Alpaq92/Workflow' ;;
esac
}
+1 -1
View File
@@ -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
View File
@@ -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
-224
View File
@@ -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.
-197
View File
@@ -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.
+139 -14
View File
@@ -2190,6 +2190,14 @@ async function chatSygna(today, names, contracts = []) {
`status ${chatStatus('sprawa', m.status)}, ${chatWho(names, m.responsible_lawyer_id, 'prowadzi', 'osoba prowadząca nie wpisana')}, otwarta ${m.opened_at}. ${m.description || ''}`,
'sygna:sprawa:' + m.id, [m.reference, m.name]),
at: m.closed_at || m.opened_at, did: m.closed_at ? 'zamknięta' : 'otwarta', matter: m }));
// Like the register's totals, for matters: "ile spraw otwartych, a ile zamkniętych" got "nie znalazłem" from Qwen
// 3 of 3 (zestaw 11). Search offers it only under chat.komplet (chatTurn), so the other arms read as before.
if (matters.length) {
const by = [...new Set(matters.map((m) => m.status))].sort().map((st) => { const ms = matters.filter((m) => m.status === st);
return `status ${chatStatus('sprawa', st)}: ${ms.length} (${ms.map((m) => m.reference).join(', ')})`; });
out.push(rec('zestawienie', 'Zestawienie spraw wg statusu (ile otwartych, ile zamkniętych)', 'matters',
`Sprawy widoczne na koncie pytającego, stan na ${today}, razem ${matters.length}; ${by.join('; ')}.`, 'sygna:sprawy', null, out.map((r) => r.key)));
}
// days=365: Sygna's default window is 14 days, and a deadline 20 days out did not exist for the chat
// ("nie znalazłem", czat-v3 termin-07-data, 2026-11-03). Overdue ones come back whatever the window.
const deadlines = (await askerGet('sygna', 'deadlines?days=365')) || [];
@@ -2873,13 +2881,21 @@ const CHAT_KIND_MOD = { umowa: 'galena', sprawa: 'sygna', termin: 'sygna', stron
// Another case of the same word: a closed list of Polish endings, never a prefix. A prefix rule made "Kodax"
// (a firm we do not have) the existing Kodar; an ending list misses an odd form, which only means today's answer.
const CHAT_ENDINGS = ['a', 'e', 'i', 'o', 'u', 'y', 'em', 'om', 'ie', 'owi', 'ach', 'ami', 'ow', 'iej', 'ej', 'ego', 'emu', 'ym', 'im', 'mi'];
function chatSameWord(q, n) {
// `wide` (chat.komplet only): the consonant alternations at a name's end too, also a closed list. Without them
// "Ortolan Logistyce", "Velmorze Pompy", "Ostoi" and "Sowińca" named no firm (battery, 28.11), so the filter
// and the entity's records never came. Folded text: Sowiniec → sowinc|a, Dębowiec → debowc|a.
const CHAT_ALTERNATIONS = [[/ka$/, 'c', ['e']], [/ga$/, 'dz', ['e']], [/ra$/, 'rz', ['e']], [/ja$/, '', ['i']], [/iec$/, 'c', CHAT_ENDINGS]];
function chatSameWord(q, n, wide = false) {
if (q === n) return true;
if (q.length < 4 || n.length < 4 || /\d/.test(n)) return false;
const stems = [n];
if (/[aeiouy]$/.test(n)) stems.push(n.slice(0, -1)); // zielona → zielon|ej, energia → energi|i
if (/e[kc]$/.test(n)) stems.push(n.slice(0, -2) + n.slice(-1)); // kaczmarek → kaczmark|a (movable e)
return stems.some((s) => q.startsWith(s) && CHAT_ENDINGS.includes(q.slice(s.length)));
if (stems.some((s) => q.startsWith(s) && CHAT_ENDINGS.includes(q.slice(s.length)))) return true;
return wide && CHAT_ALTERNATIONS.some(([re, to, ends]) => {
const s = n.replace(re, to);
return s !== n && q.startsWith(s) && ends.includes(q.slice(s.length));
});
}
// A three-letter first name inflects too ("Ewy Sadowskiej", "Jana Nowaka"), which chatSameWord refuses for a lone
// short word. Used only for the first word of a person's full name, so the surname still has to match beside it.
@@ -3218,13 +3234,18 @@ function chatGraph(records, names, today) {
put({ toks: words(core), ent: e.id, form: chatFormPart(mk) || null, full: true, person: e.person });
}
}
if (e.person || !on('czesciowe')) continue;
const own = [...cores].flatMap(words);
// "o pani Zawilskiej": a client's surname alone, read only under chat.komplet (`wide`). Two clients of one
// surname both claim the span, so the question comes back, as for any ambiguous name.
if (e.person) for (const core of cores) { const w = words(core).pop(); if (w && w.length >= 5) put({ toks: [w], ent: e.id, full: false, own, surname: true }); }
if (e.person || !on('czesciowe')) continue;
for (const core of cores) {
// Only the first word, the one that tells the firm apart (Velmora, Ortolan). A later one is mostly a common
// word as well ("Development", "Systems", "Pompy", "Energii"): it gave a law question a firm's card.
const [w, ...more] = words(core);
if (w.length >= 5 && !/\d/.test(w) && !generic.test(w) && !first.has(w)) put({ toks: [w], ent: e.id, full: false, own });
// "Fundacja Ostoja" → "o Ostoi": a generic first word leaves the second to tell the firm apart (chat.komplet only).
if ((generic.test(w) || CHAT_ORG_WORDS.test(w)) && more.length && more[0].length >= 5 && !/\d/.test(more[0])) put({ toks: [more[0]], ent: e.id, full: false, own, surname: true });
// "Velmorze Pompy": the whole name with its first word in a case the ending list does not know.
if (more.length && w.length >= 6 && !/\d/.test(w)) put({ toks: [w, ...more], ent: e.id, full: false, loose: true, own });
}
@@ -3248,7 +3269,9 @@ function chatGraph(records, names, today) {
// Where the dictionary's entries stand in a text: [{a, b, ents, hit}] over its words. Longest entry first and no
// overlaps, as chatNamed; entries of the same words at the same place all count (a core two firms share).
function chatLexSpans(text, entries, graph, { partial = true } = {}) {
// `wide`: chat.komplet's reading (consonant alternations, a client's surname alone, "SA" for S.A.); off, as before.
const CHAT_FORM_ASKED = { sa: 's a' };
function chatLexSpans(text, entries, graph, { partial = true, wide = false } = {}) {
const src = String(text);
const toks = [...src.matchAll(/[\p{L}\p{N}]+/gu)].map((m, i) => ({ t: chatFold(m[0]), s: m.index, e: m.index + m[0].length,
cap: /^\p{Lu}/u.test(m[0]), lead: i === 0 || /[.!?]\s*$/.test(src.slice(0, m.index)) }));
@@ -3268,7 +3291,8 @@ function chatLexSpans(text, entries, graph, { partial = true } = {}) {
}
const formAt = (i) => {
for (let n = 5; n >= 1; n--) {
const f = i + n <= toks.length && CHAT_FORM_OF.get(toks.slice(i, i + n).map((t) => t.t).join(' '));
const k = i + n <= toks.length && toks.slice(i, i + n).map((t) => t.t).join(' ');
const f = k && (CHAT_FORM_OF.get(k) || (wide && CHAT_FORM_ASKED[k]));
if (f) return { f, n };
}
return null;
@@ -3281,18 +3305,18 @@ function chatLexSpans(text, entries, graph, { partial = true } = {}) {
if (!q) return false;
if (x.exact) return q.t === w;
// A single word of a firm's name counts only written as a name: capitalised and not opening a sentence.
return (chatSameWord(q.t, w) || (x.person && k === 0 && x.toks.length > 1 && chatSameFirst(q.t, w)) || (x.loose && k === 0 && near(q.t, w)))
return (chatSameWord(q.t, w, wide) || (x.person && k === 0 && x.toks.length > 1 && chatSameFirst(q.t, w)) || (x.loose && k === 0 && near(q.t, w)))
&& (x.full || (q.cap && !q.lead));
});
// A capitalised word right beside a partial hit that is not of this firm's name makes another name of it:
// "Ortolan Cargo", "Kalinowe Wzgórze", "Fundacja Przystań", "w Zielonej Górze" are not our firms.
const foreign = (x, j) => { const q = toks[j]; return !!q && q.cap && !q.lead && !x.own.some((w) => chatSameWord(q.t, w) || near(q.t, w)); };
const foreign = (x, j) => { const q = toks[j]; return !!q && q.cap && !q.lead && !x.own.some((w) => chatSameWord(q.t, w, wide) || near(q.t, w)); };
const fullEnts = new Set();
for (const full of [true, false]) {
if (!full && !partial) break;
if (!full) for (const s of spans) for (const id of s.ents) fullEnts.add(id);
for (const x of entries) {
if (x.ref || x.full !== full) continue;
if (x.ref || x.full !== full || (x.surname && !wide)) continue;
for (let i = 0; i + x.toks.length <= toks.length; i++) {
if (!fits(x, i)) continue;
// A full hit wins over partial ones of the same firm; a partial hit of another firm elsewhere still
@@ -3305,7 +3329,7 @@ function chatLexSpans(text, entries, graph, { partial = true } = {}) {
if (x.form ? x.form !== f.f : graph.ent.get(x.ent).forms.size) continue;
b += f.n;
}
claim(i, b, x.ent, full ? 'pelne' : 'czesciowe');
claim(i, b, x.ent, full ? 'pelne' : x.surname ? 'nazwisko' : 'czesciowe');
}
}
}
@@ -3314,10 +3338,10 @@ function chatLexSpans(text, entries, graph, { partial = true } = {}) {
// The entity a question names, read by the names in the data, never by words for kinds of questions.
// {root, hit} | {ambiguous: [entId]} | {root: null, why: 'dwie encje'} | null.
function chatGraphFind(question, index) {
function chatGraphFind(question, index, { wide = false } = {}) {
const g = index.graph;
if (!g) return null;
const spans = chatLexSpans(question, g.lex, g);
const spans = chatLexSpans(question, g.lex, g, { wide });
if (!spans.length) return null;
// A matter and its own client named together: the matter, the narrower one.
const all = new Set(spans.flatMap((s) => [...s.ents]));
@@ -3330,6 +3354,66 @@ function chatGraphFind(question, index) {
const hit = live.some((s) => s.hit !== 'czesciowe') ? live.find((s) => s.hit !== 'czesciowe').hit : 'czesciowe';
return ids.length > 1 ? { ambiguous: ids, hit } : { root: ids[0], hit };
}
// chat.komplet (spec lw-platform/specs/2026-11-28-czat-komplet-podmiotu.md): the map's own records of what the
// question names, whatever words their titles have. In 29 of the 30 battery turns that lacked a record the answer
// needed, the map tied it to the firm, person or matter asked about, and word search gave the 12 slots to records
// sharing words with the question (28.11). Entities named in full (1-3), else the asker in the first person; plus one
// step from a record named by its number: its matter with the matter's deadlines, an order's firm and contract.
const CHAT_KOMPLET_TOP = 20;
// The word that tells a party apart: a person's surname, a firm's first word unless it says only what kind of
// body it is ("Fundacja Ostoja"). Under komplet the filter keeps found records that mention it: the namesake
// firm (Miedziak S.A. vs sp. z o.o.), the matter where it is the other side, the order whose note names the client.
function chatMark(e) {
const ws = (chatCoreKey(chatMatchKey(e.name)) || '').split(' ').filter(Boolean);
const w = e.person ? ws[ws.length - 1] : (CHAT_PARTY_GENERIC.test(ws[0] || '') || CHAT_ORG_WORDS.test(ws[0] || '')) ? ws[1] : ws[0];
return w && w.length >= 4 && !/\d/.test(w) ? w : null;
}
const chatMentions = (r, w) => chatMatchKey(`${r.title} ${r.text || ''}`).split(' ').some((t) => chatSameWord(t, w, true));
// Words that open an organisation's name and say nothing about which one ("Fundacja Ostoja"), and the plural cases
// CHAT_SELF misses ("moich wersji": the asker's card never came in the battery either).
const CHAT_ORG_WORDS = /^(?:fundacj|stowarzysz|spoldziel|instytut|centrum|kancelari|gmin|parafi|zwiazek|izb)/u;
const CHAT_SELF_PL = /(?<!\p{L})(?:moich|moim|moimi)(?!\p{L})/iu;
const CHAT_KOMPLET_KINDS = ['strona', 'sprawa', 'termin', 'umowa', 'projekt', 'wersja', 'zlecenie', 'kancelaria'];
function chatKomplet(question, index, named = []) {
const g = index.graph;
if (!g) return [];
// A partial name counts here when it names one entity ("dla Sowińca"): this only adds records, the filter that
// cuts others' records still wants the full name.
// One name on several entities of one name (a client known to Sygna and by name elsewhere) is still one party.
const spans = chatLexSpans(question, g.lex, g, { wide: true }).filter((s) => new Set([...s.ents].map((id) => g.ent.get(id).name)).size === 1);
let ids = [...new Set(spans.flatMap((s) => [...s.ents]))];
// A matter and its own client named together: the matter, as chatGraphFind.
ids = ids.filter((id) => !ids.some((m) => g.ent.get(m).type === 'sprawa' && g.ent.get(m).client === id));
if (ids.length > 3) ids = [];
if (!ids.length && !named.length && (CHAT_SELF.test(question) || CHAT_SELF_PL.test(question)) && g.ent.has('osoba:' + index.user)) ids = ['osoba:' + index.user];
const rank = (k) => { const i = CHAT_KOMPLET_KINDS.indexOf(k.split(':')[1]); return i < 0 ? CHAT_KOMPLET_KINDS.length : i; };
const keys = new Set();
const take = (e) => { if (e.rec) keys.add(e.rec); for (const k of [...e.recs.keys()].sort((a, b) => rank(a) - rank(b))) keys.add(k); };
const matterOf = (k) => g.ent.get('sprawa:' + k.split(':').pop());
for (const id of ids) {
const e = g.ent.get(id);
take(e);
// A person's documents hang on their matters, not on them: one step through each matter they hold.
if (e.type === 'osoba') for (const k of [...e.recs.keys()]) if (k.startsWith('sygna:sprawa:') && matterOf(k))
for (const p of matterOf(k).recs.keys()) if (p.startsWith('galena:projekt:')) keys.add(p);
}
const firmOf = (k) => { const o = (index.byKey.get(k) || {}).order; if (o && o.firm_id) keys.add('counsel:kancelaria:' + o.firm_id); };
for (const r of named) {
for (const id of g.of.get(r.key) || []) if (id.startsWith('sprawa:')) {
const m = g.ent.get(id);
if (m.rec) keys.add(m.rec);
if (m.client && g.ent.get(m.client).rec) keys.add(g.ent.get(m.client).rec);
for (const k of m.recs.keys()) if (k.startsWith('sygna:termin:')) keys.add(k);
}
if (g.contractMatter.has(r.key)) keys.add(g.contractMatter.get(r.key));
if (g.orderTarget.has(r.key)) keys.add(g.orderTarget.get(r.key).to);
firmOf(r.key);
// A contract named by number: the orders that name it, with their firms ("UM-2026-0114: korzystaliśmy z kogoś?").
for (const [o, t] of g.orderTarget) if (t.to === r.key) { keys.add(o); firmOf(o); }
}
return [...keys].map((k) => index.byKey.get(k)).filter(Boolean);
}
// Whether a text (a record's title) names the entity in full: the found records that stay beside a card.
const chatGraphNames = (text, ent, graph) => chatLexSpans(text, ent.lex, graph, { partial: false }).length > 0;
@@ -4422,7 +4506,13 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
prawo = chat.prawo ?? true,
// istnienie: a code source saying a capitalised name of the question matches no visible record (audit P9, 13.11);
// the condition for a milder rule 3, not yet measured on the models, so off by default.
istnienie = chat.istnienie ?? false }) {
istnienie = chat.istnienie ?? false,
// filtr: a question naming one outside entity in full keeps only that entity's own found records (spec
// lw-platform/specs/2026-11-28-czat-filtr-podmiotu.md); not yet measured on the models, so off by default.
filtr = chat.filtr ?? false,
// komplet: the named entity's records from the map, beyond what search found, with the filter's reading of names
// widened (spec lw-platform/specs/2026-11-28-czat-komplet-podmiotu.md); not yet measured, so off by default.
komplet = chat.komplet ?? false }) {
const done = (content, extra = {}) => Object.assign(answer, { content, status: '', ...extra });
const en = chatIsEn(question);
try {
@@ -4545,7 +4635,8 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
answer.prawo = lawGraph.near.map((r) => r.key);
}
// A question about the law gets no firm records: a dozen contracts beside three articles are noise.
let found = topic.length ? [] : chatSearch(index.records, question + (ana.demonstrative && prevQ ? ' ' + prevQ : ''));
let found = topic.length ? [] : chatSearch(komplet ? index.records : index.records.filter((r) => r.key !== 'sygna:sprawy'),
question + (ana.demonstrative && prevQ ? ' ' + prevQ : ''));
// "z nich": the rest of the slots stay with that kind and the totals, not with whatever shares a word.
if (back.length) found = found.filter((r) => r.kind === back[0].kind || r.kind === 'zestawienie');
// The card replaces what search found around the name: the activity list, the firm's whole deadline summary
@@ -4557,6 +4648,40 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
const top = found.top;
found = Object.assign(found.filter((r) => card.members.has(r.key) || card.names(r) || (gt.ja && /^galena:(?:umowa|zestawienie|wygasajace|ranking)/.test(r.key))), { top });
}
// Signed with their owner, the small models still gave another firm's contract to the one asked about
// (testy/czat-graf/wyniki/podmioty, 27-28.11). A record that is not in the sources cannot be given to anybody.
// Only one entity named in full, only the records the map ties to it by any edge (rank 0 alone cut Ortolan's and
// Kalinowy Dwór's own contracts, tied by name only), never to an empty list; named and resolved records stay.
if (filtr && !card && !back.length && route === 'data' && found.length) {
try {
const f = index.graph && chatGraphFind(question, index, { wide: komplet });
const e = f && f.root && f.hit !== 'czesciowe' && index.graph.ent.get(f.root);
// Under komplet a matter named by number cuts nothing: what its question needs often hangs on another one.
const cuts = e && e.type !== 'osoba' && !(komplet && e.type === 'sprawa');
const mark = komplet && cuts && e.type === 'podmiot' && chatMark(e);
const own = cuts ? found.filter((r) => e.recs.has(r.key) || (mark && chatMentions(r, mark))) : [];
// Under komplet the entity's own records come from the map below, so an empty find no longer keeps the rest.
if (own.length || (komplet && cuts && e.recs.size)) {
answer.filtr = { root: e.id, kept: own.map((r) => r.key), cut: found.filter((r) => !own.includes(r)).map((r) => r.key) };
found = Object.assign(own, { top: found.top });
}
} catch (ex) { console.warn('chat filter off:', ex); }
}
// The map's records first, then what else search found; the limit grows to CHAT_KOMPLET_TOP on this path only.
let more = 0;
if (komplet && !back.length && route === 'data' && !topic.length) {
try {
const ext = chatKomplet(question, index, [...named, ...resolved]);
const mine = new Set(ext.map((r) => r.key));
const add = ext.filter((r) => !found.some((x) => x.key === r.key));
// Also when search found them all: ranked low, they fell past the limit (UM-2026-0109's matter, 28.11).
if (ext.length) {
answer.komplet = add.map((r) => r.key);
found = Object.assign([...found.filter((r) => mine.has(r.key)), ...add, ...found.filter((r) => !mine.has(r.key))], { top: found.top });
more = CHAT_KOMPLET_TOP - CHAT_TOP;
}
} catch (ex) { console.warn('chat komplet off:', ex); }
}
const seen = new Set();
const pick = law.length || topic.length || named.length || resolved.length || back.length || card ? null : chatPick(question, index);
if (pick && !pick.table.rows.length) return done(pick.empty, { coded: 'pick', refs: [], verify: [] });
@@ -4575,7 +4700,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 + more + law.length + topic.length + lawGraph.near.length + clauses.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 });