Check a contract from the chat, report and acceptance in a side panel

"Sprawdź umowę UM-2026-0017" (or "sprawdź tę umowę" after an answer about
one) is now an action, routed by code like the rest of the chat (no model
tools): code picks the register contract, its one document file in Galena and
the skill to judge by (the only published one, or the one the question
names), and orders an `agent` analysis in Arbiter with the asker's session.
Anything missing - no Arbiter access, several contracts, files or skills, no
skill - is asked back, never guessed.

The report opens in a panel beside the chat, framed with sandbox="" as
Arbiter's console frames it, and polls while the run is going. The lawyer
accepts the analysis there (POST /analyses/{id}/acceptance, Arbiter#4), with
an optional note; the answer keeps a "Pokaż raport" button to reopen it.

Atrium#53, stage 2 (plan 3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 10:36:43 +01:00
co-authored by Claude Opus 5.5
parent 7f753f58e3
commit 2134d37464
3 changed files with 332 additions and 0 deletions
+134
View File
@@ -0,0 +1,134 @@
"""Contract review from the chat (Atrium#53, stage 2): `chatReview` decides by code what to order in
Arbiter, or what to ask back. Lifted out of `frontend/app.js` and run under Node with the modules'
APIs stubbed, so the behaviour is asserted, not the source text. DB-free; skipped where no `node`.
"""
from __future__ import annotations
import json
import pathlib
import re
import shutil
import subprocess
import pytest
ROOT = pathlib.Path(__file__).resolve().parents[2]
NODE = shutil.which("node")
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
CSS = (ROOT / "frontend" / "app.css").read_text(encoding="utf-8")
BLOCK = SRC[SRC.index("const CHAT_REVIEW = "):SRC.index("/* The panel beside the chat")]
C1 = {"id": "c1", "project_id": "p1", "number": "UM-2026-0017", "name": "Najem biura"}
C2 = {"id": "c2", "project_id": "p2", "number": "UM-2026-0018", "name": "Dostawa"}
SKILL = {"id": "s1", "name": "Umowy najmu", "status": "published", "current_version_id": "v3"}
def _run(case: dict) -> dict:
"""One `chatReview` call; returns its [text, extra] and every call it made to Arbiter."""
stubs = f"""
const CASE = {json.dumps(case)};
const calls = [];
const 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) => {{
calls.push([method, path, body]);
if (CASE.refuse) {{ throw new Error('nope'); }}
return path === 'subjects/document' ? {{ id: 'sub1' }} : {{ id: 'run1' }};
}};
let opened = null;
const reviewOpen = (a) => {{ opened = a; }};
"""
named = [{"contract": c} for c in case.get("named", [])]
prev = {"mentioned": [f"galena:umowa:{c['id']}" for c in case.get("prev", [])]}
index = "{ byKey: new Map(" + json.dumps(
[[f"galena:umowa:{c['id']}", {"contract": c}] for c in case.get("prev", [])]) + ") }"
script = stubs + BLOCK + f"""
chatReview({{ question: CASE.question, named: {json.dumps(named)}, prev: {json.dumps(prev)},
index: {index}, en: false }})
.then((out) => console.log(JSON.stringify({{ out, calls, opened }})))
.catch((e) => {{ console.error(e); process.exit(1); }});
"""
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
encoding="utf-8")
assert r.returncode == 0, r.stderr
return json.loads(r.stdout)
def _case(**kw) -> dict:
base = {"question": "Sprawdź umowę UM-2026-0017", "modules": ["galena", "arbiter"],
"skills": [SKILL], "named": [C1],
"trees": {"projects/p1/tree?recursive=true": {"entries": [
{"type": "dir", "path": "podpisane"},
{"type": "file", "path": "podpisane/skan.pdf"},
{"type": "file", "path": ".galena/meta"},
{"type": "file", "path": "umowa.docx"}]}}}
base.update(kw)
return base
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_a_named_contract_is_ordered_by_the_only_skill_and_the_panel_opens() -> None:
r = _run(_case())
text, extra = r["out"]
assert r["calls"] == [
["POST", "subjects/document", {"document_id": "p1", "path": "umowa.docx",
"title": "UM-2026-0017 Najem biura"}],
["POST", "analyses", {"subject_id": "sub1", "mode": "agent", "skill_id": "s1", "skill_n": 3}]]
assert extra["analysis"] == {"id": "run1", "number": "UM-2026-0017", "name": "Najem biura",
"skill": "Umowy najmu", "n": 3}
assert r["opened"] == extra["analysis"]
assert "UM-2026-0017" in text and "umowa.docx" in text and "zaakceptować" in text
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_the_contract_of_the_last_answer_is_this_one() -> None:
r = _run(_case(question="Sprawdź tę umowę", named=[], prev=[C1]))
assert r["out"][1]["analysis"]["number"] == "UM-2026-0017"
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
@pytest.mark.parametrize("kw, words", [
({"modules": ["galena"]}, "Arbiter"),
({"named": [C1, C2]}, "Którą umowę"),
({"named": []}, "Którą umowę"),
({"trees": {}}, "nie ma w Galenie pliku"),
({"trees": {"projects/p1/tree?recursive=true": [{"type": "file", "path": "a.docx"},
{"type": "file", "path": "b.pdf"}]}}, "2 plików"),
({"skills": []}, "Nie ma jeszcze opublikowanego skilla"),
({"skills": [SKILL, {**SKILL, "id": "s2", "name": "Umowy dostawy"}]}, "Według którego skilla"),
])
def test_anything_missing_is_asked_back_and_nothing_is_ordered(kw, words) -> None:
r = _run(_case(**kw))
assert words in r["out"][0]
assert r["calls"] == [] and r["opened"] is None
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_the_skill_named_in_the_question_is_the_one() -> None:
other = {**SKILL, "id": "s2", "name": "Umowy dostawy"}
r = _run(_case(question="Sprawdź umowę UM-2026-0017 skillem dostawy", skills=[SKILL, other]))
assert r["calls"][1][2]["skill_id"] == "s2"
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_a_refused_order_is_a_sentence_not_a_throw() -> None:
r = _run(_case(refuse=True))
text, extra = r["out"]
assert text.startswith("Arbiter nie przyjął zlecenia") and extra["failed"] is True
assert r["opened"] is None
def test_the_trigger_wants_a_verb_and_a_contract() -> None:
pattern = re.search(r"const CHAT_REVIEW = /(.*)/iu;", SRC).group(1)
assert "sprawdź" in pattern and "umow" in pattern
# The route also wants a register contract (named, or "tę umowę"): a law question stays the law's.
assert "named.some((r) => r && r.contract) || chatAnaphora(question).demonstrative" in SRC
def test_the_report_is_framed_with_no_rights_and_the_panel_never_transitions_visibility() -> None:
assert 'class="rp-report" sandbox=""' in SRC
assert "/acceptance'" in SRC
panel = CSS[CSS.index(".review-panel {"):]
assert "transition: transform" in panel and "transition: visibility" not in panel
+19
View File
@@ -467,3 +467,22 @@ a.modchip:hover { text-decoration: none; background: var(--at-surface-hover); }
/* The sidebar's "Dostosuj listę": a quiet last entry of the Aplikacje section. */
.nav-item.nav-tune { width: 100%; border: 0; background: none; font: inherit; cursor: pointer; text-align: left; color: var(--at-text-muted); }
.nav-item.nav-tune:hover { color: var(--at-text); }
/* The contract review panel beside the chat (chatReview / reviewOpen in app.js). Off-canvas on the
right; `transform` transitions, `visibility` flips at once (a delayed `visibility` sticks when
frames are throttled). Full width on a phone. */
.review-panel {
position: fixed; top: 0; right: 0; bottom: 0; z-index: 40; width: min(560px, 100vw);
display: flex; flex-direction: column; background: var(--at-surface);
border-left: 1px solid var(--at-border); box-shadow: -8px 0 24px rgba(0, 0, 0, .08);
transform: translateX(100%); visibility: hidden; transition: transform .2s ease;
}
.review-panel.open { transform: none; visibility: visible; }
.review-panel .rp-head {
display: flex; align-items: flex-start; justify-content: space-between; gap: 12px;
padding: 14px 16px; border-bottom: 1px solid var(--at-border);
}
.review-panel .rp-body { flex: 1; display: flex; flex-direction: column; gap: 12px; padding: 12px 16px; min-height: 0; overflow: auto; }
.review-panel .rp-report { flex: 1; min-height: 320px; width: 100%; border: 1px solid var(--at-border); border-radius: 8px; background: #fff; }
.review-panel .rp-accept { display: flex; flex-direction: column; gap: 8px; }
.ha-turn .ha-report { margin-top: 8px; }
+179
View File
@@ -323,6 +323,14 @@ const I18N = {
'Anuluj': 'Cancel',
'Usuń': 'Delete',
'Zamknij': 'Close',
'Raport analizy': 'Analysis report',
'Pokaż raport': 'Show the report',
'Analiza trwa': 'The analysis is running',
'Analiza skończyła się bez raportu': 'The analysis ended without a report',
'Analiza zaakceptowana': 'Analysis accepted',
'Notatka (nie da się jej później zmienić ani usunąć; nie wpisuj numerów PESEL, dowodu ani paszportu)': 'Note (it cannot be changed or deleted later; do not enter PESEL, identity card or passport numbers)',
'Akceptacja jest jednorazowa i nie da się jej cofnąć ani poprawić.': 'An acceptance is given once and cannot be withdrawn or corrected.',
'Akceptuj analizę': 'Accept the analysis',
'Zapisano.': 'Saved.',
'Tej operacji nie da się cofnąć.': 'This cannot be undone.',
'Moduły': 'Modules',
@@ -1636,6 +1644,13 @@ function chatRender(toEnd) {
else el.textContent = shown.content;
if (shown !== t) el.appendChild(chatTableEl(t.table));
if (t.review && !t.status) renderReview(el, t.review);
if (t.analysis && !t.status) { // an order in Arbiter (chatReview): its report reopens in the panel
const b = document.createElement('button');
b.className = 'btn ha-report';
b.textContent = _tr('Pokaż raport');
b.onclick = () => reviewOpen(t.analysis);
el.appendChild(b);
}
if (t.trace && t.trace.length && !t.status) { // what the model actually looked at, in order
const det = document.createElement('details');
det.className = 'ha-trace faint tiny';
@@ -1794,6 +1809,162 @@ async function arbiter(method, path, body) {
return data;
}
/* ── Contract review from the chat (Atrium#53, stage 2: plan 3) ──────────────────────────────────
"Sprawdź umowę UM-2026-0017" is an ACTION, routed by code like every other turn (no model tools,
see above): code picks the contract (named in the question, or the one the last answer was about),
its document file in Galena and the skill to check it by, and orders an `agent` analysis in Arbiter
with the asker's own session. The report then opens in a panel beside the chat, framed sandboxed
exactly as Arbiter's console frames it, and the lawyer accepts the analysis there
(`POST /analyses/{id}/acceptance`: Arbiter says `analysis.accepted`, Galena's card keeps it).
Whatever is missing - no Arbiter, no skill, several files or skills - is asked back, never guessed. */
const CHAT_REVIEW = /(?:^|[^\p{L}])(?:sprawdź|sprawdz|przeanalizuj|zweryfikuj|przejrzyj|zbadaj|review|check|analy[sz]e)(?![\p{L}])[\s\S]*(?:umow|kontrakt|contract|agreement|UM-\d)/iu;
const CHAT_REVIEW_POLL_MS = 3000;
// A Galena project's document file: not a signed scan (`podpisane/`), not a hidden path (Galena's `workflow_export.main_file`).
const reviewFiles = (tree) => (Array.isArray(tree) ? tree : (tree && tree.entries) || [])
.filter((n) => ['file', 'blob'].includes(n.type || n.kind) && n.path
&& !n.path.split('/').some((p) => p.startsWith('.')) && !n.path.startsWith('podpisane/'));
const reviewWords = (s) => (String(s).toLowerCase().match(/[\p{L}\d]{4,}/gu) || []);
/* The one contract this turn is about: named in the question, else the only one the last answer named. */
function reviewContract(named, prev, index) {
const own = named.filter((r) => r && r.contract);
if (own.length) return own.length === 1 ? { contract: own[0].contract } : { several: own.map((r) => r.contract) };
const back = ((prev && prev.mentioned) || []).map((k) => index.byKey.get(k)).filter((r) => r && r.contract);
return back.length === 1 ? { contract: back[0].contract } : back.length ? { several: back.map((r) => r.contract) } : {};
}
/* The skill to judge by: the only published one, or the one whose name the question uses. */
function reviewSkill(skills, question) {
const live = skills.filter((s) => s.status !== 'archived' && s.current_version_id);
if (live.length <= 1) return { skill: live[0] || null, all: live };
const words = new Set(reviewWords(question));
const hit = live.filter((s) => reviewWords(s.name).some((w) => words.has(w)));
return hit.length === 1 ? { skill: hit[0], all: live } : { skill: null, all: live };
}
/* The turn: [answer text, extra fields of the answer]. Every refusal is a sentence, never a throw. */
async function chatReview({ question, named, prev, index, en }) {
const say = (pl, eng, extra = {}) => [en ? eng : pl, { coded: 'review', ...extra }];
if (!chatModules().some((m) => m.slug === 'arbiter')) {
return say('Sprawdzanie umów jest w module Arbiter, a nie masz do niego dostępu.',
'Contract review lives in the Arbiter module, and you have no access to it.');
}
const pick = reviewContract(named, prev, index);
if (pick.several) {
return say(`Którą umowę mam sprawdzić: ${pick.several.slice(0, 6).map((c) => c.number + ' ' + c.name).join('; ')}? Podaj jej numer.`,
`Which contract should I check: ${pick.several.slice(0, 6).map((c) => c.number + ' ' + c.name).join('; ')}? Give its number.`,
{ coded: 'ask', mentioned: pick.several.map((c) => 'galena:umowa:' + c.id) });
}
if (!pick.contract) {
return say('Którą umowę mam sprawdzić? Podaj jej numer z rejestru, np. UM-2026-0017.',
'Which contract should I check? Give its register number, e.g. UM-2026-0017.', { coded: 'ask' });
}
const c = pick.contract;
const files = reviewFiles(await askerGet('galena', `projects/${c.project_id}/tree?recursive=true`));
if (files.length !== 1) {
return say(files.length
? `Umowa ${c.number} ma w Galenie ${files.length} plików (${files.slice(0, 5).map((f) => f.path).join(', ')}). Sprawdzam tylko umowę z jednym plikiem; zostaw w projekcie jeden plik umowy albo zleć analizę w Arbitrze.`
: `Umowa ${c.number} nie ma w Galenie pliku, który dałoby się sprawdzić.`,
files.length
? `Contract ${c.number} has ${files.length} files in Galena (${files.slice(0, 5).map((f) => f.path).join(', ')}). I only check a contract with one file; keep one contract file in the project or order the analysis in Arbiter.`
: `Contract ${c.number} has no file in Galena that could be checked.`, { mentioned: ['galena:umowa:' + c.id] });
}
const { skill, all } = reviewSkill(await api('GET', '/skills'), question);
if (!skill) {
return all.length
? say(`Według którego skilla sprawdzić umowę ${c.number}: ${all.map((s) => s.name).join('; ')}? Napisz jego nazwę w pytaniu.`,
`Which skill should check contract ${c.number}: ${all.map((s) => s.name).join('; ')}? Name it in the question.`, { coded: 'ask' })
: say('Nie ma jeszcze opublikowanego skilla do sprawdzania umów. Dodaj go w Skillach.',
'There is no published skill for checking contracts yet. Add one under Skills.');
}
const n = ((await api('GET', '/skills/' + encodeURIComponent(skill.id))).versions || [])
.find((v) => v.id === skill.current_version_id);
if (!n) return say('Nie mogę odczytać aktualnej wersji skilla ' + skill.name + '.', 'I cannot read the current version of skill ' + skill.name + '.');
try {
const subject = await arbiter('POST', 'subjects/document', { document_id: c.project_id, path: files[0].path, title: (c.number + ' ' + c.name).slice(0, 200) });
const run = await arbiter('POST', 'analyses', { subject_id: subject.id, mode: 'agent', skill_id: skill.id, skill_n: n.n });
const analysis = { id: run.id, number: c.number, name: c.name, skill: skill.name, n: n.n };
reviewOpen(analysis);
return say(`Zleciłem sprawdzenie umowy ${c.number} (${files[0].path}) skillem ${skill.name} w wersji ${n.n}. Raport otworzy się w panelu obok, gdy analiza się skończy; tam możesz ją zaakceptować.`,
`I ordered a check of contract ${c.number} (${files[0].path}) by skill ${skill.name}, version ${n.n}. The report opens in the panel beside the chat once the analysis is done; you can accept it there.`,
{ analysis, mentioned: ['galena:umowa:' + c.id] });
} catch (ex) {
return say(`Arbiter nie przyjął zlecenia: ${ex.message}`, `Arbiter refused the order: ${ex.message}`, { failed: true });
}
}
/* The panel beside the chat: the run's state while it runs, then its report framed with no rights
(`sandbox=""`, Arbiter's own CSP on the response too) and the acceptance under it. One panel, one
run at a time; a later order replaces it. Polls only while the panel is open. */
const reviewPanel = { analysis: null, timer: null };
function reviewOpen(analysis) {
reviewPanel.analysis = analysis;
let el = $('reviewPanel');
if (!el) {
el = document.createElement('aside');
el.id = 'reviewPanel';
el.className = 'review-panel';
el.setAttribute('aria-label', _tr('Raport analizy'));
document.body.appendChild(el);
}
el.classList.add('open');
reviewPoll();
}
window.reviewClose = () => {
clearTimeout(reviewPanel.timer);
reviewPanel.analysis = null;
const el = $('reviewPanel');
if (el) el.classList.remove('open');
};
const REVIEW_DONE = ['done', 'partial'];
const REVIEW_OVER = ['done', 'partial', 'failed', 'unreadable', 'interrupted', 'cancelled'];
async function reviewPoll() {
clearTimeout(reviewPanel.timer);
const a = reviewPanel.analysis;
const el = $('reviewPanel');
if (!a || !el) return;
let run;
try { run = await arbiter('GET', 'analyses/' + encodeURIComponent(a.id)); } catch (ex) { run = { status: 'error', error: ex.message }; }
if (reviewPanel.analysis !== a) return; // closed, or replaced by a later order, while this ran
const 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>`;
let body;
if (run.status === 'error') body = `<div class="banner warn" data-no-i18n>${esc(run.error)}</div>`;
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);
} else if (!REVIEW_DONE.includes(run.status)) {
body = `<div class="banner warn"><span>Analiza skończyła się bez raportu</span>: <span data-no-i18n>${esc(run.status)}</span></div>`;
} else {
const accepted = run.signoff;
body = `<iframe class="rp-report" sandbox="" referrerpolicy="no-referrer" title="Raport"
src="${esc(new URL('../arbiter/api/v1/analyses/' + encodeURIComponent(a.id) + '/report', document.baseURI).href)}"></iframe>
<div class="rp-accept">${accepted
? `<div class="banner ok"><span>Analiza zaakceptowana</span> <span data-no-i18n>${esc(String(accepted.created_at || '').slice(0, 10))}</span></div>`
: `<label class="field"><span>Notatka (nie da się jej później zmienić ani usunąć; nie wpisuj numerów PESEL, dowodu ani paszportu)</span>
<textarea id="rpNote" rows="2" maxlength="4000"></textarea></label>
<div class="faint tiny">Akceptacja jest jednorazowa i nie da się jej cofnąć ani poprawić.</div>
<div id="rpErr" class="banner warn hidden" data-no-i18n></div>
<button class="btn primary" onclick="reviewAccept()">${svg(ICN.check || ICN.sparkles, 16)}<span>Akceptuj analizę</span></button>`}</div>`;
}
el.innerHTML = head + `<div class="rp-body">${body}</div>`;
localize(el);
}
window.reviewAccept = async () => {
const a = reviewPanel.analysis;
if (!a) return;
const note = ($('rpNote') && $('rpNote').value.trim()) || null;
try {
await arbiter('POST', 'analyses/' + encodeURIComponent(a.id) + '/acceptance', { note });
toast(_tr('Analiza zaakceptowana'));
reviewPoll();
} catch (ex) {
const err = $('rpErr');
if (err) { err.textContent = ex.message; err.classList.remove('hidden'); }
}
};
/* An Atrium GET answered as text, not JSON: a skill file's bytes as the editor reads them. */
async function apiText(path) {
const res = await fetch(API + path, { credentials: 'same-origin' });
@@ -4090,6 +4261,14 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
const named = chatNamed(question, index.records).map(([k]) => index.byKey.get(k));
// A party hit never takes a law question off Insider unless the question is about a contract.
if (!named.length && (!CHAT_TOPICWORD.test(question) || /umow|kontrakt|contract|agreement/iu.test(question))) named.push(...chatByParty(question, index.records));
// "Sprawdź umowę …": an action in Arbiter, not a question to the model (chatReview).
// Only about a contract of the register: one named, or "tę umowę" after an answer that named one. "Sprawdź, czy
// umowa o dzieło wymaga formy pisemnej" names none and stays a question about the law.
if (CHAT_REVIEW.test(question) && chatRoute(question) !== 'law_cite'
&& (named.some((r) => r && r.contract) || chatAnaphora(question).demonstrative)) {
const [text, extra] = await chatReview({ question, named, prev: at >= 0 ? turns[at] : null, index, en });
return done(text, extra);
}
const ana = chatAnaphora(question);
// "ta druga" right after the map asked which firm: the second candidate as the question listed them. Resolved
// through the anchors' records instead, it missed when the two anchors were of different kinds.