chat: Scribe and Lexicon read from the chat, a draft created by code (Atrium#53)

Their consoles are gone, so the chat indexes Scribe's templates and drafts and
Lexicon's sources and clause shelves with the asker's session, searches the
library's clauses for a library question, and creates a Scribe draft (from the
one named template, or from scratch) as a coded action.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 21:46:32 +01:00
co-authored by Claude Opus 5.5
parent ad920ed7e8
commit ece89497d6
2 changed files with 222 additions and 3 deletions
@@ -0,0 +1,120 @@
"""Scribe and Lexicon lost their consoles (Atrium#53): the chat reads their templates, drafts,
sources and library, and creates a draft in Scribe by code. Lifted out of `frontend/app.js` and run
under Node with the modules' APIs stubbed. DB-free; skipped where no `node`."""
from __future__ import annotations
import json
import pathlib
import shutil
import subprocess
import pytest
ROOT = pathlib.Path(__file__).resolve().parents[2]
NODE = shutil.which("node")
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
def _between(start: str, end: str) -> str:
i = SRC.index(start)
return SRC[i:SRC.index(end, i)]
BLOCK = "\n".join([
_between("const chatStems = ", "\n") + "\n",
_between("const reviewWords = ", "\n") + "\n",
_between("const CHAT_CLAUSE_TOP = ", "async function chatClauses"),
_between("const chatWho = ", "// The calendar week"),
_between("/* Scribe and Lexicon have no console", "// What Insider's resolve takes"),
])
TPL = [{"id": "t1", "name": "Najem lokalu", "description": "Umowa najmu", "field_count": 3, "slot_count": 1},
{"id": "t2", "name": "Dostawa towaru", "description": None, "field_count": 2, "slot_count": 0}]
DRAFTS = [{"id": "d1", "title": "Najem Kraków", "template_id": "t1", "template_name": "Najem lokalu",
"from_scratch": False, "status": "draft", "owner_id": "u1", "created_at": "2026-11-20T10:00:00"}]
SOURCES = [{"id": "s1", "title": "Wzór NDA", "kind": "file", "name": "nda.docx", "shared": True,
"note": None, "library": {"count": 7}}]
def _run(call: str, case: dict) -> dict:
script = f"""
const CASE = {json.dumps(case)};
const gets = [], posts = [];
const askerGet = async (slug, path) => {{ gets.push(slug + ':' + path); return (CASE.gets || {{}})[slug + ':' + path] ?? null; }};
const jsonOf = (t) => JSON.parse(t);
const httpError = (r, d) => Object.assign(new Error('HTTP ' + r.status), {{ status: r.status, problem: d }});
const document = {{ baseURI: 'http://x/atrium/' }};
const fetch = async (url, opt) => {{ posts.push([String(url), opt.method, JSON.parse(opt.body)]);
const st = CASE.refuse || 201; return {{ ok: st < 300, status: st, text: async () => JSON.stringify({{ id: 'd9', title: JSON.parse(opt.body).title, detail: 'nie' }}) }}; }};
{BLOCK}
({call}).then((out) => console.log(JSON.stringify({{ out, gets, posts }})))
.catch((e) => {{ console.error(e); process.exit(1); }});
"""
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
encoding="utf-8")
assert r.returncode == 0, r.stderr
return json.loads(r.stdout)
GETS = {"scribe:templates": TPL, "scribe:drafts": DRAFTS, "lexicon:sources?status=active": SOURCES,
"lexicon:library/shelves": [{"type": "poufnosc", "label": "Poufność", "count": 4},
{"type": None, "label": None, "count": 0}]}
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_scribe_templates_and_drafts_become_records() -> None:
out = _run("chatScribe({ u1: 'Anna Nowak' })", {"gets": GETS})["out"]
keys = [r["key"] for r in out]
assert keys == ["scribe:szablon:t1", "scribe:szablon:t2", "scribe:szkic:d1"]
assert "Najem lokalu" in out[2]["text"] and "Anna Nowak" in out[2]["text"]
assert out[2]["members"] == ["scribe:szablon:t1"]
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
@pytest.mark.parametrize("call", ["chatScribe({})", "chatLexicon()"])
def test_no_access_is_null(call) -> None:
assert _run(call, {"gets": {}})["out"] is None
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_lexicon_sources_and_shelves() -> None:
out = _run("chatLexicon()", {"gets": GETS})["out"]
assert out[0]["key"] == "lexicon:zrodlo:s1" and "7" in out[0]["text"]
assert out[1]["key"] == "lexicon:polki" and "Poufność 4" in out[1]["text"]
assert "bez typu" not in out[1]["text"]
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_library_clauses_are_searched_only_for_a_library_question() -> None:
path = "lexicon:library/clauses?q=poufn"
hit = [{"source_id": "s1", "source_title": "Wzór NDA", "position": 2, "label": "§ 3",
"numbering": "§ 3", "text": "Strony zachowają poufność.", "types": ["poufnosc"]}]
got = _run("chatLibrary('Jaką klauzulę poufności mamy w bibliotece?')", {"gets": {path: hit}})
assert got["gets"] == [path]
assert got["out"][0]["key"] == "lexicon:klauzula:s1:2" and "poufność" in got["out"][0]["text"]
assert _run("chatLibrary('Jaka kara umowna w UM-1?')", {"gets": {}})["out"] == []
def _index() -> str:
return "{ records: " + json.dumps([{"kind": "szablon", "key": "scribe:szablon:" + t["id"],
"template": t} for t in TPL]) + " }"
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_a_draft_is_created_from_the_one_named_template() -> None:
got = _run(f"chatDraft({{ question: 'Utwórz projekt pisma z szablonu najem „Najem Gdańsk”', index: {_index()}, en: false }})", {})
assert got["posts"] == [["http://x/scribe/api/v1/drafts", "POST", {"template_id": "t1", "title": "Najem Gdańsk"}]]
assert got["out"][1]["mentioned"] == ["scribe:szkic:d9"]
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_from_scratch_and_unclear_template() -> None:
got = _run(f"chatDraft({{ question: 'Załóż szkic od zera', index: {_index()}, en: false }})", {})
assert got["posts"][0][2] == {"template_id": None, "title": ""}
asked = _run(f"chatDraft({{ question: 'Utwórz szkic', index: {_index()}, en: false }})", {})
assert asked["posts"] == [] and asked["out"][1]["coded"] == "ask"
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
def test_a_refusal_is_a_sentence() -> None:
got = _run(f"chatDraft({{ question: 'Załóż szkic od zera', index: {_index()}, en: false }})", {"refuse": 404})
assert "nie masz do niego dostępu" in got["out"][0]
+102 -3
View File
@@ -2310,6 +2310,99 @@ async function chatGalena(names) {
return out;
}
/* Scribe and Lexicon have no console any more (Atrium#53): the chat is where their templates, drafts, sources and
library are read, with the asker's own session like every other module. Templates are read by every user of
Scribe; drafts are the asker's own (a moderator's: all); Lexicon answers only the sources this account may read. */
async function chatScribe(names) {
const templates = await askerGet('scribe', 'templates');
if (templates === null) return null;
const tpl = Object.fromEntries(templates.map((t) => [t.id, t.name]));
const out = templates.map((t) => ({ slug: 'scribe', kind: 'szablon', title: `Szablon dokumentu ${t.name}`, inner: null,
key: 'scribe:szablon:' + t.id, labels: [t.name], template: t,
text: `Szablon dokumentu „${t.name}” w Scribe: ${t.description || 'bez opisu'}. Pól do wypełnienia ${t.field_count}, miejsc na klauzule ${t.slot_count}.` }));
for (const d of (await askerGet('scribe', 'drafts')) || []) {
out.push({ slug: 'scribe', kind: 'szkic', title: `Projekt pisma ${d.title || 'bez tytułu'}`, inner: null, key: 'scribe:szkic:' + d.id,
labels: d.title ? [d.title] : [], at: d.created_at, did: 'utworzony', draft: d,
text: `Projekt pisma (szkic w Scribe) „${d.title || 'bez tytułu'}”, ${d.from_scratch ? 'pisany od zera, bez szablonu' : `z szablonu ${d.template_name || tpl[d.template_id] || 'usuniętego'}`}, ` +
`status ${d.status}, ${chatWho(names, d.owner_id, 'autor', 'autor nie wpisany')}, utworzony ${(d.created_at || '').slice(0, 10)}.`,
...(d.template_id ? { members: ['scribe:szablon:' + d.template_id] } : {}) });
}
return out;
}
async function chatLexicon() {
const sources = await askerGet('lexicon', 'sources?status=active');
if (sources === null) return null;
const out = sources.map((s) => ({ slug: 'lexicon', kind: 'źródło', title: `Wzorzec w bibliotece klauzul: ${s.title}`, inner: null,
key: 'lexicon:zrodlo:' + s.id, labels: [s.title], source: s,
text: `Wzorzec (źródło) „${s.title}” w bibliotece klauzul Lexicon, ${s.kind === 'document' ? 'dokument z Galeny' : 'plik ' + (s.name || '')}, ` +
`${s.shared ? 'udostępniony wszystkim' : 'prywatny'}, klauzul w bibliotece ${(s.library && s.library.count) || 0}. ${s.note || ''}` }));
const shelves = ((await askerGet('lexicon', 'library/shelves')) || []).filter((x) => x.count);
if (shelves.length) out.push({ slug: 'lexicon', kind: 'zestawienie', title: 'Biblioteka klauzul Lexicon: typy klauzul i ich liczba', inner: null,
key: 'lexicon:polki', members: out.map((r) => r.key),
text: `Biblioteka klauzul Lexicon, liczba klauzul według typu: ${shelves.map((x) => `${x.type ? x.label : 'bez typu'} ${x.count}`).join('; ')}.` });
return out;
}
/* Library clauses whose words the question uses, read now (Lexicon's own full-text search), when it asks about the
library's clauses or wordings ("jaką klauzulę poufności mamy w bibliotece"). [] otherwise, or without access. */
const CHAT_LIBRARY = /bibliot|lexicon|wzorc|wzorów|wzory|wzór|library|template clause/iu;
async function chatLibrary(question) {
if (!CHAT_LIBRARY.test(question) || !/klauzul|zapis|postanowie|brzmieni|clause|wording/iu.test(question)) return [];
const words = [...chatStems(question)].filter((w) => !CHAT_CLAUSE_STOP.includes(w) && !/^(?:bibli|lexic|wzor|wzór|klauz|libra|claus|mamy|jaką|which|what)/u.test(w)); // chatStems: 5-letter stems
if (!words.length) return [];
try {
const hits = (await askerGet('lexicon', 'library/clauses?q=' + encodeURIComponent(words.slice(0, 8).join(' ')))) || [];
return hits.slice(0, CHAT_CLAUSE_TOP).map((c) => ({ slug: 'lexicon', kind: 'klauzula',
key: `lexicon:klauzula:${c.source_id}:${c.position}`, title: `${c.source_title}: ${c.label || String(c.text).slice(0, 80)}`, inner: null,
labels: [c.source_title], text: `Klauzula z biblioteki Lexicon, wzorzec „${c.source_title}”${c.numbering ? ', ' + c.numbering : ''}` +
`${(c.types || []).length ? ', typ ' + c.types.join(', ') : ''}: ${String(c.text).slice(0, 2000)}` }));
} catch (ex) {
if (ex.name === 'AbortError') throw ex;
return [];
}
}
/* "Utwórz projekt pisma z szablonu Najem" / "…od zera": an ACTION in Scribe, routed by code like contract review.
Code picks the template (the only one whose name the question uses), or writes from scratch when asked to;
anything unclear is asked back, never guessed. Scribe decides who may (the asker's own session). */
const CHAT_DRAFT = /(?:^|[^\p{L}])(?:utwórz|utworz|załóż|zaloz|zacznij|przygotuj|create|start)\s+(?:nowy\s+|new\s+|a\s+)?(?:projekt\s+pisma|projekt\s+dokumentu|szkic|draft)/iu;
const CHAT_SCRATCH = /od\s+zera|bez\s+szablonu|from\s+scratch|without\s+a?\s*template/iu;
async function scribeWrite(method, path, body) {
const r = await fetch(new URL('../scribe/api/v1/' + path, document.baseURI), { method, credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
const data = jsonOf(await r.text());
if (!r.ok) throw httpError(r, data);
return data;
}
async function chatDraft({ question, index, en }) {
const say = (pl, eng, extra = {}) => [en ? eng : pl, { coded: 'draft', ...extra }];
const templates = index.records.filter((r) => r.kind === 'szablon');
const title = ((question.match(/[„"«]([^”"»]{1,300})[”"»]/u) || [])[1] || '').trim();
let tpl = null;
if (!CHAT_SCRATCH.test(question)) {
const words = new Set(reviewWords(question));
const hit = templates.filter((r) => reviewWords(r.template.name).some((w) => words.has(w)));
if (hit.length !== 1) {
const list = (hit.length ? hit : templates).slice(0, 8).map((r) => r.template.name).join('; ');
return say(templates.length ? `Z którego szablonu mam utworzyć projekt: ${list}? Napisz jego nazwę albo „od zera”.` : 'Nie widzę żadnego szablonu w Scribe. Napisz „od zera”, a utworzę projekt bez szablonu.',
templates.length ? `Which template should the draft use: ${list}? Name it, or say "from scratch".` : 'I see no template in Scribe. Say "from scratch" and I will create a draft without one.',
{ coded: 'ask', mentioned: (hit.length ? hit : templates).map((r) => r.key) });
}
tpl = hit[0].template;
}
try {
const d = await scribeWrite('POST', 'drafts', { template_id: tpl ? tpl.id : null, title: title || (tpl ? tpl.name : '') });
return say(`Utworzyłem w Scribe projekt pisma „${d.title || 'bez tytułu'}”${tpl ? ` z szablonu ${tpl.name}` : ' od zera'}.`,
`I created the draft "${d.title || 'untitled'}" in Scribe${tpl ? ` from the template ${tpl.name}` : ' from scratch'}.`, { mentioned: ['scribe:szkic:' + d.id] });
} catch (ex) {
if (ex.name === 'AbortError') throw ex;
if ([401, 403, 404].includes(ex.status)) return say('Tworzenie pism jest w module Scribe, a nie masz do niego dostępu.', 'Drafting lives in the Scribe module, and you have no access to it.');
return say(`Scribe nie utworzył projektu: ${(ex.problem && ex.problem.detail) || ex.message}.`, `Scribe did not create the draft: ${(ex.problem && ex.problem.detail) || ex.message}.`);
}
}
// What Insider's resolve takes: an article of a code or a named EU act, a Dz.U. reference, a case number, a CELEX.
// A topic question without a citation ("kara umowna") goes to chatTopic, and only once Insider's own index
// of the acts' texts is built: its live mode matches titles and finds junk.
@@ -2695,12 +2788,13 @@ async function chatIndex() {
const register = chatRegister(today);
const parts = [['Rejestr umów (Galena)', () => register], ['Sygna (sprawy, terminy, klienci)',
async () => chatSygna(today, names, ((await register) || []).filter((r) => r.contract).map((r) => r.contract))],
['Counsel Scorecard (kancelarie zewnętrzne, oceny)', chatCounsel], ['Galena (dokumenty, opinie)', () => chatGalena(names)]];
['Counsel Scorecard (kancelarie zewnętrzne, oceny)', chatCounsel], ['Galena (dokumenty, opinie)', () => chatGalena(names)],
['Scribe (szablony, projekty pism)', () => chatScribe(names)], ['Lexicon (wzorce, biblioteka klauzul)', chatLexicon]];
const [got, law] = await Promise.all([Promise.all(parts.map(([, read]) => read())), askerGet('insider', 'sources')]);
const blind = parts.filter((_, i) => got[i] === null).map(([name]) => name);
// "Do you have access to Insider?" is a question about the chat itself: answered from this record.
const seen = parts.filter((_, i) => got[i] !== null).map(([name]) => name);
const access = { slug: 'atrium', kind: 'dostęp', key: 'atrium:dostep', title: 'Dostęp czatu: moduły i dane widoczne na Twoim koncie (Insider, Sygna, Counsel, Galena z rejestrem umów)', inner: null,
const access = { slug: 'atrium', kind: 'dostęp', key: 'atrium:dostep', title: 'Dostęp czatu: moduły i dane widoczne na Twoim koncie (Insider, Sygna, Counsel, Galena z rejestrem umów, Scribe, Lexicon)', inner: null,
text: `Czat czyta dane na koncie pytającego. Ma dostęp do: ${seen.join(', ') || 'żadnego modułu'}. Nie ma dostępu do: ${blind.join(', ') || 'brak takich modułów'}. ` +
(law === null ? 'Insider (przepisy i orzeczenia): brak dostępu na tym koncie.'
: 'Insider (przepisy i orzeczenia): dostęp jest. Czat pobiera tekst przepisu, akt albo orzeczenie, gdy pytanie podaje konkretne odwołanie, np. art. 471 k.c., art. 6 RODO, Dz.U. 2018 poz. 1000, sygnaturę II C 2145/25. Szuka też przepisów po samym temacie pytania.') };
@@ -4351,6 +4445,11 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
const [text, extra] = await chatReview({ question, named, prev: at >= 0 ? turns[at] : null, index, en });
return done(text, extra);
}
// "Utwórz projekt pisma z szablonu …": an action in Scribe (chatDraft).
if (CHAT_DRAFT.test(question)) {
const [text, extra] = await chatDraft({ question, index, en });
return done(text, extra);
}
const ana = chatAnaphora(question);
// "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.
@@ -4438,7 +4537,7 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
}
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]);
const clauses = [...await chatClauses(question, [...named, ...resolved]), ...await chatLibrary(question)];
// A fault in the law graph leaves the turn as without it.
let lawGraph = { near: [] };
if (prawo) {