feat(chat, home): a contract's text in the chat; ways into Galena (Atrium#53, section 5)

A question about what a named contract says reads its one document file
from Galena now (GET projects/{id}/text, as the asker, nothing stored); code
picks up to four paragraphs sharing the question's words and gives them to
the model as sources. Galena has no menu entry, so the home page links its
documents and its contract register for whoever has access.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 19:12:49 +01:00
co-authored by Claude Opus 5.5
parent 84402c5645
commit 6bc1464a23
2 changed files with 111 additions and 2 deletions
@@ -0,0 +1,65 @@
"""What a named contract says (Atrium#53, section 5): `chatClauses` reads the contract's text from
Galena and picks the paragraphs that share the question's words. Run under Node with the module
calls stubbed; skipped where no `node`."""
from __future__ import annotations
import json
import pathlib
import shutil
import subprocess
import pytest
ROOT = pathlib.Path(__file__).resolve().parents[2]
NODE = shutil.which("node")
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
def _between(start: str, end: str) -> str:
i = SRC.index(start)
return SRC[i:SRC.index(end, i)]
BLOCK = "\n".join([
_between("const chatStems = ", "\n") + "\n",
_between("const reviewFiles = ", "const reviewWords"),
_between("const CHAT_CLAUSE = ", "/* The panel beside the chat"),
])
C = {"id": "c1", "project_id": "p1", "number": "UM-2026-0017", "name": "Najem biura"}
PARAS = ["§ 1. Przedmiotem umowy jest najem lokalu.",
"§ 2. Czynsz płatny do 10. dnia miesiąca.",
"§ 5. Za zwłokę najemca zapłaci karę umowną 0,5% czynszu dziennie.",
"§ 6. Umowę można wypowiedzieć z trzymiesięcznym okresem wypowiedzenia."]
def _run(question: str, files=("umowa.docx",), named=True) -> list:
case = {"question": question, "named": [{"contract": C}] if named else [],
"tree": {"entries": [{"type": "file", "path": f} for f in files]}, "paras": PARAS}
script = f"""
const CASE = {json.dumps(case)};
const askerGet = async (slug, path) => path.includes('/tree') ? CASE.tree : {{ paragraphs: CASE.paras }};
{BLOCK}
chatClauses(CASE.question, CASE.named).then((out) => console.log(JSON.stringify(out)))
.catch((e) => {{ console.error(e); process.exit(1); }});
"""
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
encoding="utf-8")
assert r.returncode == 0, r.stderr
return json.loads(r.stdout)
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_a_content_question_gets_the_matching_paragraphs_in_document_order() -> None:
out = _run("Jaka kara umowna za zwłokę jest w UM-2026-0017?")
assert out and out[0]["key"] == "galena:zapis:c1:2"
assert "karę umowną" in out[0]["text"] and "UM-2026-0017" in out[0]["text"]
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
@pytest.mark.parametrize("question, kw", [
("Kiedy kończy się UM-2026-0017?", {}), # not about content
("Jaka kara umowna w UM-2026-0017?", {"named": False}), # no contract named
("Jaka kara umowna w UM-2026-0017?", {"files": ("a.docx", "b.pdf")}), # which file?
])
def test_otherwise_nothing_is_read(question, kw) -> None:
assert _run(question, **kw) == []
+46 -2
View File
@@ -323,6 +323,8 @@ const I18N = {
'Anuluj': 'Cancel',
'Usuń': 'Delete',
'Zamknij': 'Close',
'Rejestr umów': 'Contract register',
'Dokumenty': 'Documents',
'Raport analizy': 'Analysis report',
'Pokaż raport': 'Show the report',
'Analiza trwa': 'The analysis is running',
@@ -1915,6 +1917,35 @@ 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
about content ("jaka kara umowna w UM-2026-0017", "co mówi § 5") reads the contract's one document file from
Galena now, as the asker (`GET projects/{id}/text`, nothing stored), and code picks the paragraphs that share
the question's words. They go to the model as sources like any record, so the answer cites them. Only for a
question about content, only for the first named contract with exactly one document file. */
const CHAT_CLAUSE = /klauzul|zapis|postanowie|paragraf|§|treść|tekst|brzmi|mówi|stanowi|przewiduj|kar[aąy]|odsetk|wypowiedz|odstąpi|termin|poufno|odpowiedzialno|gwarancj|rękojm|zabezpiecz|clause|provision|says|penalt|terminat|liabil/iu;
const CHAT_CLAUSE_TOP = 4;
async function chatClauses(question, named) {
const rec = named.find((r) => r && r.contract);
if (!rec || !CHAT_CLAUSE.test(question)) return [];
const c = rec.contract;
try {
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) || [];
const words = chatStems(question.replace(new RegExp(c.number.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), ''));
const scored = paras.map((p, i) => ({ p, i, s: [...chatStems(p)].filter((w) => words.has(w)).length }))
.filter((x) => x.s > 0).sort((a, b) => b.s - a.s || a.i - b.i).slice(0, CHAT_CLAUSE_TOP)
.sort((a, b) => a.i - b.i);
return scored.map(({ p, i }) => ({ slug: 'galena', kind: 'zapis', key: `galena:zapis:${c.id}:${i}`,
title: `${c.number}: ${p.slice(0, 80)}`, inner: 'card/' + c.project_id, labels: [c.number],
text: `Fragment umowy ${c.number} „${c.name}” (plik ${files[0].path}, akapit ${i + 1}): ${p.slice(0, 2000)}` }));
} catch (ex) {
if (ex.name === 'AbortError') throw ex;
return []; // no text (a scan, another format, no access): the card's fields still answer what they can
}
}
/* The panel beside the chat: the run's state while it runs, then its report framed with no rights
(`sandbox=""`, Arbiter's own CSP on the response too) and the acceptance under it. One panel, one
run at a time; a later order replaces it. Polls only while the panel is open. */
@@ -4380,6 +4411,8 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
topic = t.records;
}
const law = await chatLaw(question, index);
// A question about what a named contract SAYS: its best paragraphs, read now from Galena (chatClauses).
const clauses = await chatClauses(question, [...named, ...resolved]);
// A fault in the law graph leaves the turn as without it.
let lawGraph = { near: [] };
if (prawo) {
@@ -4405,7 +4438,7 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
// The entity's card right after law and topic; a one-record link card behind its record, so [1] stays the record.
const pool = [...(istnienie && !pick && !named.length && !resolved.length && !card && !law.length ? chatExistence(question, index) : []),
...(pick ? [pick.rec] : []), ...law, ...topic, ...lawGraph.near,
...(card && card.rec.kind === 'karta' ? [card.rec] : []), ...named, ...resolved,
...(card && card.rec.kind === 'karta' ? [card.rec] : []), ...named, ...clauses, ...resolved,
...(card && card.rec.kind !== 'karta' ? [card.rec] : []), ...backSum, ...back, ...chatCarry(prev, index),
...(card ? card.lead : []), ...found]
.filter((r) => !seen.has(r.key) && seen.add(r.key));
@@ -4417,7 +4450,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);
.slice(0, CHAT_TOP + 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 });
@@ -4833,6 +4866,7 @@ async function viewHome(C) {
</form>
<div id="homeResults" class="home-results hidden" aria-live="polite"></div>` : '')
+ '<div id="homeKeys"></div>'
+ homeGalenaLinks()
+ '<div id="homeStats" class="home-stats" aria-live="polite"></div>'
+ '<div id="homeModStats" class="home-stats" aria-live="polite"></div>'
/* Your apps are the sidebar; the home page mentions them only when there are none. */
@@ -4866,6 +4900,16 @@ 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
way in here: the documents and the contract register, opened in the frame. Only for somebody with access. */
function homeGalenaLinks() {
const g = (state.launcher || []).find((m) => m.slug === 'galena' && m.has_access);
if (!g) return '';
return `<div class="home-label"><span>Dokumenty</span></div><div class="row" style="gap:8px;flex-wrap:wrap;margin-bottom:12px">
<a class="btn" href="${esc(frameHash('galena', ''))}">${moduleIcon(g, 16)}<span>Dokumenty</span></a>
<a class="btn" href="${esc(frameHash('galena', 'cards'))}">${moduleIcon(g, 16)}<span>Rejestr umów</span></a></div>`;
}
async function loadHomeStats() {
const box = $('homeStats');
if (!box) return;