Chat: read contracts from Galena's register, drop the clause library

Since Compass 0030 the contracts live in Galena's register (WP-R3), so the
chat's contracts?... reads against Compass 404ed. The register reader now
reads galena cards?limit=200 (same card fields: number, counterparty,
value_amount/value_currency, concluded/starts/ends_on, display status),
keys galena:umowa:*, links card/<project_id> and cards, and is labelled
"Rejestr umów (Galena)". Home search finds contracts in Galena too.

Compass's contracts/{id}/library is gone and Lexicon's library is keyed by
its own sources, not by a register card, so the contract law-currency check,
the clause excerpts and the clause-to-Civil-Code graph edges are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 10:46:40 +01:00
co-authored by Claude Opus 5.5
parent cc3099c55a
commit 91c83ce233
+74 -260
View File
@@ -1138,15 +1138,16 @@ const HOME_SEARCH = {
},
compass: async (base, q) => {
const qs = 'limit=5&q=' + encodeURIComponent(q);
const [c, p] = await Promise.all([moduleGet(base, 'contracts?' + qs), moduleGet(base, 'counterparties?' + qs)]);
return (c.items || []).map((i) => ({ kind: 'Umowa', title: i.name, sub: i.number, inner: 'contracts/' + i.id }))
.concat((p.items || []).map((i) => ({ kind: 'Kontrahent', title: i.name, sub: i.nip, inner: 'counterparties/' + i.id })));
// Since Compass 0030 the contracts are Galena's register (below); the counterparties stay here.
const p = await moduleGet(base, 'counterparties?' + qs);
return (p.items || []).map((i) => ({ kind: 'Kontrahent', title: i.name, sub: i.nip, inner: 'counterparties/' + i.id }));
},
galena: async (base, q) => {
const r = await moduleGet(base, 'search?q=' + encodeURIComponent(q));
return (r.hits || []).slice(0, 8).map((h) => (h.type === 'file'
const [r, c] = await Promise.all([moduleGet(base, 'search?q=' + encodeURIComponent(q)),
moduleGet(base, 'cards?limit=5&q=' + encodeURIComponent(q)).catch(() => ({}))]);
return (c.items || []).map((i) => ({ kind: 'Umowa', title: i.name, sub: i.number, inner: 'card/' + i.project_id })).concat((r.hits || []).slice(0, 8).map((h) => (h.type === 'file'
? { kind: 'Plik', title: h.name, sub: `${h.project} / ${h.path}`, inner: 'n/' + h.project_id + (h.folder ? '?path=' + encodeURIComponent(h.folder) : '') }
: { kind: 'Folder', title: h.name, sub: h.path, inner: 'n/' + h.id }));
: { kind: 'Folder', title: h.name, sub: h.path, inner: 'n/' + h.id })));
},
counsel: async (base, q) => {
const KIND = { firm: 'Kancelaria', matter: 'Sprawa', response: 'Ocena', question: 'Pytanie' };
@@ -1442,21 +1443,23 @@ const chatUmowy = (n) => chatPlural(n, 'umowa', 'umowy', 'umów');
const chatAddDays = (today, n) => new Date(Date.parse(today) + n * 864e5).toISOString().slice(0, 10);
const chatMoney = (x) => Number(x).toLocaleString('pl-PL', { minimumFractionDigits: 2, maximumFractionDigits: 2, useGrouping: 'always' }).replace(/\s/g, ' ');
async function chatCompass(today) {
// Galena's contract register (WP-R3; since Compass 0030 the contracts live there, not in Workflow). A card
// is a project typed `umowa`: `status` is the one shown today, `card/<project_id>` its console page.
async function chatRegister(today) {
const rows = [];
for (let off = 0; ; off += 200) {
const page = await askerGet('compass', 'contracts?limit=200&offset=' + off);
const page = await askerGet('galena', 'cards?limit=200&offset=' + off);
if (page === null) return null;
rows.push(...page);
if (page.length < 200) break;
}
const rec = (kind, title, inner, text, key, members) => ({ slug: 'compass', kind, title, inner, text, key, members });
const ck = (c) => 'compass:umowa:' + c.id;
const rec = (kind, title, inner, text, key, members) => ({ slug: 'galena', kind, title, inner, text, key, members });
const ck = (c) => 'galena:umowa:' + c.id;
const out = rows.map((c) => {
const left = c.ends_on ? chatDays(c.ends_on, today) : 0;
const when = c.ends_on ? `kończy się ${c.ends_on} (${left >= 0 ? 'za ' + left + ' dni' : -left + ' dni temu'})` : 'bez daty końca';
const value = c.value_amount ? `wartość ${chatMoney(c.value_amount)} ${c.value_currency}` : 'bez wartości';
return { ...rec('umowa', c.number + ' ' + c.name, 'contracts/' + c.id,
return { ...rec('umowa', c.number + ' ' + c.name, 'card/' + c.project_id,
`Umowa ${c.number} „${c.name}”, kontrahent ${c.counterparty || 'brak'}, status ${c.status}, ${value}, zawarta ${c.concluded_on || 'brak daty'}, ${when}.`, ck(c)),
labels: [c.number, c.name, c.counterparty], at: c.created_at, did: 'dodana do rejestru umów', contract: c };
});
@@ -1477,8 +1480,8 @@ async function chatCompass(today) {
: `status ${status}, waluta ${cur}: ${chatUmowy(g.n)}, łączna wartość ${chatMoney(g.sum)} ${cur} (${g.nums.join(', ')})`;
});
const statuses = [...new Set(rows.map((c) => c.status))];
out.push({ ...rec('zestawienie', 'Zestawienie umów wg statusu i waluty (wartości łączne, liczba umów)', 'contracts',
`Rejestr umów, stan na ${today}, razem ${chatUmowy(rows.length)}. ${totals.join('; ')}.`, 'compass:zestawienie', rows.map(ck)),
out.push({ ...rec('zestawienie', 'Zestawienie umów wg statusu i waluty (wartości łączne, liczba umów)', 'cards',
`Rejestr umów, stan na ${today}, razem ${chatUmowy(rows.length)}. ${totals.join('; ')}.`, 'galena:zestawienie', rows.map(ck)),
// `list`: the groups a list question can ask for, each picked only by its own words ("w statusie szkic"):
// "wygasające" alone is the expiry windows, not the status "wygasla".
list: statuses.map((st) => ({ re: new RegExp(`status\\p{L}*\\s+(?:\\p{L}+\\s+)?${chatEsc(st.slice(0, 5))}`, 'iu'), keys: rows.filter((c) => c.status === st).map(ck) })) });
@@ -1486,17 +1489,17 @@ async function chatCompass(today) {
for (const w of [30, 60, 90]) {
const soon = rows.filter((c) => c.ends_on && chatDays(c.ends_on, today) >= 0 && chatDays(c.ends_on, today) <= w)
.sort((a, b) => a.ends_on.localeCompare(b.ends_on));
out.push({ ...rec('zestawienie', `Umowy wygasające (kończące się) w ciągu ${w} dni`, 'contracts?expiring_within=' + w,
out.push({ ...rec('zestawienie', `Umowy wygasające (kończące się) w ciągu ${w} dni`, 'cards',
// The window's last day is written out: the check holds an answer's "do 28 listopada" to the sources.
`Stan na ${today}, okno ${w} dni do ${chatAddDays(today, w)}. W ciągu ${w} dni kończy się ${chatUmowy(soon.length)}: ` + (soon.map((c) =>
`${c.number} ${c.name} (${c.counterparty || 'brak'}) kończy się ${c.ends_on}, za ${chatDays(c.ends_on, today)} dni, status ${c.status}, ` +
(c.value_amount ? `wartość ${chatMoney(c.value_amount)} ${c.value_currency}` : 'bez wartości')).join('; ') || 'brak') + '.',
'compass:wygasajace:' + w, soon.map(ck)), list: [{ re: chatAsksWindow(w), keys: soon.map(ck) }] });
'galena:wygasajace:' + w, soon.map(ck)), list: [{ re: chatAsksWindow(w), keys: soon.map(ck) }] });
}
const top = rows.filter((c) => c.value_amount).sort((a, b) => b.value_amount - a.value_amount).slice(0, 5);
out.push(rec('zestawienie', 'Umowy o najwyższej wartości (ranking)', 'contracts', 'Bez przeliczania walut. ' + top.map((c, i) =>
out.push(rec('zestawienie', 'Umowy o najwyższej wartości (ranking)', 'cards', 'Bez przeliczania walut. ' + top.map((c, i) =>
`${i + 1}. ${c.number} ${c.name} (${c.counterparty || 'brak'}): ${chatMoney(c.value_amount)} ${c.value_currency}, status ${c.status}`).join('; ') + '.',
'compass:ranking', top.map(ck)));
'galena:ranking', top.map(ck)));
return out;
}
@@ -1542,7 +1545,7 @@ async function chatSygna(today, names, contracts = []) {
const ends = contracts.filter((c) => c.status === 'obowiazuje' && c.ends_on && chatDays(c.ends_on, today) <= 30)
.map((c) => ({ title: `Koniec umowy ${c.number} „${c.name}”`, kind: 'umowa', due_date: c.ends_on, days_left: chatDays(c.ends_on, today),
who: `umowa ${c.number}, kontrahent ${c.counterparty || 'brak'}`, ref: `umowa ${c.number}, ${c.counterparty || 'brak kontrahenta'}`, owner: '-',
key: 'compass:umowa:' + c.id }));
key: 'galena:umowa:' + c.id }));
const open = [...deadlines.filter((d) => !d.completed_at).map((d) => ({ ...d, key: 'sygna:termin:' + d.id, ref: `sprawa ${d.matter_reference} „${d.matter_name || ''}”`,
owner: names[d.owner_id] || 'nieznany', who: `sprawa ${d.matter_reference} „${d.matter_name || ''}”, odpowiada ${names[d.owner_id] || 'nieznany'}` })), ...ends]
.sort((a, b) => a.due_date.localeCompare(b.due_date));
@@ -1699,119 +1702,19 @@ async function chatLaw(question, index) {
return out;
}
/* "Are the provisions this contract cites current?" is decided here, not by the model: the contract's
clauses come from Compass's library (its text, already split; never /file, which audits a download per
call), the citations are cut out by regex, Insider resolves each against the current consolidated text,
and the verdict is computed. The model only phrases one summary record; the verdicts show under the
answer even when it fails. "Current" means: the act is in force, the article is in the current text and
not marked repealed, and a cited consolidated text (t.j.) is the current one. What changed in an article
since signing is not checked. */
const CHAT_LAWWORD = /przepis|artyku|\bart\.|\bustaw|kodeks|rodo|k\.c\.|provision|statut|\blaws?\b|article/i;
const CHAT_CHECKWORD = /aktualn(?:[eya]\b|ych|oś)|obowiązuj|uchylon|nowelizac|zmienion|powołuj|odwołuj|cytuj|current|in force|valid|repeal|amend|\bcite|refer/i;
// "Czy umowa jeszcze obowiązuje?", "Is the contract still valid under the law?": the contract's own status.
const CHAT_CONTRACT_STATUS = /\b(?:umow|contract|agreement)\S*\s+(?:\S+\s+){0,2}?(?:obowiązuj|valid|in force|zmienion|amended)/i;
// A question about the law itself, not the firm's data: legal words, and nothing of ours named or implied.
// "Termin" alone is a Sygna deadline, "kto" a person here, "w umowie z X" one of our contracts.
const CHAT_TOPICWORD = /przepis|\bustaw|kodeks|\bprawo\b|prawn|przedawn|kar[aęy]\s+umown|wypowiedz|odstąpi|rękojm|odszkodowan|zadat|pracodawc|urlop|spadk|zachowek|orzecznictw|\blaws?\b|statut|case law/i;
const CHAT_FIRMWORD = /(?:^|[^\p{L}])(?:mamy|mam|nasz\p{L}*|moj\p{L}*|mój|kontrahent\p{L}*|klien\p{L}*|kancelari\p{L}*|kto|compass\p{L}*|sygn[aiy]e?|rejestr\p{L}*|w umowie|our|we)(?![\p{L}])/iu;
// "Które umowy przewidują kary umowne?", "Który prawnik prowadzi najwięcej spraw?": our records as the subject.
const CHAT_FIRMLIST = /(?:^|[^\p{L}])(?:któr|jaki|ile|pokaż|wymień)\p{L}*\s+(?:z\s+|wszystkie\s+)?(?:umowy|umów|sprawy|spraw|prawni\p{L}*)(?![\p{L}])/iu;
function chatRoute(question, contracts, named = 0) {
if (contracts.length && CHAT_LAWWORD.test(question) && CHAT_CHECKWORD.test(question) && !CHAT_CONTRACT_STATUS.test(question)) return 'contract_law_check';
function chatRoute(question, named = 0) {
if (chatCites(question).length) return 'law_cite';
return !named && CHAT_TOPICWORD.test(question) && !CHAT_FIRMWORD.test(question) && !CHAT_FIRMLIST.test(question) ? 'law_topic' : 'data';
}
// A whole act named without an article ("przepisy Kodeksu cywilnego", "zgodnie z RODO").
const CHAT_ACTS = new RegExp(CHAT_CODE + '|ustaw[a-ząćęłńóśźż]*\\s+Prawo\\s+[a-ząćęłńóśźż]+|\\bRODO\\b', 'gi');
// The citations in a contract's clauses, each with the clauses it stands in. A whole-act mention is
// looked for only outside the citations, so "art. 481 Kodeksu cywilnego" is not also one. Five letters
// per word keep the cases of one name together ("ustawy"/"ustawą Prawo przewozowe").
function chatExtractCites(clauses) {
const found = new Map();
const add = (cite, whole, label) => {
const k = whole ? cite.toLowerCase().split(/\s+/).map((w) => w.slice(0, 5)).join(' ') : cite.toLowerCase();
if (!found.has(k)) found.set(k, { cite, whole, clauses: [] });
const f = found.get(k);
if (label && !f.clauses.includes(label)) f.clauses.push(label);
};
for (const c of clauses) {
const text = String(c.text || '').replace(/\s+/g, ' ');
for (const cite of chatCites(text)) add(cite, false, c.label);
const rest = CHAT_CITES.reduce((s, re) => s.replace(re, ' '), text);
for (const m of rest.match(CHAT_ACTS) || []) add(m, true, c.label);
}
return [...found.values()];
}
const chatActName = (d) => (!d ? '' : /^Dz\.\s?U/.test(d.signature || '') ? d.signature : String(d.title || '').replace(/\s+z dnia[\s\S]*$/, ''));
const chatOff = (d) => !!d && ((d.extra || {}).in_force === 'NOT_IN_FORCE' || /uchylon|nieobowiązuj|wygaśnięcie/i.test(d.status || ''));
const chatBare = (d) => (d ? d.id.replace(/^[a-z_]+:/, '') : '');
// One citation's verdict. A whole act goes as its article 1: resolve takes no act name alone (422), and
// every code and EU act has an article 1, which answers for the act's status and current text.
async function chatCurrency(item, insider) {
const row = { ...item, label: item.cite };
const set = (verdict, ok, line) => Object.assign(row, { verdict, ok, line });
if (!insider) return set('nie sprawdzono', null, 'nie sprawdzono: brak dostępu do Insidera na tym koncie');
let r = null;
try { r = await askerGet('insider', 'resolve?citation=' + encodeURIComponent((item.whole ? 'art. 1 ' : '') + item.cite)); }
catch (ex) { if (ex.name === 'AbortError') throw ex; } // 422: Insider does not know this form
if (!r || !r.resolved) {
return set('nie sprawdzono', null, item.whole ? 'nie sprawdzono: Insider nie rozpoznaje tego aktu po samej nazwie' : 'nie sprawdzono: Insider nie rozpoznał tego odwołania');
}
const c = r.citation || {};
const cur = r.current_consolidated || (r.documents || [])[0];
const a = r.article;
row.act = c.kind === 'act' ? chatBare(r.base || r.cited) : (c.celex || c.eli || '');
if (cur) Object.assign(row, { inner: insiderInner(cur, !item.whole && a && a.located ? a : null), url: cur.official_url });
if (item.whole) {
row.label = (c.code || item.cite) + ', cały akt';
return chatOff(cur) ? set('akt nieobowiązujący', false, `akt nie obowiązuje (status: ${cur.status})`)
: set('aktualny', true, `wymieniony bez numeru artykułu; akt obowiązuje, obecny tekst: ${chatActName(cur)}`);
}
if (c.kind === 'act') {
const cited = r.cited || (r.documents || [])[0];
// base is set only when the cited document is itself a consolidated text; citing the act's original
// publication ("Dz. U. z 2018 r. poz. 1000 z późn. zm.") is the usual form and cites the act as amended.
if (r.base && r.current_consolidated && chatBare(cited) !== chatBare(r.current_consolidated)) {
return set('nieaktualny tekst jednolity', false, `umowa cytuje nieaktualny tekst jednolity ${chatActName(cited)} (status: ${cited.status}); obecny tekst jednolity to ${chatActName(r.current_consolidated)}`);
}
return chatOff(cited) ? set('akt nieobowiązujący', false, `akt nie obowiązuje (status: ${cited.status})`)
: set('aktualny', true, r.base || !r.current_consolidated ? 'to obecny tekst aktu, akt obowiązuje'
: `akt obowiązuje, obecny tekst jednolity: ${chatActName(r.current_consolidated)}`);
}
if (!a || !a.located) {
return a && a.reason === 'not_in_text' ? set('nie ma w obecnym tekście', false, `takiego artykułu nie ma w obecnym tekście (${chatActName(cur)})`)
: set('nie sprawdzono', null, 'nie sprawdzono: Insider nie ma teraz tekstu tego aktu');
}
if (chatOff(cur)) return set('akt nieobowiązujący', false, `akt nie obowiązuje (status: ${cur.status})`);
const head = chatClean(a.text).replace(/\s+/g, ' ');
// "(utracił moc)": struck down by the Constitutional Tribunal, as dead as a repealed one.
const gone = head.match(/^Art(?:ykuł|\.)?\s*\d+\w*\.?\s*\((uchylon|utracił moc|pominięt|skreślon)/i);
if (gone) {
const verdict = /^utrac/i.test(gone[1]) ? 'utracił moc' : 'uchylony';
return set(verdict, false, `${verdict.toUpperCase()}: w obecnym tekście (${chatActName(cur)}) artykuł brzmi „${head.slice(0, 40)}”`);
}
return set('aktualny', true, `aktualny: artykuł jest w obecnym tekście (${chatActName(cur)}), akt obowiązuje`);
}
// {record, view} for the answer, or {coded}: what code says itself when there is nothing to check.
async function chatReview(contract, index) {
const lib = await askerGet('compass', `contracts/${contract.key.split(':').pop()}/library`);
if (!lib) return { coded: `Nie mogę odczytać treści umowy ${contract.title}.` };
if (lib.state !== 'done') return { coded: `Umowa ${contract.title} nie jest jeszcze podzielona na klauzule (stan: ${lib.state || 'brak'}), więc nie sprawdzę jej przepisów.` };
const found = chatExtractCites(lib.clauses || []);
const rows = await Promise.all(found.slice(0, 10).map((x) => chatCurrency(x, index.law)));
// A whole act whose article the contract also cites is said by that article's line already.
const view = rows.filter((x) => !x.whole || !x.act || !rows.some((y) => !y.whole && y.act === x.act));
if (!view.length) return { coded: `W umowie ${contract.title} nie znalazłem odwołań do konkretnych przepisów ani aktów (są najwyżej ogólne, np. „przepisy prawa”).` };
const title = 'Przegląd aktualności przepisów w umowie ' + contract.title;
const at = (x) => x.clauses.length ? ` (${x.clauses.join(', ')})` : '';
return { view: { title, rows: view.map(({ label, clauses, verdict, ok, line, inner, url }) => ({ label, clauses, verdict, ok, line, inner, url })) },
record: { slug: 'compass', kind: 'przegląd', key: 'atrium:przeglad:' + contract.key, title, inner: contract.inner, members: [contract.key],
text: `${title}, sprawdzony w Insiderze w obecnych tekstach aktów, stan na ${new Date().toLocaleDateString('sv')}. Umowa powołuje się na ${view.length}: ` +
view.map((x, i) => `${i + 1}. ${x.label}${at(x)}: ${x.line}`).join('; ') + '.' +
(found.length > 10 ? ` Rozpoznano ${found.length} odwołań, sprawdzono pierwsze 10.` : '') +
' Lista obejmuje odwołania rozpoznane w treści umowy; zapisane w innej formie mogły zostać pominięte.' } };
}
/* A question about the law with no citation ("czy pracodawca może wypowiedzieć…"): one short call to the
chosen model names the act and rewords the question in the statute's words, code reads that act's whole
text from Insider and ranks its articles by word prefixes, then fetches the best three articles' text; the
@@ -2043,17 +1946,12 @@ async function chatTopic(question, index, onStatus, model) {
}
/* GraphRAG prawa (testy/czat-prawo/PROJEKT.md, ramię G, domyślnie wyłączone): obok przepisu, który czat już
pobrał, jego sąsiedztwo w grafie, a przy klauzulach umowy przepisy, do których klauzula prowadzi. Krawędzie:
pobrał, jego sąsiedztwo w grafie. Krawędzie:
odesłania z grafu Insidera (graph/references, ze zdaniem cytującym), struktura aktu (sąsiednie artykuły tej
samej jednostki: Kodeks cywilny odsyła numerami rzadko, 111 krawędzi na 1297 artykułów, więc o obniżeniu kary
z art. 483 mówi art. 484 obok, nie odesłanie) i klauzula → artykuł (typ klauzuli z biblioteki Compassu albo
odwołanie w jej tekście). Kod łączy, model czyta. */
z art. 483 mówi art. 484 obok, nie odesłanie). Kod łączy, model czyta. Klauzule umów (biblioteka Compassu)
odpadły wraz z umowami w Compassie: rejestr Galeny trzyma metadane umowy, nie jej podział na klauzule. */
const CHAT_UNIT_HEAD = /\n[\s#]*(?:KSIĘGA|TYTUŁ|DZIAŁ|Rozdział|Oddział)\b/;
// A clause type → the Civil Code's general articles on it. Types with no general Civil Code rule get no edge
// rather than a guessed one: poufność, RODO, spory, prawa autorskie, and termination (art. 365¹ binds only
// open-ended obligations, so on a fixed-term contract it would mislead).
const CHAT_CLAUSE_KC = { kary_umowne: ['kary umowne', ['483', '484']], odpowiedzialnosc: ['odpowiedzialność', ['471', '473']],
platnosci: ['płatności', ['481']], rekojmia_gwarancja: ['rękojmia i gwarancja', ['556', '558', '577']] };
const CHAT_REF_KIND = { ODSYLA_DO: 'odesłanie', STOSUJE_ODPOWIEDNIO: 'stosuje się odpowiednio', Z_ZASTRZEZENIEM: 'z zastrzeżeniem' };
const chatCaret = (n) => String(n).replace(/[⁰¹²³⁴⁵⁶⁷⁸⁹]+/, (x) => '^' + [...x].map((c) => '⁰¹²³⁴⁵⁶⁷⁸⁹'.indexOf(c)).join(''));
// The last article with that number: a t.j. opens with the promulgating notice's own Art. 1-4.
@@ -2088,58 +1986,32 @@ async function chatLawAround(seed, index, shown) {
(refLines.length ? refLines.join(' ') : `Art. ${own} nie odsyła numerem do innych przepisów.`) +
(rest.length ? ` Sąsiednie przepisy z tej samej części aktu: ${rest.map((a) => chatArtText(a, 1500)).join(' ')}` : '') };
}
async function chatClauseLaw(rec, index, shown) {
const lines = [];
const want = [];
for (const k of rec.picked || []) {
const typed = (k.types || []).filter((t) => CHAT_CLAUSE_KC[t]);
// Only the Civil Code's articles: another act's citation is chatReview's (is it current), not this graph's.
const cited = chatCites(k.text).filter((c) => /\bk\.?\s?c\b|cywiln/i.test(c)).map((c) => chatCaret((c.match(/\d+[⁰¹²³⁴⁵⁶⁷⁸⁹]*/) || [''])[0])).filter(Boolean);
const nums = [...new Set([...typed.flatMap((t) => CHAT_CLAUSE_KC[t][1]), ...cited])];
if (!nums.length) continue;
want.push(...nums);
lines.push(`${k.label}${typed.length ? ` (${typed.map((t) => CHAT_CLAUSE_KC[t][0]).join(', ')})` : ''} → ${nums.map((n) => 'art. ' + chatSup(n)).join(', ')}` +
(cited.length ? ` (klauzula sama powołuje ${cited.map((n) => 'art. ' + chatSup(n)).join(', ')})` : ''));
}
if (!lines.length) return null;
const doc = await chatActDoc('Kodeks cywilny');
if (!doc) return null;
const arts = await chatActArticles(doc, index);
const texts = [...new Set(want)].filter((n) => !shown.has(n)).slice(0, 5).map((n) => chatArtAt(arts, n)).filter(Boolean);
texts.forEach((a) => shown.add(a.num));
return { slug: 'insider', kind: 'przepis', key: 'insider:graf:' + rec.key, title: rec.title.replace(/^Klauzule/, 'Przepisy Kodeksu cywilnego do klauzul'),
inner: insiderInner(doc), url: doc.official_url, members: rec.members,
text: `Połączenia klauzul (${rec.title}) z Kodeksem cywilnym według typu klauzuli w bibliotece modułu Workflow albo odwołania w jej treści; to przepisy ogólne, umowa może się od nich różnić w granicach ustawy: ` +
lines.join('; ') + '. ' + texts.map((a) => chatArtText(a, 1200)).join(' ') };
}
async function chatLawGraph({ law, topic, clauses }, index) {
if (!index.law) return { near: [], clauses: [] };
async function chatLawGraph({ law, topic }, index) {
if (!index.law) return { near: [] };
const seeds = [...law.filter((r) => r.seed).slice(0, 2), ...topic.filter((r) => r.seed).slice(0, 1)];
// Articles the model already reads in full are not repeated.
const shown = new Set(seeds.map((r) => chatCaret(r.seed.num)));
const near = [];
for (const r of seeds) near.push(await chatLawAround(r.seed, index, shown));
const linked = [];
for (const c of clauses) linked.push(await chatClauseLaw(c, index, shown));
return { near: near.filter(Boolean), clauses: linked.filter(Boolean) };
return { near: near.filter(Boolean) };
}
async function chatIndex() {
const today = new Date().toLocaleDateString('sv');
const names = Object.fromEntries(((await askerGet('sygna', 'users')) || []).map((u) => [u.id, u.full_name]));
// Sygna's urgency summary takes Compass's contracts in, so both readers share one fetch.
const compass = chatCompass(today);
const parts = [['Workflow (umowy)', () => compass], ['Sygna (sprawy, terminy, klienci)',
async () => chatSygna(today, names, ((await compass) || []).filter((r) => r.contract).map((r) => r.contract))],
// Sygna's urgency summary takes the register's contracts in, so both readers share one fetch.
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)]];
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, Workflow, Sygna, Counsel, Galena)', 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)', 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. Sprawdza też, czy przepisy, na które powołuje się umowa z modułu Workflow, są aktualne. Szuka też przepisów po samym temacie pytania.') };
: '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.') };
const records = got.filter(Boolean).flat();
// "What happened lately" read as "what ends soon" until the dates of what was done were one record.
@@ -2196,10 +2068,10 @@ const CHAT_GRAPH_RULES = new Set(['id', 'nip', 'nazwa', 'nazwa_organizacji', 'na
const CHAT_VIA_RANK = { strona: 0, sprawa: 0, klient: 0, termin: 0, k1: 0, k2: 0, numer: 0, osoba: 0, id: 0, nip: 0,
nazwa: 1, nazwa_organizacji: 1, k3: 1, nazwa_bez_formy: 2, przedstawiciel: 3 };
const chatWeaker = (a, b) => (CHAT_VIA_RANK[b] > CHAT_VIA_RANK[a] ? b : a);
const CHAT_VIA_PL = { id: 'ten sam kontrahent z listy modułu Workflow', nazwa: 'ta sama nazwa', nazwa_organizacji: 'ta sama nazwa',
const CHAT_VIA_PL = { id: 'ten sam kontrahent z listy kontrahentów', nazwa: 'ta sama nazwa', nazwa_organizacji: 'ta sama nazwa',
nazwa_bez_formy: 'nazwa bez formy prawnej', przedstawiciel: 'strona umowy wg przedstawicieli' };
const CHAT_ID_PL = { nip: 'zgodny NIP', krs: 'zgodny KRS', regon: 'zgodny REGON', pesel: 'zgodny PESEL' };
const CHAT_KIND_MOD = { umowa: 'compass', sprawa: 'sygna', termin: 'sygna', strona: 'sygna', kancelaria: 'counsel', zlecenie: 'counsel',
const CHAT_KIND_MOD = { umowa: 'galena', sprawa: 'sygna', termin: 'sygna', strona: 'sygna', kancelaria: 'counsel', zlecenie: 'counsel',
projekt: 'galena', wersja: 'galena' };
// Another case of the same word: a closed list of Polish endings, never a prefix. A prefix rule made "Kodax"
@@ -2668,7 +2540,7 @@ const chatGraphNames = (text, ent, graph) => chatLexSpans(text, ent.lex, graph,
// Whether one named record has a link into another module: then it gets a short card of its links.
function chatLinkable(key, g) {
const kind = key.split(':')[1];
if (kind === 'umowa') return g.contractMatter.has(key) || (g.of.get(key) || []).some((id) => [...g.ent.get(id).mods].some((m) => m !== 'compass'));
if (kind === 'umowa') return g.contractMatter.has(key) || (g.of.get(key) || []).some((id) => [...g.ent.get(id).mods].some((m) => m !== 'galena'));
if (kind === 'zlecenie') return g.orderTarget.has(key);
if (kind === 'projekt') return g.projMatter.has(key);
if (kind === 'wersja') return (g.of.get(key) || []).some((id) => id.startsWith('sprawa:'));
@@ -2682,14 +2554,14 @@ function chatGraphAsk(ids, index) {
// One fact per candidate, counted by code: the module where it has the most records.
const fact = (e) => {
if (e.type === 'sprawa') { const c = e.client && g.ent.get(e.client); return `Sygna: sprawa${c ? ', klient ' + c.name : ''}`; }
const opts = [['Sygna', n(e, 'sygna:sprawa:'), (k) => `klient w ${chatPlural(k, 'sprawie', 'sprawach', 'sprawach')}`], ['Workflow', n(e, 'compass:umowa:'), chatUmowy],
const opts = [['Sygna', n(e, 'sygna:sprawa:'), (k) => `klient w ${chatPlural(k, 'sprawie', 'sprawach', 'sprawach')}`], ['Galena', n(e, 'galena:umowa:'), chatUmowy],
['Galena', n(e, 'galena:projekt:'), (k) => chatPlural(k, 'projekt dokumentów', 'projekty dokumentów', 'projektów dokumentów')],
['Counsel', n(e, 'counsel:zlecenie:'), (k) => chatPlural(k, 'zlecenie', 'zlecenia', 'zleceń')]];
const best = opts.reduce((a, b) => (b[1] > a[1] ? b : a));
return best[1] ? `${best[0]}: ${best[2](best[1])}` : e.rec ? 'Sygna: klient bez spraw' : e.type === 'osoba' ? 'osoba z zespołu' : 'bez rekordów';
};
// The anchor record of each candidate, so "ta pierwsza" next turn resolves through chatResolveRefs.
const anchor = (e) => e.rec || [...e.recs.keys()].find((k) => k.startsWith('compass:umowa:')) || null;
const anchor = (e) => e.rec || [...e.recs.keys()].find((k) => k.startsWith('galena:umowa:')) || null;
const noun = cands.every((e) => e.type === 'sprawa') ? 'którą sprawę' : cands.every((e) => e.person) ? 'którą osobę' : 'którą firmę';
// Two candidates of one name: writing the full name again would only bring the same question back.
const ORD = ['pierwsza', 'druga', 'trzecia', 'czwarta', 'piąta', 'szósta'];
@@ -2769,7 +2641,7 @@ function chatCardLines(e, index, today, kind) {
const items = new Map(((index.byKey.get('sygna:terminy') || {}).items || []).map((d) => [d.key, d]));
// The days and groups of the urgency summary itself, so the card and "sygna:terminy" never disagree.
const dls = get('sygna:termin:').map((r) => items.get(r.key)).filter(Boolean).sort((a, b) => S(a.due_date).localeCompare(S(b.due_date)));
const contracts = get('compass:umowa:').sort((a, b) => (a.contract.ends_on || '9999').localeCompare(b.contract.ends_on || '9999') || S(a.contract.number).localeCompare(S(b.contract.number)));
const contracts = get('galena:umowa:').sort((a, b) => (a.contract.ends_on || '9999').localeCompare(b.contract.ends_on || '9999') || S(a.contract.number).localeCompare(S(b.contract.number)));
const projects = get('galena:projekt:').sort((a, b) => S(a.project.name).localeCompare(S(b.project.name), 'pl'));
const versions = get('galena:wersja:').sort((a, b) => S(a.draft.created_at).localeCompare(S(b.draft.created_at)));
const orders = get('counsel:zlecenie:').sort((a, b) => S(a.order.reference).localeCompare(S(b.order.reference)));
@@ -2808,9 +2680,9 @@ function chatCardLines(e, index, today, kind) {
}).join('; ') + '.' : `: ${kind === 'osoba' ? 'brak, ta osoba nie odpowiada za żaden niewykonany termin' : 'brak niewykonanych terminów w ' + (kind === 'sprawa' ? 'tej sprawie' : 'sprawach tego podmiotu')}.`));
out.total.push(`${chatPlural(dls.length, 'termin niewykonany', 'terminy niewykonane', 'terminów niewykonanych')}${dls.length ? ` (po terminie: ${dls.filter((d) => d.days_left < 0).length})` : ''}`);
}
// Compass
if (kind === 'osoba') L('Workflow: umowy nie mają w danych osoby odpowiedzialnej, więc ich tu nie ma.');
else if (chatCardBlind(index, 'compass')) L('Workflow: od podziału Compassu moduł nie przechowuje umów, więc czat ich tu nie pokazuje.');
// Galena's contract register
if (kind === 'osoba') L('Rejestr umów (Galena): umowy nie mają w danych osoby odpowiedzialnej, więc ich tu nie ma.');
else if (chatCardBlind(index, 'rejestr')) L('Rejestr umów (Galena): brak dostępu na tym koncie, umów nie widzę.');
else {
const sums = new Map();
for (const r of contracts) if (r.contract.value_amount) sums.set(r.contract.value_currency, (sums.get(r.contract.value_currency) || 0) + Number(r.contract.value_amount));
@@ -2820,11 +2692,11 @@ function chatCardLines(e, index, today, kind) {
return `${c.number} „${c.name}”, kontrahent ${c.counterparty || 'brak'}${why(r).length ? ` (powiązanie: ${why(r).join('; ')})` : ''}, status ${c.status}, ` +
`${c.value_amount ? `wartość ${chatMoney(c.value_amount)} ${c.value_currency}` : 'bez wartości'}, ${c.ends_on ? `kończy się ${c.ends_on}, ${d >= 0 ? 'za ' + d + ' dni' : -d + ' dni temu'}` : 'bez daty końca'}`;
};
const head = kind === 'sprawa' ? 'Workflow, umowy przypisane do tej sprawy' : 'Workflow, umowy';
const head = kind === 'sprawa' ? 'Rejestr umów (Galena), umowy przypisane do tej sprawy' : 'Rejestr umów (Galena), umowy';
L(contracts.length ? `${head} (${contracts.length}), łączna wartość ${[...sums].map(([cur, s]) => `${chatMoney(s)} ${cur}`).join(' i ') || 'nieokreślona'}, od najwcześniej kończącej się: ` +
chatCap(contracts.map(item), contracts.map((r) => r.contract.number)) + '.'
: `${head} (0): ${kind === 'sprawa' ? 'brak, w module Workflow żadna widoczna umowa nie jest przypisana do tej sprawy' : 'brak, żadna widoczna umowa nie jest połączona z tym podmiotem po NIP, numerze sprawy ani pełnej nazwie'} (w rejestrze na tym koncie: ${chatUmowy(visible('umowa'))}).`);
out.total.push(`${chatUmowy(contracts.length)} w module Workflow${contracts.length ? ` (${counts(contracts, (r) => r.contract.status)})` : ''}`);
: `${head} (0): ${kind === 'sprawa' ? 'brak, w rejestrze umów żadna widoczna umowa nie jest przypisana do tej sprawy' : 'brak, żadna widoczna umowa nie jest połączona z tym podmiotem po NIP, numerze sprawy ani pełnej nazwie'} (w rejestrze na tym koncie: ${chatUmowy(visible('umowa'))}).`);
out.total.push(`${chatUmowy(contracts.length)} w rejestrze umów Galeny${contracts.length ? ` (${counts(contracts, (r) => r.contract.status)})` : ''}`);
}
// Galena
if (chatCardBlind(index, 'galena')) L('Galena: brak dostępu na tym koncie, dokumentów nie widzę.');
@@ -2909,7 +2781,7 @@ function chatCard(entId, index, today, { table = false, ja = false } = {}) {
const others = (prefix, num) => [...c.recs.keys()].filter((k) => k.startsWith(prefix) && !e.recs.has(k)).map((k) => index.byKey.get(k)).filter(Boolean)
.sort((a, b) => String(num(a) || '').localeCompare(String(num(b) || '')));
const ms = others('sygna:sprawa:', (r) => r.matter.reference);
const cs = others('compass:umowa:', (r) => r.contract.number);
const cs = others('galena:umowa:', (r) => r.contract.number);
const os = others('counsel:zlecenie:', (r) => r.order.reference);
const list = (rs, num) => (rs.length ? ` (${rs.map(num).join(', ')})` : '');
lines.push(chatNoBrackets(`Klient tej sprawy, ${c.name}, ma także: ${chatPlural(ms.length, 'inną sprawę', 'inne sprawy', 'innych spraw')}${list(ms, (r) => r.matter.reference)}, ` +
@@ -2921,7 +2793,7 @@ function chatCard(entId, index, today, { table = false, ja = false } = {}) {
const lead = parts.lead.filter((r) => r.key !== e.rec);
const out = { rec, lead, members, names: (r) => chatGraphNames(r.title || '', e, g), table: { head: [], rows: [] } };
if (table) {
const MOD = { sygna: 'Sygna', compass: 'Workflow', galena: 'Galena', counsel: 'Counsel' };
const MOD = { sygna: 'Sygna', galena: 'Galena', counsel: 'Counsel' };
const items = new Map(((index.byKey.get('sygna:terminy') || {}).items || []).map((d) => [d.key, d]));
const row = (r) => {
const why = (e.why.get(r.key) || []).join('; ') || '-';
@@ -2953,7 +2825,7 @@ function chatLinkCard(recKey, index, today) {
// What a podmiot has besides `except`: its matters, other contracts and orders.
const about = (e, except) => {
const ms = recsOf(e, 'sygna:sprawa:').filter((x) => !except.includes(x.key)).map(seen);
const cs = recsOf(e, 'compass:umowa:').filter((x) => !except.includes(x.key)).map(seen);
const cs = recsOf(e, 'galena:umowa:').filter((x) => !except.includes(x.key)).map(seen);
const os = recsOf(e, 'counsel:zlecenie:').filter((x) => !except.includes(x.key)).map(seen);
const parts = [ms.length ? `jest klientem w ${chatPlural(ms.length, 'sprawie', 'sprawach', 'sprawach')} w Sygnie: ${ms.map(matter).join('; ')}` : 'nie jest klientem w żadnej sprawie widocznej w Sygnie'];
const more = [];
@@ -2966,8 +2838,8 @@ function chatLinkCard(recKey, index, today) {
const out = ps.map((e) => `kontrahent ${e.name} (powiązanie: ${(e.why.get(c.key) || []).join('; ')}) ${about(e, [c.key, ...except])}`);
const mk = g.contractMatter.get(c.key);
// Not assigned is said only when the field is empty: assigned to a matter the asker cannot see leaves no trace.
if (mk) out.push(`umowa jest przypisana w module Workflow do sprawy ${matter(seen(index.byKey.get(mk)))}`);
else if (!c.contract.matter_ref) out.push('umowa nie jest przypisana do sprawy w module Workflow');
if (mk) out.push(`umowa jest przypisana w rejestrze umów do sprawy ${matter(seen(index.byKey.get(mk)))}`);
else if (!c.contract.matter_ref) out.push('umowa nie jest przypisana do sprawy w rejestrze umów');
return out;
};
const matterLinks = (m, except) => {
@@ -3042,7 +2914,7 @@ function chatSearch(records, question) {
// ponytail: a module's keywords, enough for four modules; more modules want a question classifier.
const CHAT_BLIND_WORDS = {
'Workflow (umowy)': ['umowa', 'umowy', 'umów', 'umowę', 'umowi', 'kontr', 'contr', 'wygas'],
'Rejestr umów (Galena)': ['umowa', 'umowy', 'umów', 'umowę', 'umowi', 'kontr', 'contr', 'wygas'],
'Counsel Scorecard (kancelarie zewnętrzne, oceny)': ['zewnę', 'ocena', 'ocenę', 'oceny', 'ocen', 'ranki', 'score'],
};
// What the code answers itself: told the asker had no access, the model still said "there is none".
@@ -3640,43 +3512,8 @@ function chatByParty(question, recs) {
}
return [...hits];
}
// A question about what to do with a contract or what to watch in it is answered from its text: the clauses
// from Compass's library. Asked "co trzeba zrobić" with only the register row, the model invented advice
// ("aby uniknąć automatycznego wygaśnięcia") for a contract that has no renewal clause at all.
// "Co zrobić przed końcem", "przedłużenie": a question about acting on an expiring contract.
const CHAT_ACT = /co\s+(?:\p{L}+\s+){0,3}?(?:zrobi|zrób|przygotow)|przed\s+(?:jej\s+|jego\s+)?(?:końc|upływ|wygaś)|przedłuż|wypowi|rozwiąz|odstąp|jak\s+(?:ją|go)\b|krok|what\s+(?:should|to\s+do)|before\s+(?:it\s+)?end|renew|terminat|next\s+step/iu;
const CHAT_RISK = /uważ|ryzyk|pułapk|niekorzyst|zagroż|haczyk|watch\s+out|risk|red\s+flag|pitfall/iu;
// Term, renewal, notice, termination and what follows the end; penalties after them.
const CHAT_END_CLAUSE = [/nieprzedłuż|przedłuż/iu, /wypowi|rozwiąz|odstąp/iu, /zawart\p{L}*\s+na\s+(?:okres|czas)|okres\p{L}*\s+\d+\s+miesi|w\s+terminie\s+do\s+\d/iu,
/po\s+zakończeni|po\s+upływie|wygas/iu, /kar\p{L}*\s+umown/iu];
// "Czy kary umowne w umowie z Zawadą są ograniczone?": a content question about one contract, answered from
// the clauses on that subject. With the register row only, the model said "nie znalazłem" (§ 5 ust. 1 says it).
const CHAT_CLAUSE_TOPICS = ['kar', 'odpowiedzialn', 'poufn', 'tajemnic', 'płatn', 'wynagrodz', 'faktur', 'gwarancj', 'rękojm',
'odbi', 'odbior', 'ubezpiecz', 'zabezpiecz', 'podwykonaw', 'penalt', 'liabil', 'confidential', 'payment', 'warrant']
.map((s) => new RegExp(`(?<![\\p{L}])${s}`, 'iu'));
// "na 90 dni przed upływem": the last day for that notice, counted in code from the register's end date, so
// the model need not do date arithmetic ("musisz złożyć" for a window that closed in August).
function chatNoticeBy(text, end, today) {
const m = end && String(text).match(/na\s+(\d{1,3})\s+(dni|miesi\p{L}*)\s+przed/iu);
if (!m) return '';
const d = new Date(end + 'T00:00:00Z');
if (/^dni/i.test(m[2])) d.setUTCDate(d.getUTCDate() - Number(m[1])); else d.setUTCMonth(d.getUTCMonth() - Number(m[1]));
const by = d.toISOString().slice(0, 10);
return ` [Wyliczone: przy końcu z rejestru ${end} ostatni dzień na to oświadczenie to ${by}; ${by < today ? 'ten dzień już minął, więc oświadczenie złożone teraz byłoby po terminie z tej klauzuli' : 'zostało ' + chatDays(by, today) + ' dni'}.]`;
}
async function chatClauses(rec, risk, per, topics = []) {
const c = rec.contract;
const lib = await askerGet('compass', `contracts/${c.id}/library`);
const head = `Klauzule z treści umowy ${c.number} „${c.name}” (kontrahent ${c.counterparty || 'brak'}; w rejestrze koniec ${c.ends_on || 'brak daty'})`;
const base = { slug: 'compass', kind: 'klauzule', key: 'compass:klauzule:' + c.id, title: `Klauzule umowy ${c.number} ${c.name}`, inner: rec.inner, members: [rec.key] };
if (!lib || lib.state !== 'done') return { ...base, text: `${head}: treść umowy nie jest jeszcze podzielona na klauzule, więc jej warunków nie znam.` };
const all = lib.clauses || [];
const picked = risk ? all : topics.length ? all.filter((k) => topics.some((re) => re.test(k.text))) : CHAT_END_CLAUSE.flatMap((re) => all.filter((k) => re.test(k.text)));
const today = new Date().toLocaleDateString('sv');
const lines = [...new Set(picked)].slice(0, per).map((k) => `${k.label}: ${String(k.text).replace(/\s+/g, ' ').replace(/^\d+\.\s*|^§\s*\d+\s*/, '').trim().slice(0, risk ? 260 : 320)}` +
chatNoticeBy(k.text, c.ends_on, today));
return { ...base, picked: [...new Set(picked)].slice(0, per), text: lines.length ? `${head}, wybrane do pytania:\n` + lines.join('\n')
: `${head}: w treści umowy nie znalazłem postanowień ${topics.length ? 'na temat z pytania' : 'o okresie obowiązywania, przedłużeniu, wypowiedzeniu ani karach umownych'}.` };
}
// A recommendation question gets told the shape of a useful answer; a lookup question keeps its plain one.
// "Najcenniejsza" is a lookup: told to add a next step, the model borrowed the example's § 4 ust. 2.
// Not a risk question: squeezed into "Najpierw X, bo …", "na co uważać" got payment terms called a risk.
@@ -3690,13 +3527,13 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
// the full map (true) cost Qwen its "nie ma" answers twice. false switches the map off entirely.
// ja: the asker's own card for "co mam na głowie" (testy/czat-graf/RUNDA4.md: passed on Qwen and Bielik); false switches it off.
graf = chat.graf ?? 'osoba', ja = chat.ja ?? true,
// prawo: the law graph beside the cited article and the contract's clauses (testy/czat-prawo/PROJEKT.md: passed on
// prawo: the law graph beside the cited article (testy/czat-prawo/PROJEKT.md: passed on
// Qwen and Bielik, 12.11); false switches it off.
prawo = chat.prawo ?? true }) {
const done = (content, extra = {}) => Object.assign(answer, { content, status: '', ...extra });
try {
// "Umowa o dzieło" in a question about the law is not a question about Compass's contracts.
const coded = chatRoute(question, []) === 'law_topic' ? null : chatRefusal(index, question);
// "Umowa o dzieło" in a question about the law is not a question about the register's contracts.
const coded = chatRoute(question) === 'law_topic' ? null : chatRefusal(index, question);
if (coded) return done(coded, { coded: 'refusal' });
// A turn that failed its check still named its records (kept in `mentioned`): "ta umowa" after it means them.
const at = turns.map((t) => t.role === 'assistant' && !t.aborted && (!t.failed || !!(t.mentioned && t.mentioned.length))).lastIndexOf(true);
@@ -3736,8 +3573,8 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
} else if (!named.length && !resolved.length && /wygas|kończ\p{L}*\s+się|expir|ending/iu.test(question) && CHAT_ACT.test(question)
&& (chatCount(question) === 1 || /(?<![\p{L}])first(?![\p{L}])/iu.test(question))) {
// "Which expiring contract first, and what does its renewal clause say?": the expiring ones are "z nich",
// so code ranks them and fetches the picked one's clauses instead of the model guessing at a register row.
const win = index.byKey.get('compass:wygasajace:90');
// so code ranks them instead of the model guessing at a register row.
const win = index.byKey.get('galena:wygasajace:90');
back = ((win && win.members) || []).map((k) => index.byKey.get(k)).filter(Boolean).slice(0, 8);
}
// "Która z nich najważniejsza": the contracts ranked by value in code. Left to compare, the model called a
@@ -3746,13 +3583,11 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
const today = new Date().toLocaleDateString('sv');
const byVal = [...cs].sort((a, b) => Number(b.value_amount || 0) - Number(a.value_amount || 0));
const byEnd = cs.filter((c) => c.ends_on).sort((a, b) => a.ends_on.localeCompare(b.ends_on)).concat(cs.filter((c) => !c.ends_on));
const backSum = cs.length > 1 ? [{ slug: 'compass', kind: 'zestawienie', key: 'compass:z-nich', title: 'Umowy z poprzedniej odpowiedzi według wartości', inner: 'contracts', members: back.map((r) => r.key),
const backSum = cs.length > 1 ? [{ slug: 'galena', kind: 'zestawienie', key: 'galena:z-nich', title: 'Umowy z poprzedniej odpowiedzi według wartości', inner: 'cards', members: back.map((r) => r.key),
text: `Najwyższą wartość ma ${byVal[0].number} (${byVal[0].value_amount ? chatMoney(byVal[0].value_amount) + ' ' + byVal[0].value_currency : 'bez wartości'}), najwcześniej kończy się ${byEnd[0].number} (${byEnd[0].ends_on || 'bez daty końca'}). ` +
'Umowy wymienione w poprzedniej odpowiedzi, od najwyższej wartości (bez przeliczania walut): ' + byVal
.map((c, i) => `${i + 1}. ${c.number} ${c.name} (${c.counterparty || 'brak'}): ${c.value_amount ? chatMoney(c.value_amount) + ' ' + c.value_currency : 'bez wartości'}, ` +
(c.ends_on ? `kończy się ${c.ends_on}, za ${chatDays(c.ends_on, today)} dni` : 'bez daty końca')).join('; ') + '.' }] : [];
const focus = [...named, ...resolved].filter((r) => r.kind === 'umowa');
let review = [];
let topic = [];
// Computed on both arms: on A it only records whether B would have had a card (coverage without extra turns).
let gt = null;
@@ -3762,8 +3597,8 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
// "Wypowiedzenie umowy z Velmora Pompy" names a client, so it is a data question, not one for Insider. A name
// read from one word ("Energii", "Zielonej Górze") never takes a question off Insider, and a question that
// stays with the law gets no card, so it gets no question back either.
const route0 = chatRoute(question, focus, named.length + resolved.length);
const route1 = chatRoute(question, focus, named.length + resolved.length + 1);
const route0 = chatRoute(question, named.length + resolved.length);
const route1 = chatRoute(question, named.length + resolved.length + 1);
const usable = !!(graf && gt && route1 === 'data' && (route0 === 'data' || gt.hit !== 'czesciowe'));
if (usable && gt.ask) return done(gt.ask, { coded: 'ask', mentioned: gt.mentioned, graf: gt });
const route = usable && (gt.root || gt.link) ? route1 : route0;
@@ -3787,29 +3622,12 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
if (t.coded) return done(t.coded, { coded: 'topic' });
topic = t.records;
}
if (route === 'contract_law_check') {
answer.status = 'Sprawdzam przepisy umowy w Insiderze…';
onUpdate(answer);
const rv = await chatReview(focus[0], index);
if (rv.coded) return done(rv.coded, { coded: 'review', mentioned: [focus[0].key] });
answer.review = rv.view;
review = [rv.record];
}
const law = await chatLaw(question, index);
const cands = [...named, ...resolved, ...back].filter((r) => r.kind === 'umowa' && r.contract);
const risk = CHAT_RISK.test(question);
const topics = cands.length === 1 ? CHAT_CLAUSE_TOPICS.filter((re) => re.test(question)) : [];
// "Która z nich": only the top by value and the first to end get their clauses, in full. Two clauses each for
// seven contracts cut the ones a lawyer acts on (UM-2026-0007's overdue delivery and its withdrawal right).
const top = back.length > 2 ? [byVal[0], byEnd[0]].map((c) => cands.find((r) => r.contract === c)).filter((r, i, a) => r && a.indexOf(r) === i) : cands.slice(0, 8);
// One contract: its whole text for a risk question, the clauses on the asked subject or its end clauses.
const clauses = route === 'data' && cands.length && (risk || topics.length || CHAT_ACT.test(question))
? await Promise.all(top.map((r) => chatClauses(r, risk && top.length === 1, top.length > 2 ? 2 : top.length > 1 ? 8 : risk ? 30 : 10, topics))) : [];
// A fault in the law graph leaves the turn as without it.
let lawGraph = { near: [], clauses: [] };
let lawGraph = { near: [] };
if (prawo) {
try { lawGraph = await chatLawGraph({ law, topic, clauses }, index); } catch (ex) { if (ex.name === 'AbortError') throw ex; console.warn('law graph off:', ex); }
answer.prawo = [...lawGraph.near, ...lawGraph.clauses].map((r) => r.key);
try { lawGraph = await chatLawGraph({ law, topic }, index); } catch (ex) { if (ex.name === 'AbortError') throw ex; console.warn('law graph off:', ex); }
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 : ''));
@@ -3822,17 +3640,17 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
// szkicu" still needs the register (testy/czat-graf/RUNDA4.md; cutting them all failed in RUNDA3.md).
if (card && card.rec.kind === 'karta') {
const top = found.top;
found = Object.assign(found.filter((r) => card.members.has(r.key) || card.names(r) || (gt.ja && r.key.startsWith('compass:'))), { 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 });
}
const seen = new Set();
const pick = review.length || law.length || topic.length || named.length || resolved.length || back.length || card ? null : chatPick(question, index);
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: [] });
// The entity's card right after law and topic; a one-record link card behind its record, so [1] stays the record.
const sources = [...(pick ? [pick.rec] : []), ...review, ...law, ...topic, ...lawGraph.near,
const sources = [...(pick ? [pick.rec] : []), ...law, ...topic, ...lawGraph.near,
...(card && card.rec.kind === 'karta' ? [card.rec] : []), ...named, ...resolved,
...(card && card.rec.kind !== 'karta' ? [card.rec] : []), ...backSum, ...back, ...clauses, ...lawGraph.clauses, ...chatCarry(prev, index),
...(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)).slice(0, CHAT_TOP + law.length + review.length + topic.length + clauses.length + lawGraph.near.length + lawGraph.clauses.length);
.filter((r) => !seen.has(r.key) && seen.add(r.key)).slice(0, CHAT_TOP + law.length + topic.length + lawGraph.near.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 });
@@ -3843,14 +3661,12 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
const about = [...resolved, ...(card && card.rec.kind === 'karta' ? [card.rec] : [])].map((r) => `[${sources.indexOf(r) + 1}] ${r.title}`);
const count = pick ? null : chatCount(question);
const want = count || pick || card ? null : chatListFor(sources, question);
// Without it the model named only what failed and called "the rest" current, hiding which the rest were.
const hint = review.length ? '\n(Odpowiedz listą: każdy przepis z przeglądu [1] w osobnym punkcie, z jego oceną, także te aktualne.)'
// The search matches words, so a found article may not answer; the model says which one does, or none.
: topic.length ? '\n(Przepisy w źródłach znalazła wyszukiwarka Insidera po słowach pytania i nie każdy musi pasować. Odpowiedz tylko z tych, które odpowiadają na pytanie, podając numer artykułu i ustawę; jeśli żaden nie odpowiada, napisz, że nie znalazłem przepisu, który odpowiada na pytanie.' +
// The search matches words, so a found article may not answer; the model says which one does, or none.
const hint = topic.length ? '\n(Przepisy w źródłach znalazła wyszukiwarka Insidera po słowach pytania i nie każdy musi pasować. Odpowiedz tylko z tych, które odpowiadają na pytanie, podając numer artykułu i ustawę; jeśli żaden nie odpowiada, napisz, że nie znalazłem przepisu, który odpowiada na pytanie.' +
(topic.some((r) => r.kind === 'orzeczenie') ? ' Orzeczenia to tylko przykłady z orzecznictwa, nie przesądzają sprawy.' : '') + ')'
// Models dropped items of a listed group (2 of 6 overdue deadlines): told the count, they mostly list all.
: pick ? `\n(Źródło [1] to lista wybrana przez system (${chatPlural(pick.table.rows.length, 'pozycja', 'pozycje', 'pozycji')}). Pod Twoją odpowiedzią pokaże się jako tabela z datami, osobami i następnymi krokami, więc jej nie przepisuj. Napisz 1-4 zdania: co jest na pierwszym miejscu i dlaczego, z [1]; jeśli na liście jest kilka pozycji po terminie, wymień każdą z nich; nie dodawaj pozycji spoza listy i nie zmieniaj kroków. Jeśli lista jest pusta, napisz, że takich pozycji nie ma.)`
: want && want.keys.length > 1 && want.keys.every((k) => k.startsWith('compass:umowa:')) ? `\n(Źródło [${want.n}] wymienia ${chatPlural(want.keys.length, 'umowę', 'umowy', 'umów')}. Pod Twoją odpowiedzią pokażą się jako tabela z datami i wartościami, więc ich nie przepisuj. Napisz 1-2 zdania: ile ich jest i która kończy się najwcześniej, z [${want.n}].)`
: want && want.keys.length > 1 && want.keys.every((k) => k.startsWith('galena:umowa:')) ? `\n(Źródło [${want.n}] wymienia ${chatPlural(want.keys.length, 'umowę', 'umowy', 'umów')}. Pod Twoją odpowiedzią pokażą się jako tabela z datami i wartościami, więc ich nie przepisuj. Napisz 1-2 zdania: ile ich jest i która kończy się najwcześniej, z [${want.n}].)`
: want ? `\n(Źródło [${want.n}] wymienia ${chatPlural(want.keys.length, 'pozycję', 'pozycje', 'pozycji')}${want.labels.length ? ' (' + want.labels.join(', ') + ')' : ''}: wymień wszystkie${want.labels.length > 1 ? ', w każdej grupie osobno, z nazwą grupy' : ''}.)` : '';
// The hints are Polish, and with them an English question got a Polish answer.
const en = chatIsEn(question);
@@ -3868,9 +3684,7 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
// The § slot only for a clause: for a deadline the model wrote "(§ nie podany w źródłach)" or made one up.
'Wzór formy, nie treści: „Najpierw <umowa albo termin>, bo <fakt ze źródła> [n]. Następny krok: <czynność z klauzuli albo źródła> [n].” ' +
'Oznaczenie § dopisz tylko wtedy, gdy krok wynika z klauzuli umowy w źródłach; przy terminie podaj jego podstawę prawną ze źródła, jeśli ją ma. ' +
'Jeśli źródła nie pozwalają ocenić, co ważniejsze albo co zrobić, napisz to wprost zamiast zgadywać. Krótko.)' : '') +
(risk && clauses.length ? '\n(Wymień ryzykowne klauzule, każdą w jednym wierszu: jej §, na czym polega ryzyko i którą stronę obciąża. Klauzuli, która chroni nas, nie nazywaj ryzykiem. Krótko.)' : '') +
(clauses.length ? '\n(Warunki umowy bierz tylko z klauzul w źródłach i podawaj ich oznaczenie §; czego w klauzulach nie ma, tego nie twierdź.)' : '');
'Jeśli źródła nie pozwalają ocenić, co ważniejsze albo co zrobić, napisz to wprost zamiast zgadywać. Krótko.)' : '');
const messages = chatMessages(index.blind, question, sources, chatHistory(turns, answer.refs), about, hint + shape + chatCardHint(card, sources, graf));
const round = async (msgs) => {
const got = await chatRound(model, msgs, answer, onUpdate);
@@ -3906,7 +3720,7 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
if (!cited.length &&!/nie znalazłem|nie masz dostępu|nie mam dostępu|pomagam|did not find|could not find|couldn't find|no access|don't have access/i.test(text)) {
// Uncited and nothing in the data matched the question well (a poem, small talk): out of scope, said by
// code. Uncited although records matched stays an error: that answer came from the model's memory.
if (!named.length && !resolved.length && !law.length && !review.length && !topic.length && found.top < CHAT_OFFTOPIC && !card) {
if (!named.length && !resolved.length && !law.length && !topic.length && found.top < CHAT_OFFTOPIC && !card) {
return done(CHAT_SCOPE, { coded: 'refusal', refs: [], verify: [] });
}
throw new Error(_tr('model odpowiedział bez wskazania źródła, czyli z pamięci. Zapytaj jeszcze raz albo inaczej.'));