czat: mapa podmiotów - runda poprawek po przeglądzie

- R5: firma znana tylko z przedstawicieli nie łączy się po nazwie bez formy
- nazwa z tekstu równa wpisowi z listy kontrahentów nie tworzy osobnego nośnika;
  nośnik tekstowy w grupie z dwoma NIP-ami rozbity per umowa
- rozpoznanie: trafienie częściowe tylko pierwszym słowem rdzenia (plus wpis loose
  dla długich rdzeni), obce słowo z wielkiej litery obok blokuje trafienie,
  przebieg częściowy także obok trafienia pełnego (dwie encje)
- dopytanie zwraca kolejność kandydatów; "ta druga/pierwsza" w następnej turze
  przypina właściwego kandydata (pin); przy identycznych nazwach prosi o numer
- trasa: +1 do liczby nazwanych tylko gdy mapa daje kartę i trafienie nie jest
  częściowe na pytaniu o prawo; dopytanie nie zabiera pytań o prawo
- wyjątek w budowie karty wyłącza mapę w tej turze, nie wywraca czatu;
  sortowania odporne na brak pól
- karta sprawy: inne umowy/sprawy klienta posortowane po numerze

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqFLC3q51VqQzdfk12g
This commit is contained in:
tobayah
2026-11-11 03:28:08 +01:00
co-authored by Claude Opus 5.5
parent 1bf95309fd
commit a6114a1c36
+94 -30
View File
@@ -2358,9 +2358,12 @@ function chatGraph(records, names, today) {
setIds(x, cp);
x.att.push({ rec: r.key, how: 'lista' });
}
// The text names the same counterparty as the contract's own list: the list is the surer carrier. A text
// carrier beside it was shared by every contract of that name, so two firms of one name and two NIPs met in it.
const listed = new Set((c.counterparties || []).map((cp) => chatMatchKey(cp.name)).filter(Boolean));
for (const piece of String(c.counterparty || '').split('; ')) {
const k = chatMatchKey(piece);
if (k) carrier('n:' + k, piece.trim(), typeOf(k)).att.push({ rec: r.key, how: 'tekst' });
if (k && !listed.has(k)) carrier('n:' + k, piece.trim(), typeOf(k)).att.push({ rec: r.key, how: 'tekst' });
}
if (!on('przedstawiciel')) continue;
// "Jan Nowicki (Członek Zarządu, Ortolan Logistyka S.A.)": the firm is the last part in the closing brackets,
@@ -2433,6 +2436,9 @@ function chatGraph(records, names, today) {
const formed = new Map();
for (const c of carriers.values()) {
if (c.type !== 'org' || !chatHasForm(c.mk)) continue;
// R5: a firm known only from a contract's representatives joins by R2/R3 alone, so it is no target for a
// bare name. A group it shares with a real carrier is still found through that one.
if (!c.party && !c.list && c.att.length && c.att.every((a) => a.how === 'przedstawiciel')) continue;
const core = chatCoreKey(c.mk);
if (!formed.has(core)) formed.set(core, new Map());
if (!formed.get(core).has(uf2.find(c.key))) formed.get(core).set(uf2.find(c.key), c.key);
@@ -2459,6 +2465,20 @@ function chatGraph(records, names, today) {
}
const broken = (k) => ID_KINDS.some((t) => compIds.get(comp.find(p1.get(k)))[t].size > 1);
for (const e of named) if (!broken(e.a)) join(e.a, e.b, e.via, CHAT_VIA_PL[e.via]);
// A text name in a group split by two NIPs may be either firm: each contract keeps a carrier of its own, so the
// name does not gather both firms' contracts under one entity with no NIP. Such a carrier joined nothing above.
for (const k of keys.filter((x) => x.startsWith('n:') && broken(x))) {
const c = carriers.get(k);
const recs = [...new Set(c.att.map((a) => a.rec))];
if (recs.length < 2) continue;
carriers.delete(k);
keys.splice(keys.indexOf(k), 1);
for (const rec of recs) {
const x = { ...c, key: `${k}@${rec}`, att: c.att.filter((a) => a.rec === rec) };
carriers.set(x.key, x);
keys.push(x.key);
}
}
// ---- entities ----
const ent = new Map();
@@ -2620,8 +2640,14 @@ function chatGraph(records, names, today) {
}
}
if (e.person || !on('czesciowe')) continue;
const own = [...cores].flatMap(words);
for (const core of cores) {
for (const w of words(core)) if (w.length >= 5 && !/\d/.test(w) && !generic.test(w) && !first.has(w)) put({ toks: [w], ent: e.id, full: false });
// Only the first word, the one that tells the firm apart (Velmora, Ortolan). A later one is mostly a common
// word as well ("Development", "Systems", "Pompy", "Energii"): it gave a law question a firm's card.
const [w, ...more] = words(core);
if (w.length >= 5 && !/\d/.test(w) && !generic.test(w) && !first.has(w)) put({ toks: [w], ent: e.id, full: false, own });
// "Velmorze Pompy": the whole name with its first word in a case the ending list does not know.
if (more.length && w.length >= 6 && !/\d/.test(w)) put({ toks: [w, ...more], ent: e.id, full: false, loose: true, own });
}
}
for (const [uid, full] of Object.entries(names)) {
@@ -2668,19 +2694,31 @@ function chatLexSpans(text, entries, graph, { partial = true } = {}) {
}
return null;
};
// The first word in a case chatSameWord does not know ("velmorze"): all but the last letter, and only with the
// rest of the name beside it.
const near = (q, w) => w.length >= 6 && q.startsWith(w.slice(0, -1));
const fits = (x, i) => x.toks.every((w, k) => {
const q = toks[i + k];
if (!q) return false;
if (x.exact) return q.t === w;
// A single word of a firm's name counts only written as a name: capitalised and not opening a sentence.
return (chatSameWord(q.t, w) || (x.person && k === 0 && x.toks.length > 1 && chatSameFirst(q.t, w))) && (x.full || (q.cap && !q.lead));
return (chatSameWord(q.t, w) || (x.person && k === 0 && x.toks.length > 1 && chatSameFirst(q.t, w)) || (x.loose && k === 0 && near(q.t, w)))
&& (x.full || (q.cap && !q.lead));
});
// A capitalised word right beside a partial hit that is not of this firm's name makes another name of it:
// "Ortolan Cargo", "Kalinowe Wzgórze", "Fundacja Przystań", "w Zielonej Górze" are not our firms.
const foreign = (x, j) => { const q = toks[j]; return !!q && q.cap && !q.lead && !x.own.some((w) => chatSameWord(q.t, w) || near(q.t, w)); };
const fullEnts = new Set();
for (const full of [true, false]) {
if (!full && (!partial || spans.length)) break; // one full hit wins over partial ones
if (!full && !partial) break;
if (!full) for (const s of spans) for (const id of s.ents) fullEnts.add(id);
for (const x of entries) {
if (x.ref || x.full !== full) continue;
for (let i = 0; i + x.toks.length <= toks.length; i++) {
if (!fits(x, i)) continue;
// A full hit wins over partial ones of the same firm; a partial hit of another firm elsewhere still
// counts, so "Velmora Pompy i Sowiniec" names two firms, not one.
if (!full && (fullEnts.has(x.ent) || foreign(x, i - 1) || foreign(x, i + x.toks.length))) continue;
let b = i + x.toks.length;
// "Miedziak Energia S.A." picks the S.A.; without a form written both firms of that core stay in play.
const f = full && !x.exact ? formAt(b) : null;
@@ -2709,7 +2747,9 @@ function chatGraphFind(question, index) {
const sets = [...new Set(live.map((s) => [...s.ents].sort().join('|')))];
if (sets.length > 1) return { root: null, why: 'dwie encje' };
const ids = sets[0].split('|');
return ids.length > 1 ? { ambiguous: ids } : { root: ids[0], hit: live[0].hit };
// The hit travels with an ambiguous name too: one word alone ("Energii") must not take a question off Insider.
const hit = live.some((s) => s.hit !== 'czesciowe') ? live.find((s) => s.hit !== 'czesciowe').hit : 'czesciowe';
return ids.length > 1 ? { ambiguous: ids, hit } : { root: ids[0], hit };
}
// Whether a text (a record's title) names the entity in full: the found records that stay beside a card.
const chatGraphNames = (text, ent, graph) => chatLexSpans(text, ent.lex, graph, { partial: false }).length > 0;
@@ -2740,20 +2780,26 @@ function chatGraphAsk(ids, index) {
// 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 noun = cands.every((e) => e.type === 'sprawa') ? 'którą sprawę' : cands.every((e) => e.person) ? 'którą osobę' : 'którą firmę';
return { ask: `O ${noun} chodzi: ${cands.map((e) => `${e.name} (${fact(e)})`).join('; ')}? Napisz pełną nazwę.`,
mentioned: cands.map(anchor).filter(Boolean), why: 'niejednoznaczna nazwa', ambiguous: ids };
// 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'];
const tail = new Set(cands.map((e) => e.name)).size < cands.length ? `Napisz, która: ${ORD.slice(0, cands.length).join(', ').replace(/, (?=[^,]*$)/, ' czy ')}.` : 'Napisz pełną nazwę.';
// `order`: the candidates as shown, so "ta druga" next turn means the second of them (chatTurn).
return { ask: `O ${noun} chodzi: ${cands.map((e) => `${e.name} (${fact(e)})`).join('; ')}? ${tail}`,
mentioned: cands.map(anchor).filter(Boolean), why: 'niejednoznaczna nazwa', ambiguous: ids, order: cands.map((e) => e.id) };
}
// The plan of a turn: a card of which entity, a card of one record's links, a question back, or nothing (`why`).
function chatGraphTurn({ question, index, named = [], resolved = [], back = [] }) {
function chatGraphTurn({ question, index, named = [], resolved = [], back = [], pin = null }) {
const g = index.graph;
if (!g) return null;
// `pin`: the candidate the asker picked by its place in the code's own question back ("ta druga").
if (pin && g.ent.has(pin)) return { root: pin, kind: g.ent.get(pin).type, hit: 'pelne' };
if (back.length) return { why: 'odwołanie do listy' };
const entOf = (r) => (r.kind === 'sprawa' ? 'sprawa:' + r.key.split(':').pop()
: r.kind === 'strona' ? (g.of.get(r.key) || []).find((id) => id.startsWith('podmiot:')) : null);
const picked = [...named, ...resolved];
const found = chatGraphFind(question, index);
if (found && found.ambiguous && !picked.length) return chatGraphAsk(found.ambiguous, index);
if (found && found.ambiguous && !picked.length) return { ...chatGraphAsk(found.ambiguous, index), hit: found.hit };
if (found && found.why === 'dwie encje') return { why: 'dwie encje' };
const text = found && found.root ? [found.root] : [];
let ents = [...new Set([...picked.map(entOf).filter(Boolean), ...text])].filter((id) => g.ent.has(id));
@@ -2771,13 +2817,15 @@ function chatGraphTurn({ question, index, named = [], resolved = [], back = [] }
}
if (!root) return { why: found ? 'brak encji' : 'nic w pytaniu' };
const e = g.ent.get(root);
if (e.type === 'osoba') return e.recs.size ? { root, kind: 'osoba' } : { why: 'jeden moduł' };
if (e.mods.size >= 2) return { root, kind: e.type };
// A root from a named record is a full hit; from the text, as sure as the words that found it.
const hit = picked.map(entOf).includes(root) ? 'pelne' : found.hit;
if (e.type === 'osoba') return e.recs.size ? { root, kind: 'osoba', hit } : { why: 'jeden moduł' };
if (e.mods.size >= 2) return { root, kind: e.type, hit };
// One module only: a card adds something when the question asks for a kind of record the entity has none of
// ("czy mamy umowę z Fundacją Ostoja") or that the asker cannot see. Only ever a reason for a card, never to refuse.
const blind = index.blind.map((b) => b.split(' ')[0].toLowerCase());
const asked = (question.match(/\p{L}+/gu) || []).map((w) => CHAT_KIND_MOD[chatKindOf(chatFold(w))]).filter(Boolean);
return asked.some((m) => !e.mods.has(m) || blind.includes(m)) ? { root, kind: e.type } : { why: 'jeden moduł' };
return asked.some((m) => !e.mods.has(m) || blind.includes(m)) ? { root, kind: e.type, hit } : { why: 'jeden moduł' };
}
// ---- the card ----
@@ -2792,14 +2840,16 @@ function chatCardLines(e, index, today, kind) {
const get = (prefix) => [...e.recs.keys()].filter((k) => k.startsWith(prefix)).map((k) => index.byKey.get(k)).filter(Boolean);
const visible = (kind) => index.records.filter((r) => r.kind === kind).length;
const why = (r) => (e.why.get(r.key) || []).filter(Boolean);
const matters = get('sygna:sprawa:').sort((a, b) => a.matter.reference.localeCompare(b.matter.reference));
// String(): a register row may lack a field (a draft contract without a number); sorting must not throw on it.
const S = (x) => String(x || '');
const matters = get('sygna:sprawa:').sort((a, b) => S(a.matter.reference).localeCompare(S(b.matter.reference)));
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) => a.due_date.localeCompare(b.due_date));
const contracts = get('compass:umowa:').sort((a, b) => (a.contract.ends_on || '9999').localeCompare(b.contract.ends_on || '9999') || a.contract.number.localeCompare(b.contract.number));
const projects = get('galena:projekt:').sort((a, b) => a.project.name.localeCompare(b.project.name, 'pl'));
const versions = get('galena:wersja:').sort((a, b) => a.draft.created_at.localeCompare(b.draft.created_at));
const orders = get('counsel:zlecenie:').sort((a, b) => a.order.reference.localeCompare(b.order.reference));
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 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)));
const late = (d) => `po terminie od ${chatPlural(-d.days_left, 'dnia', 'dni', 'dni')}`;
const groups = [['PO TERMINIE', 'po terminie', (d) => d.days_left < 0], ['W TYM TYGODNIU', 'w tym tygodniu', (d) => d.days_left >= 0 && d.days_left <= 7],
['PÓŹNIEJ', 'później', (d) => d.days_left > 7]];
@@ -2925,10 +2975,12 @@ function chatCard(entId, index, today, { table = false } = {}) {
// The second hop: what else the matter's client has, as numbers only.
const c = e.client && g.ent.get(e.client);
if (c) {
const others = (prefix) => [...c.recs.keys()].filter((k) => k.startsWith(prefix) && !e.recs.has(k)).map((k) => index.byKey.get(k)).filter(Boolean);
const ms = others('sygna:sprawa:');
const cs = others('compass:umowa:');
const os = others('counsel:zlecenie:');
// By number, as in B7c's example: the order the map met them in says nothing to the reader.
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 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)}, ` +
`${chatPlural(cs.length, 'umowę', 'umowy', 'umów')}${list(cs, (r) => r.contract.number)}, ${chatPlural(os.length, 'inne zlecenie', 'inne zlecenia', 'innych zleceń')}${list(os, (r) => r.order.reference)}.`));
@@ -3716,8 +3768,12 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
// 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));
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.
const asked = graf && !named.length && ana.ordinal && prev && prev.coded === 'ask' && prev.graf && prev.graf.order;
const pin = asked ? asked.at(ana.ordinal < 0 ? -1 : ana.ordinal - 1) || null : null;
let resolved = [];
if (!named.length && (ana.demonstrative || ana.ordinal)) {
if (!named.length && !pin && (ana.demonstrative || ana.ordinal)) {
const res = chatResolveRefs(prev, ana, index);
const which = CHAT_WHICH[res.kind] || 'który z nich';
if (res.ambiguous) {
@@ -3761,13 +3817,21 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
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;
try { gt = index.graph && chatGraphTurn({ question, index, named, resolved, back }); } catch (ex) { console.warn('chat map off:', ex); }
if (graf && gt && gt.ask) return done(gt.ask, { coded: 'ask', mentioned: gt.mentioned, graf: gt });
// "Wypowiedzenie umowy z Velmora Pompy" names a client, so it is a data question, not one for Insider.
const route = chatRoute(question, focus, named.length + resolved.length + (graf && gt && (gt.root || gt.link) ? 1 : 0));
// A card only for a data question: a cited article stays Insider's.
const card = !graf || !gt || route !== 'data' ? null : gt.root ? chatCard(gt.root, index, today, { table: graf === 'tabela' })
: gt.link ? chatLinkCard(gt.link, index, today) : null;
try { gt = index.graph && chatGraphTurn({ question, index, named, resolved, back, pin }); } catch (ex) { console.warn('chat map off:', ex); }
// "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 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;
// A card only for a data question: a cited article stays Insider's. A fault in building it leaves the turn as A.
let card = null;
try {
card = !usable || route !== 'data' ? null : gt.root ? chatCard(gt.root, index, today, { table: graf === 'tabela' })
: gt.link ? chatLinkCard(gt.link, index, today) : null;
} catch (ex) { console.warn('chat map off:', ex); card = null; }
// Set here, so turns that end early (done) carry it too; the harness reads it from every answer.
if (graf) answer.graf = gt && { root: gt.root || null, link: gt.link || null, why: gt.why || null, card: card && card.rec.key, members: card ? [...card.members] : [] };
else answer.grafDry = gt && { root: gt.root || null, link: gt.link || null, why: gt.why || null, ask: !!gt.ask };