fix(home, chat): trends read once and recent only; review panel backs off; clause text cached

The trends route reads the log's status once and has no days parameter; milestones filter on
created_at in SQL. The console starts the trends fetch beside the stats. The chat keeps a
contract's text per conversation; the review panel's polling doubles to 30 s and stops after
20 minutes, and a late answer for a closed panel touches nothing. Ticket narration removed from
comments; behaviour tests replace source greps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 14:45:22 +01:00
co-authored by Claude Opus 5.5
parent b17d17e0f8
commit 77b8370675
21 changed files with 310 additions and 133 deletions
@@ -1,4 +1,4 @@
"""Arbiter becomes a service module (Atrium#53, stage 2), as Galena did in `0016`.
"""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
@@ -1,4 +1,4 @@
"""Panorama folds into Atrium's home (Atrium#53, stage 3): it leaves the menu and the catalogue.
"""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
+1 -1
View File
@@ -126,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, Atrium#53; kept for a module that reports on the log). Same rules: only
# (none since Panorama left the platform; kept for a module that reports on the log). 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 = ""
+1 -1
View File
@@ -59,7 +59,7 @@ class Module(UUIDPkMixin, TimestampMixin, Base):
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 (issue Atrium#53: on everywhere, not in the menu): other modules open its screens by link.
# 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"))
+4 -6
View File
@@ -31,13 +31,11 @@ def home_stats(db: Session = Depends(get_db),
@router.get("/home/trends")
def home_trends(days: int = Query(30, ge=1, le=366), db: Session = Depends(get_db),
def home_trends(db: Session = Depends(get_db),
user: AppUser = Depends(require_administrator)) -> dict:
"""Trends from the event log (moved from Panorama): events per day and kind, and how long
documents took from their first version to approval and to signature. Platform-wide sums, so
platform administrators only."""
return {"activity": trends.activity(db, days=days),
"durations": trends.durations(db, trends.SEGMENTS)}
"""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")
+3 -3
View File
@@ -35,7 +35,7 @@ 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 (Atrium#53):
# 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",
@@ -66,7 +66,7 @@ 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 (Atrium#53): other modules open its screens by link.
# 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.",
@@ -119,7 +119,7 @@ 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 (Atrium#53, stage 2): contracts are checked from the chat, and its screens open
# A service too: contracts are checked from the chat, and its screens open
# by link (the report panel, a contract card's "Otwórz analizę"). Standalone it keeps its menu.
"in_menu": False,
"category": "Umowy",
+56 -69
View File
@@ -1,6 +1,5 @@
"""History and trends on the home page: aggregates over the platform's event log (`module_event`).
Moved here from Panorama (Atrium#53, stage 3: Panorama folds into Atrium's home and is retired).
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
@@ -25,10 +24,10 @@ from sqlalchemy import DateTime, Text, column, func, literal_column, select, tab
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Session as DbSession
#: The platform's working day (Compass's `clock.ZONE`): a day on a chart is a day in Poland.
#: The platform's working day: a day on a chart is a day in Poland.
ZONE = "Europe/Warsaw"
#: The longest history a chart asks for.
MAX_DAYS = 366
#: 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
@@ -51,17 +50,15 @@ KIND_LABELS: dict[str, str] = {
}
#: The milestones a document passes, each the FIRST event of its kind naming that document
#: (`payload.document_id`), in order. Compass measured four stages from its own tables; three of its
#: five milestones exist as events today, so two stages remain. A new event kind adds a milestone
#: here, not a table.
#: (`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"),
)
#: A stage runs from one milestone to the next.
#: 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 (Compass W7).
#: The distribution's bands in days, both ends included; `None` = no upper end.
BANDS = ((0, 7), (8, 30), (31, 90), (91, None))
@@ -85,20 +82,14 @@ def _day(column_):
return func.date(func.timezone(literal_column(f"'{ZONE}'"), column_))
def activity(db: DbSession, *, days: int = 30, today: dt.date | None = None) -> dict[str, Any]:
"""Events per day and kind over the last `days` days (today included, the oldest first), every
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."""
days = max(1, min(int(days), MAX_DAYS))
status = log_status(db)
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)
day = _day(_EVENT.c.created_at)
rows = db.execute(
select(day.label("day"), _EVENT.c.kind, func.count().label("n"))
.where(day >= first, day <= today)
.group_by(day, _EVENT.c.kind)).all()
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:
@@ -108,81 +99,77 @@ def activity(db: DbSession, *, days: int = 30, today: dt.date | None = None) ->
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)],
"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()),
}
# ── durations (Compass `dashboard.durations`, W5-W7, rebuilt on events) ───────
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))
def _runs(chosen: list[int]) -> list[tuple[int, int]]:
"""The chosen stages as unbroken runs, each (first, last): [0, 1, 3] → [(0, 1), (3, 3)]."""
runs: list[tuple[int, int]] = []
for i in sorted(set(chosen)):
if runs and runs[-1][1] == i - 1:
runs[-1] = (runs[-1][0], i)
else:
runs.append((i, i))
return runs
# -- durations ------------------------------------------------------------------
def measure(m: dict[str, dt.date | None], segments) -> int | str:
"""One document's days over the chosen stages, or why it has none: `missing` when an end of a
run is unknown, `order` when a run ends before it starts. Pure, as Compass's."""
names = [name for name, _ in MILESTONES]
total = 0
for first, last in _runs([SEGMENTS.index(s) for s in segments]):
start, end = m.get(names[first]), m.get(names[last + 1])
if start is None or end is None:
return "missing"
if end < start:
return "order"
total += (end - start).days
return total
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."""
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)
# `->>` 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]
rows = db.execute(
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))
.group_by(doc, _EVENT.c.kind)).all()
by_doc: dict[str, dict[str, dt.date]] = defaultdict(dict)
name_of = {kind: name for name, kind in MILESTONES}
for document, kind, day in rows:
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, segments, *, today: dt.date | None = None) -> dict[str, Any]:
"""How long documents took over the chosen stages: how many were measured, the median, the
bands, and how many were left out and why. Aggregates only — no document is named."""
chosen = [s for s in SEGMENTS if s in segments]
status = log_status(db)
empty = {"segments": chosen, "measured": 0, "median_days": None,
"bands": [{"from": lo, "to": hi, "count": 0} for lo, hi in BANDS],
"skipped": {"missing": 0, "order": 0}}
if status != "ok" or not chosen:
return {"status": status, **empty}
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}
for m in milestones(db, today=today):
days = measure(m, chosen)
if isinstance(days, str):
skipped[days] += 1
else:
measured.append(days)
return {"status": "ok", "segments": chosen, "measured": len(measured),
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)}
+25 -1
View File
@@ -1,4 +1,4 @@
"""What a named contract says (Atrium#53, section 5): `chatClauses` reads the contract's text from
"""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
@@ -37,6 +37,7 @@ def _run(question: str, files=("umowa.docx",), named=True) -> list:
"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)))
@@ -63,3 +64,26 @@ def test_a_content_question_gets_the_matching_paragraphs_in_document_order() ->
])
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"]
+3 -5
View File
@@ -1,4 +1,4 @@
"""Contract review from the chat (Atrium#53, stage 2): `chatReview` decides by code what to order in
"""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`.
"""
@@ -30,7 +30,6 @@ def _run(case: dict) -> dict:
stubs = f"""
const CASE = {json.dumps(case)};
const calls = [];
const chatModules = () => CASE.modules.map((slug) => ({{ slug }}));
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) => {{
@@ -58,8 +57,7 @@ chatReview({{ question: CASE.question, named: {json.dumps(named)}, prev: {json.d
def _case(**kw) -> dict:
base = {"question": "Sprawdź umowę UM-2026-0017", "modules": ["galena", "arbiter"],
"skills": [SKILL], "named": [C1],
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"},
@@ -138,7 +136,7 @@ def test_the_report_is_framed_with_no_rights_and_the_panel_never_transitions_vis
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(modules=["galena"], refuse=403))
r = _run(_case(refuse=403))
assert "nie masz do niego dostępu" in r["out"][0] and r["opened"] is None
@@ -7,7 +7,7 @@ the submodule is checked out: an evidence table a module adds later must not dep
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 (Atrium#53): the tier stays, and nothing is listed in it.
module of the READER tier, left the platform: the tier stays, and nothing is listed in it.
"""
from __future__ import annotations
+50 -14
View File
@@ -1,33 +1,69 @@
"""Panorama's trends on Atrium's home (Atrium#53, stage 3). DB-free: the pure parts, and the guard."""
"""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 inspect
import types
import uuid
from app.routers import marketplace
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 test_a_document_is_measured_over_both_stages():
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, trends.SEGMENTS) == 10
assert trends.measure(m, ["przygotowanie"]) == 3
assert trends.measure(m) == 10
def test_a_document_without_a_milestone_or_out_of_order_is_left_out():
# Both stages together run from creation to signature: the end that is missing is the signature.
assert trends.measure({"created": D, "approved": D, "signed": None}, trends.SEGMENTS) == "missing"
assert trends.measure({"created": D, "approved": None, "signed": D}, ["przygotowanie"]) == "missing"
late = {"created": D, "approved": D - dt.timedelta(days=1), "signed": D}
assert trends.measure(late, ["przygotowanie"]) == "order"
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_trends_are_for_platform_administrators_only():
source = inspect.getsource(marketplace.home_trends)
assert "require_administrator" in source
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
+1 -1
View File
@@ -315,7 +315,7 @@ class TestEventEmitters:
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 (Atrium#53), so the role here is a stand-in."""
left the platform, so the role here is a stand-in."""
tiers = identity_grants.event_emitters(_platform(
identity_reader_roles="galena_app,agora_app,reporter_app",
module_event_emitter_roles="galena_app,agora_app",
+2 -2
View File
@@ -224,14 +224,14 @@ class TestFields:
class TestServiceModules:
"""A service module (`in_menu` false, Galena per Atrium#53) loses its menu entry and its
"""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
# Panorama left the platform (Atrium#53): no longer seeded; 0018 hides an existing row.
# 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"))
+113
View File
@@ -0,0 +1,113 @@
"""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}]) == ""
@@ -65,7 +65,7 @@ def arbiter_revision():
def test_0017_makes_only_arbiter_a_service_and_back(arbiter_revision, monkeypatch):
"""Atrium#53, stage 2: contracts are checked from the chat, Arbiter's screens open by link."""
"""Contracts are checked from the chat, Arbiter's screens open by link."""
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
@@ -84,7 +84,7 @@ def test_0018_retires_only_panorama_from_the_menu(monkeypatch):
def test_panorama_is_off_the_platform():
"""Atrium#53: the seed no longer offers Panorama and the front door no longer routes it; an
"""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
+1 -1
View File
@@ -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 — Atrium#53), ten apps: 10 x 13 = 130 — compose.yaml now sets max_connections
# With Lexicon and Agora too (and Panorama, retired since), 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
+1 -1
View File
@@ -77,6 +77,6 @@ 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 (Atrium#53).
# 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
+1 -1
View File
@@ -88,7 +88,7 @@ MODEL_PROVIDER_MIGRATOR_ROLES=arbiter_migrator
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): 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, Atrium#53). Joined the same way; a role is an emitter or a reader, never both (the grant
# 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=
# The shared counterparty register (dredd-core 0.21.0, revision 0012), in the same schema. Writers:
+1 -1
View File
@@ -430,7 +430,7 @@ write_app_files() {
# 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 (Atrium#53): the reader tier starts empty.
# 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): Sygna writes, and its
# migrator moves its own counterparties in. No reader since Workflow (Compass) was retired.
+1 -1
View File
@@ -472,7 +472,7 @@ app_setup() { # sets the per-app globals for $1
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 (Atrium#53): nothing is
# 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.
# The shared counterparty register (dredd-core 0.21.0): the module's tier is the one the hub
+41 -20
View File
@@ -328,6 +328,7 @@ const I18N = {
'Raport analizy': 'Analysis report',
'Pokaż raport': 'Show the report',
'Analiza trwa': 'The analysis is running',
'Analiza trwa dłużej niż zwykle. Jej wynik zobaczysz w module Arbiter.': 'The analysis is taking longer than usual. You will find its result in the Arbiter module.',
'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)',
@@ -1753,6 +1754,7 @@ 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();
}
@@ -1829,7 +1831,7 @@ async function arbiter(method, path, body) {
return data;
}
/* ── Contract review from the chat (Atrium#53, stage 2: plan 3) ──────────────────────────────────
/* ── 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
@@ -1841,6 +1843,10 @@ async function arbiter(method, path, body) {
// 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
// followed in Arbiter, not 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
@@ -1917,7 +1923,7 @@ async function chatReview({ question, named, prev, index, en }) {
}
}
/* What a named contract SAYS (Atrium#53, section 5): the card holds fields, not the text, so a question
/* 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
@@ -1932,10 +1938,20 @@ async function chatClauses(question, named) {
if (!rec || !CHAT_CLAUSE.test(question)) return [];
const c = rec.contract;
try {
const files = reviewFiles(await askerGet('galena', `projects/${c.project_id}/tree?recursive=true`));
if (files.length !== 1) return [];
const doc = await askerGet('galena', `projects/${c.project_id}/text?path=${encodeURIComponent(files[0].path)}`);
const paras = (doc && doc.paragraphs) || [];
// 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 }))
@@ -1943,7 +1959,7 @@ async function chatClauses(question, named) {
.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 ${files[0].path}, akapit ${i + 1}): ${p.slice(0, 2000)}` }));
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
@@ -1955,7 +1971,7 @@ async function chatClauses(question, named) {
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;
reviewPanel.analysis = { ...analysis, since: Date.now(), polls: 0 };
let el = $('reviewPanel');
if (!el) {
el = document.createElement('aside');
@@ -1983,17 +1999,20 @@ async function reviewPoll() {
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="Zamknij">${svg(ICN.x, 16)}</button></div>`;
<button class="btn icon" onclick="reviewClose()" aria-label="${esc(_tr('Zamknij'))}">${svg(ICN.x, 16)}</button></div>`;
let body;
if (run.status === 'error') { // a network blip: say so and try again, never stop for good
if (tooLong && (run.status === 'error' || !REVIEW_OVER.includes(run.status))) {
body = '<div class="banner warn"><span>Analiza trwa dłużej niż zwykle. Jej wynik zobaczysz w module Arbiter.</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, CHAT_REVIEW_POLL_MS * 3);
}
else if (!REVIEW_OVER.includes(run.status)) {
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, CHAT_REVIEW_POLL_MS);
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 {
@@ -2006,7 +2025,7 @@ async function reviewPoll() {
<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 || ICN.sparkles, 16)}<span>Akceptuj analizę</span></button>`}</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);
@@ -2018,8 +2037,9 @@ async function reviewAccept() {
try {
await arbiter('POST', 'analyses/' + encodeURIComponent(a.id) + '/acceptance', { note });
toast(_tr('Analiza zaakceptowana'));
reviewPoll();
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'); }
}
@@ -4904,7 +4924,7 @@ 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, Atrium#53), so its two screens people go to on their own get a
/* 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);
@@ -4917,6 +4937,7 @@ function homeGalenaLinks() {
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
@@ -4943,20 +4964,20 @@ async function loadHomeStats() {
<a class="chart-more" href="#/admin/audit">Dziennik zdarzeń</a></div>`);
}
}
if (p) charts.push(...await homeTrendCards());
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 (moved from Panorama, Atrium#53 stage 3): events per day
/* 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?days=30'); } catch { return []; }
try { t = await api('GET', '/home/trends'); } catch { return []; }
const out = [];
const a = t.activity;
if (a && a.status === 'ok' && a.days.length) {