Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0eefd90b40 | ||
|
|
e2babc1591 | ||
|
|
c610e1b008 | ||
|
|
05e699e38c | ||
|
|
a30de3a9dc | ||
|
|
3a60ac7882 | ||
|
|
16bf069604 |
+10
-10
@@ -1,30 +1,30 @@
|
||||
[submodule "deploy/modules/galena"]
|
||||
path = deploy/modules/galena
|
||||
url = https://github.com/Alpaq92/Galena
|
||||
url = ../Galena.git
|
||||
[submodule "deploy/modules/counsel"]
|
||||
path = deploy/modules/counsel
|
||||
url = https://github.com/Alpaq92/CounselScorecard
|
||||
url = ../CounselScorecard.git
|
||||
[submodule "deploy/modules/sygna"]
|
||||
path = deploy/modules/sygna
|
||||
url = https://github.com/Alpaq92/Sygna
|
||||
url = ../Sygna.git
|
||||
[submodule "deploy/modules/insider"]
|
||||
path = deploy/modules/insider
|
||||
url = https://github.com/Alpaq92/Insider.git
|
||||
url = ../Insider.git
|
||||
[submodule "deploy/modules/lexicon"]
|
||||
path = deploy/modules/lexicon
|
||||
url = https://github.com/Alpaq92/Lexicon
|
||||
url = ../Lexicon.git
|
||||
[submodule "deploy/modules/agora"]
|
||||
path = deploy/modules/agora
|
||||
url = https://github.com/Alpaq92/Agora
|
||||
url = ../Agora.git
|
||||
[submodule "deploy/modules/parafa"]
|
||||
path = deploy/modules/parafa
|
||||
url = https://github.com/Alpaq92/Parafa
|
||||
url = ../Parafa.git
|
||||
[submodule "deploy/modules/scribe"]
|
||||
path = deploy/modules/scribe
|
||||
url = https://github.com/Alpaq92/Scribe
|
||||
url = ../Scribe.git
|
||||
[submodule "deploy/modules/arbiter"]
|
||||
path = deploy/modules/arbiter
|
||||
url = https://github.com/Alpaq92/Arbiter
|
||||
url = ../Arbiter.git
|
||||
[submodule "deploy/modules/workflow"]
|
||||
path = deploy/modules/workflow
|
||||
url = https://github.com/Alpaq92/Workflow
|
||||
url = ../Workflow.git
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Home chat's filter of one entity (spec lw-platform/specs/2026-11-28-czat-filtr-podmiotu.md, `chat.filtr`).
|
||||
|
||||
Signed with their owner, small models still gave another firm's record to the firm asked about. With the filter, a
|
||||
question naming exactly one outside entity in full keeps, of what search found, only the records the map ties to that entity.
|
||||
An ambiguous name, two entities, a partial name and an empty result leave the turn as it was; named records stay.
|
||||
|
||||
The chat block of `frontend/app.js` is built under Node, as in `test_chat_traps_console.py`, with a model stub.
|
||||
DB-free and network-free; skipped only where no `node` binary exists.
|
||||
"""
|
||||
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")
|
||||
APP = ROOT / "frontend" / "app.js"
|
||||
|
||||
pytestmark = pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
|
||||
# The world on a frozen day (2026-11-12). The asker is u1. Pairs that must be told apart: Miedziak Energia S.A.
|
||||
# and sp. z o.o. (two NIPs), Velmora Pompy and Velmora Serwis, contract UM-2026-0109 and matter 2026/0109.
|
||||
# Pairs that must NOT be: Kalinowy Dwór written "Sp. z o.o." and in full, two unrelated foundations.
|
||||
_PRELUDE = r"""
|
||||
const fs = require('fs');
|
||||
const src = fs.readFileSync(APP, 'utf8');
|
||||
const BLOCK = src.slice(src.indexOf('// Code finds, the model reads'), src.indexOf("// A module's screen"));
|
||||
const TODAY = '2026-11-12';
|
||||
const NOW = Date.parse(TODAY + 'T12:00:00Z');
|
||||
class FixedDate extends Date { constructor(...a) { super(...(a.length ? a : [NOW])); } static now() { return NOW; } }
|
||||
const party = (id, name, nip, kind = 'organisation') => ({ id, name, nip, address: null, kind });
|
||||
const matter = (id, reference, name, client, clientId, lawyer) => ({ id, reference, name, client_name: client, client_party_id: clientId,
|
||||
practice_area: null, status: 'open', responsible_lawyer_id: lawyer, opened_at: '2026-03-01', closed_at: null, description: '' });
|
||||
const card = (id, number, name, cp, matterRef, created = '2026-02-01T09:00:00Z') => ({ id, project_id: 'p-' + id, number, name,
|
||||
counterparty: cp ? cp.name : null, counterparties: cp ? [cp] : [], matter_ref: matterRef, status: 'obowiazuje',
|
||||
value_amount: 1000, value_currency: 'PLN', concluded_on: '2026-01-02', ends_on: '2027-06-30', created_at: created });
|
||||
const order = (id, firmId, reference, title, notes, created = '2026-11-10T08:00:00Z') => ({ id, firm_id: firmId, reference, title,
|
||||
billing_notes: notes, status: 'in_progress', budget_estimate: 5000, budget_currency: 'PLN', matter_owner_id: null, created_at: created });
|
||||
const WORLD = {
|
||||
'sygna/users': [{ id: 'u1', full_name: 'Anna Nowak' }, { id: 'u2', full_name: 'Piotr Zając' }],
|
||||
'sygna/parties': [
|
||||
party('s1', 'Miedziak Energia S.A.', '6340001110'),
|
||||
party('s2', 'Miedziak Energia sp. z o.o.', '6340005550'),
|
||||
party('s3', 'Velmora Pompy sp. z o.o.', '5250001111'),
|
||||
party('s4', 'Velmora Serwis sp. z o.o.', '5250002222'),
|
||||
party('s5', 'Fundacja Ostoja', null),
|
||||
party('s6', 'Fundacja Zielony Las', null),
|
||||
party('s7', 'Kalinowy Dwór sp. z o.o.', null)],
|
||||
'sygna/matters': [
|
||||
matter('m1', '2026/0107', 'Spór o dostawy pomp', 'Velmora Pompy sp. z o.o.', 's3', 'u1'),
|
||||
matter('m2', '2026/0109', 'Windykacja należności', 'Miedziak Energia sp. z o.o.', 's2', 'u2')],
|
||||
'sygna/deadlines?days=365': [
|
||||
{ id: 'd1', title: 'Odpowiedź na pozew', kind: 'procedural', due_date: '2026-11-20', days_left: 8, completed_at: null, matter_id: 'm1',
|
||||
matter_reference: '2026/0107', matter_name: 'Spór o dostawy pomp', basis: null, owner_id: 'u1', source: 'court' },
|
||||
{ id: 'd2', title: 'Wezwanie do zapłaty', kind: 'internal', due_date: '2026-11-25', days_left: 13, completed_at: null, matter_id: 'm2',
|
||||
matter_reference: '2026/0109', matter_name: 'Windykacja należności', basis: null, owner_id: 'u2', source: 'internal' }],
|
||||
'galena/cards?limit=200&offset=0': [
|
||||
// Same digits as matter 2026/0109, pinned to no matter.
|
||||
card('c1', 'UM-2026-0109', 'Dostawa energii', { id: 'k1', name: 'Miedziak Energia S.A.', nip: '6340001110' }, null),
|
||||
// Pinned to a matter the asker sees.
|
||||
card('c2', 'UM-2026-0110', 'Serwis pomp', { id: 'k2', name: 'Velmora Serwis sp. z o.o.', nip: '5250002222' }, 'm1', '2026-11-11T09:00:00Z'),
|
||||
// Pinned to a matter this account does not see.
|
||||
card('c3', 'UM-2026-0111', 'Najem magazynu', { id: 'k3', name: 'Kalinowy Dwór Sp. z o.o.', nip: null }, 'm-hidden'),
|
||||
card('c4', 'UM-2026-0112', 'Dzierżawa gruntu', { id: 'k4', name: 'Kalinowy Dwór spółka z ograniczoną odpowiedzialnością', nip: null }, null),
|
||||
card('c5', 'UM-2026-0113', 'Darowizna', { id: 'k5', name: 'Fundacja Ostoja', nip: null }, null),
|
||||
card('c6', 'UM-2026-0114', 'Sprzedaż energii', { id: 'k6', name: 'Miedziak Energia sp. z o.o.', nip: '6340005550' }, null)],
|
||||
'counsel/firms': [
|
||||
{ id: 'f1', name: 'Hofmann Legal', legal_name: 'Hofmann Legal sp.k.', status: 'active', contact_person: null, notes: '' },
|
||||
{ id: 'f2', name: 'Lis i Wspólnicy', legal_name: 'Lis i Wspólnicy sp.p.', status: 'active', contact_person: null, notes: '' }],
|
||||
'counsel/matters': [
|
||||
order('o1', 'f1', 'ZK/2026/058', 'Opinia do umowy UM-2026-0109', ''),
|
||||
order('o2', 'f2', 'ZK/2026/059', 'Reprezentacja w sporze', 'Klient: Velmora Pompy sp. z o.o., sprawa 2026/0107'),
|
||||
order('o3', 'f1', 'ZK/2026/060', 'Analiza ogólna', '')],
|
||||
'counsel/review-cycles': [],
|
||||
'galena/drive/home': { workspaces: [{ id: 'pr1', kind: 'project', name: 'Pisma procesowe', path: '/Kancelaria/Pisma procesowe', review_policy: 'required' }] },
|
||||
'galena/drive/shared': [],
|
||||
'galena/projects/pr1/tree?recursive=true': [],
|
||||
'galena/projects/pr1/drafts': [
|
||||
{ id: 'w1', title: 'Opinia o karach umownych', status: 'pending', author_id: 'u1', created_at: '2026-11-09T10:00:00Z' },
|
||||
{ id: 'w2', title: 'Projekt pozwu', status: 'pending', author_id: 'u2', created_at: '2026-11-08T10:00:00Z' }],
|
||||
};
|
||||
const fetch = async (url) => {
|
||||
const u = new URL(String(url));
|
||||
if (u.pathname === '/atrium/api/v1/models/ask') return new Response('data: ' + JSON.stringify({ choices: [{ delta: { content: 'Odpowiedź [1].' } }] }) +
|
||||
'\n\ndata: [DONE]\n\n', { status: 200, headers: { 'Content-Type': 'text/event-stream' } });
|
||||
const m = /^\/([^/]+)\/api\/v1\/(.*)$/.exec(u.pathname);
|
||||
const body = m && WORLD[m[1] + '/' + m[2] + u.search];
|
||||
return body === undefined ? new Response('{}', { status: 404 }) : new Response(JSON.stringify(body), { status: 200 });
|
||||
};
|
||||
// The block's functions by name; `patch` rewrites the block first.
|
||||
function fns(names, patch = (b) => b) {
|
||||
const load = new Function('fetch', 'document', 'state', 'chat', '_tr', 'moduleHref', 'coreRefusal', 'Date', 'console',
|
||||
patch(BLOCK) + `\nreturn { ${names.join(', ')} };`);
|
||||
const quiet = { ...console, warn: () => {} };
|
||||
return load(fetch, { baseURI: 'http://t.local/atrium/' }, { user: { id: 'u1' }, launcher: [] }, { ctl: new AbortController() },
|
||||
(s) => s, (slug, inner) => slug + '/#/' + inner, (p) => p.detail, FixedDate, quiet);
|
||||
}
|
||||
// One turn on the default arm (team member's card, asker's card), the filter on or off; `opts` adds chatTurn's switches.
|
||||
async function turn(question, filtr, patch = (b) => b, opts = {}) {
|
||||
const f = fns(['chatIndex', 'chatTurn'], patch);
|
||||
const index = await f.chatIndex();
|
||||
const a = await f.chatTurn({ model: 'm', question, turns: [], index, graf: 'osoba', ja: true, prawo: false, filtr, ...opts });
|
||||
const names = (key) => (index.graph.of.get(key) || []).map((id) => index.graph.ent.get(id).name);
|
||||
return { refs: a.refs.map((r) => r.key), filtr: a.filtr || null, komplet: a.komplet || null, root: a.filtr ? index.graph.ent.get(a.filtr.root).name : null,
|
||||
owners: Object.fromEntries(a.refs.map((r) => [r.key, names(r.key)])) };
|
||||
}
|
||||
const both = async (q, patch) => ({ on: await turn(q, true, patch), off: await turn(q, false, patch) });
|
||||
"""
|
||||
|
||||
|
||||
def _run(js: str) -> object:
|
||||
script = f"const APP = {json.dumps(str(APP))};\n" + _PRELUDE + \
|
||||
f"\n(async () => {{ const out = await (async () => {{ {js} }})(); console.log(JSON.stringify(out)); }})()" \
|
||||
".catch((e) => { console.error(e && e.stack || e); process.exit(1); });"
|
||||
r = subprocess.run([NODE, "-"], input=script, capture_output=True, text=True, timeout=120, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
def test_one_firm_named_in_full_keeps_only_its_own_records() -> None:
|
||||
# Velmora Serwis: its party and its contract stay; Velmora Pompy's party and matter, another firm's order,
|
||||
# the activity list and the 30/60/90-day windows that search brought on the shared words drop.
|
||||
got = _run("return both('Jakie umowy ma Velmora Serwis sp. z o.o.?');")
|
||||
on, off = got["on"], got["off"]
|
||||
assert on["root"] == "Velmora Serwis sp. z o.o."
|
||||
assert on["refs"] == ["sygna:strona:s4", "galena:umowa:c2"]
|
||||
assert {"sygna:strona:s3", "sygna:sprawa:m1", "atrium:aktywnosc", "galena:wygasajace:30"} <= set(off["refs"])
|
||||
assert set(on["filtr"]["kept"]) | set(on["filtr"]["cut"]) == set(off["refs"])
|
||||
assert off["filtr"] is None # off by default: chatTurn without the flag is the turn of today
|
||||
|
||||
|
||||
def test_a_named_record_of_another_firm_stays() -> None:
|
||||
# UM-2026-0109 is Miedziak Energia's: named in the question, it stays first; the filter cuts only what search found.
|
||||
got = _run("return both('Czy umowa UM-2026-0109 dotyczy Velmora Serwis sp. z o.o.?');")
|
||||
assert got["on"]["root"] == "Velmora Serwis sp. z o.o."
|
||||
assert got["on"]["refs"][0] == "galena:umowa:c1" and got["off"]["refs"][0] == "galena:umowa:c1"
|
||||
assert "sygna:strona:s3" in got["off"]["refs"] and "sygna:strona:s3" not in got["on"]["refs"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("question", [
|
||||
"Co mamy z Velmora?", # ambiguous: two Velmoras
|
||||
"Porównaj umowy Velmora Serwis sp. z o.o. i Fundacja Ostoja", # two entities
|
||||
"Jakie umowy ma Ostoja?", # one word of the name only
|
||||
"Co mam na głowie?", # the asker's own card cuts already
|
||||
"Co prowadzi Piotr Zając?", # a team member's card cuts already
|
||||
])
|
||||
def test_no_filter_where_the_spec_leaves_the_turn_as_it_was(question: str) -> None:
|
||||
got = _run(f"return both({json.dumps(question)});")
|
||||
assert got["on"]["filtr"] is None
|
||||
assert got["on"]["refs"] == got["off"]["refs"]
|
||||
|
||||
|
||||
def test_an_entity_with_none_of_its_records_found_is_never_left_with_an_empty_list() -> None:
|
||||
got = _run("return both('Jakie umowy ma Velmora Serwis sp. z o.o.?', "
|
||||
"(b) => b.replace('e.recs.has(r.key)', 'false'));")
|
||||
assert got["on"]["filtr"] is None
|
||||
assert got["on"]["refs"] == got["off"]["refs"] and got["on"]["refs"]
|
||||
|
||||
|
||||
def test_a_fault_in_the_filter_leaves_the_turn_as_it_was() -> None:
|
||||
got = _run("return both('Jakie umowy ma Velmora Serwis sp. z o.o.?', "
|
||||
"(b) => b.replace('const cuts = e && e.type', 'const cuts = e.nope.x && e.type'));")
|
||||
assert got["on"]["filtr"] is None and got["on"]["refs"] == got["off"]["refs"]
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Home chat's komplet of the entity asked about (spec lw-platform/specs/2026-11-28-czat-komplet-podmiotu.md, `chat.komplet`).
|
||||
|
||||
With the filter, small models stopped borrowing another firm's record and said "not found" instead: the right record
|
||||
was in the map but not among the twelve search hits. Under komplet the map's records for the named party, the asker
|
||||
or up to three parties join the sources first (limit 20), a record named by number brings its matter, client,
|
||||
deadlines and orders, names are read in their cases, and Sygna gets a matters-by-status summary.
|
||||
|
||||
Reuses the world and harness of `test_chat_filter_console.py`. DB-free and network-free; skipped where no `node`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from test_chat_filter_console import NODE, _run
|
||||
|
||||
pytestmark = pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
|
||||
K = "undefined, { komplet: true }"
|
||||
|
||||
|
||||
def _pair(question: str, setup: str = "") -> dict:
|
||||
q = json.dumps(question)
|
||||
return _run(f"{setup}\nreturn {{ on: await turn({q}, true, {K}), off: await turn({q}, true) }};")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("asked", "name", "same"), [
|
||||
("logistyce", "logistyka", True), # k → c
|
||||
("velmorze", "velmora", True), # r → rz
|
||||
("ostoi", "ostoja", True), # j → i
|
||||
("sowinca", "sowiniec", True), # -iec → -ńca (words arrive folded, chatFold)
|
||||
("sowincem", "sowiniec", True),
|
||||
("pradze", "praga", True), # g → dz
|
||||
("kodax", "kodar", False), # a prefix is not a case: the reason it is a list
|
||||
("velmorek", "velmora", False),
|
||||
("ostrowie", "ostoja", False),
|
||||
])
|
||||
def test_case_alternations_are_a_closed_list_read_only_when_wide(asked: str, name: str, same: bool) -> None:
|
||||
got = _run(f"const {{ chatSameWord }} = fns(['chatSameWord']);"
|
||||
f"return [chatSameWord({json.dumps(asked)}, {json.dumps(name)}, true),"
|
||||
f" chatSameWord({json.dumps(asked)}, {json.dumps(name)})];")
|
||||
assert got == [same, False] # without komplet (`wide`) the reading of names is today's
|
||||
|
||||
|
||||
def test_a_firm_in_another_case_gets_its_records_and_an_unknown_name_none() -> None:
|
||||
got = _pair("Co mamy o Ostoi?")
|
||||
assert got["off"]["refs"] == []
|
||||
assert got["on"]["refs"] == ["sygna:strona:s5", "galena:umowa:c5"]
|
||||
assert _pair("Co mamy o Ostrowie?")["on"]["refs"] == []
|
||||
|
||||
|
||||
def test_the_entity_s_records_come_first_and_the_limit_is_twenty() -> None:
|
||||
many = ("WORLD['galena/cards?limit=200&offset=0'].push(...Array.from({ length: 25 }, (_, i) => card('x' + i, "
|
||||
"'UM-2026-02' + String(i).padStart(2, '0'), 'Umowa najmu ' + i, { id: 'kx', name: 'Fundacja Zielony Las', nip: null }, null)));")
|
||||
got = _pair("Jakie umowy ma Fundacja Zielony Las?", many)
|
||||
on = got["on"]["refs"]
|
||||
assert len(on) == 20 and len(got["off"]["refs"]) <= 12
|
||||
assert on[0] == "sygna:strona:s6" and all(k.startswith("galena:umowa:x") for k in on[1:])
|
||||
|
||||
|
||||
def test_the_namesake_firm_and_its_matter_stay_under_komplet_only() -> None:
|
||||
# Miedziak S.A. asked: the sp. z o.o.'s contract and matter mention "Miedziak" and stay, for "that one is the other firm's".
|
||||
got = _pair("Jakie umowy ma Miedziak Energia S.A.?")
|
||||
assert got["on"]["root"] == got["off"]["root"] == "Miedziak Energia S.A."
|
||||
assert {"sygna:strona:s2", "galena:umowa:c6", "sygna:sprawa:m2"} <= set(got["on"]["refs"])
|
||||
assert "galena:umowa:c6" not in got["off"]["refs"]
|
||||
|
||||
|
||||
def test_a_matter_named_by_number_is_not_filtered() -> None:
|
||||
got = _pair("Jaka umowa jest przypięta do sprawy 2026/0109?")
|
||||
assert got["off"]["filtr"] is not None and got["on"]["filtr"] is None
|
||||
assert got["on"]["refs"][:3] == ["sygna:sprawa:m2", "sygna:termin:d2", "sygna:strona:s2"]
|
||||
|
||||
|
||||
def test_two_parties_get_both_komplets_and_no_filter() -> None:
|
||||
got = _pair("Kto ma więcej umów, Kalinowy Dwór czy Velmora Pompy?")
|
||||
on = got["on"]["refs"]
|
||||
assert got["on"]["filtr"] is None
|
||||
assert {"sygna:strona:s3", "sygna:strona:s7", "sygna:sprawa:m1", "galena:umowa:c3", "galena:umowa:c4",
|
||||
"sygna:termin:d1", "counsel:zlecenie:o2"} <= set(on[:8])
|
||||
assert "counsel:zlecenie:o2" not in got["off"]["refs"]
|
||||
|
||||
|
||||
def test_the_asker_s_records_join_on_a_question_about_mine() -> None:
|
||||
got = _pair("Jakie terminy są w moich sprawach?")
|
||||
assert got["on"]["refs"][:3] == ["sygna:termin:d1", "sygna:sprawa:m1", "galena:wersja:w1"]
|
||||
assert "galena:wersja:w1" not in got["off"]["refs"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("question", "first"), [
|
||||
# A contract by number → its matter, the matter's client and deadline.
|
||||
("Kto prowadzi sprawę z umowy UM-2026-0110?", ["galena:umowa:c2", "sygna:sprawa:m1", "sygna:strona:s3", "sygna:termin:d1"]),
|
||||
# An order by number → its firm, and the matter its note names.
|
||||
("Która kancelaria realizuje ZK/2026/059?", ["counsel:zlecenie:o2", "counsel:kancelaria:f2", "sygna:sprawa:m1"]),
|
||||
# A contract by number → the orders that name it, with their firm.
|
||||
("Czy przy UM-2026-0109 korzystaliśmy z kancelarii zewnętrznej?", ["galena:umowa:c1", "counsel:zlecenie:o1", "counsel:kancelaria:f1"]),
|
||||
])
|
||||
def test_a_record_named_by_number_brings_one_step_of_the_map(question: str, first: list[str]) -> None:
|
||||
got = _pair(question)
|
||||
assert got["on"]["refs"][: len(first)] == first
|
||||
assert got["off"]["refs"][: len(first)] != first
|
||||
|
||||
|
||||
def test_the_matters_by_status_summary_exists_under_komplet_only() -> None:
|
||||
got = _pair("Ile spraw mamy otwartych, a ile zamkniętych?")
|
||||
assert got["on"]["refs"][0] == "sygna:sprawy"
|
||||
assert "sygna:sprawy" not in got["off"]["refs"]
|
||||
|
||||
|
||||
def test_off_by_default_and_a_fault_leaves_the_turn_as_it_was() -> None:
|
||||
q = json.dumps("Kto prowadzi sprawę z umowy UM-2026-0110?")
|
||||
got = _run(f"return {{ def: await turn({q}, true), off: await turn({q}, true, undefined, {{ komplet: false }}),"
|
||||
f" bad: await turn({q}, true, (b) => b.replace('const ext = chatKomplet(', 'const ext = nope.x('), {{ komplet: true }}) }};")
|
||||
assert got["def"] == got["off"] and got["def"]["komplet"] is None
|
||||
assert got["bad"]["komplet"] is None and got["bad"]["refs"]
|
||||
+139
-14
@@ -2190,6 +2190,14 @@ async function chatSygna(today, names, contracts = []) {
|
||||
`status ${chatStatus('sprawa', m.status)}, ${chatWho(names, m.responsible_lawyer_id, 'prowadzi', 'osoba prowadząca nie wpisana')}, otwarta ${m.opened_at}. ${m.description || ''}`,
|
||||
'sygna:sprawa:' + m.id, [m.reference, m.name]),
|
||||
at: m.closed_at || m.opened_at, did: m.closed_at ? 'zamknięta' : 'otwarta', matter: m }));
|
||||
// Like the register's totals, for matters: "ile spraw otwartych, a ile zamkniętych" got "nie znalazłem" from Qwen
|
||||
// 3 of 3 (zestaw 11). Search offers it only under chat.komplet (chatTurn), so the other arms read as before.
|
||||
if (matters.length) {
|
||||
const by = [...new Set(matters.map((m) => m.status))].sort().map((st) => { const ms = matters.filter((m) => m.status === st);
|
||||
return `status ${chatStatus('sprawa', st)}: ${ms.length} (${ms.map((m) => m.reference).join(', ')})`; });
|
||||
out.push(rec('zestawienie', 'Zestawienie spraw wg statusu (ile otwartych, ile zamkniętych)', 'matters',
|
||||
`Sprawy widoczne na koncie pytającego, stan na ${today}, razem ${matters.length}; ${by.join('; ')}.`, 'sygna:sprawy', null, out.map((r) => r.key)));
|
||||
}
|
||||
// days=365: Sygna's default window is 14 days, and a deadline 20 days out did not exist for the chat
|
||||
// ("nie znalazłem", czat-v3 termin-07-data, 2026-11-03). Overdue ones come back whatever the window.
|
||||
const deadlines = (await askerGet('sygna', 'deadlines?days=365')) || [];
|
||||
@@ -2873,13 +2881,21 @@ const CHAT_KIND_MOD = { umowa: 'galena', sprawa: 'sygna', termin: 'sygna', stron
|
||||
// Another case of the same word: a closed list of Polish endings, never a prefix. A prefix rule made "Kodax"
|
||||
// (a firm we do not have) the existing Kodar; an ending list misses an odd form, which only means today's answer.
|
||||
const CHAT_ENDINGS = ['a', 'e', 'i', 'o', 'u', 'y', 'em', 'om', 'ie', 'owi', 'ach', 'ami', 'ow', 'iej', 'ej', 'ego', 'emu', 'ym', 'im', 'mi'];
|
||||
function chatSameWord(q, n) {
|
||||
// `wide` (chat.komplet only): the consonant alternations at a name's end too, also a closed list. Without them
|
||||
// "Ortolan Logistyce", "Velmorze Pompy", "Ostoi" and "Sowińca" named no firm (battery, 28.11), so the filter
|
||||
// and the entity's records never came. Folded text: Sowiniec → sowinc|a, Dębowiec → debowc|a.
|
||||
const CHAT_ALTERNATIONS = [[/ka$/, 'c', ['e']], [/ga$/, 'dz', ['e']], [/ra$/, 'rz', ['e']], [/ja$/, '', ['i']], [/iec$/, 'c', CHAT_ENDINGS]];
|
||||
function chatSameWord(q, n, wide = false) {
|
||||
if (q === n) return true;
|
||||
if (q.length < 4 || n.length < 4 || /\d/.test(n)) return false;
|
||||
const stems = [n];
|
||||
if (/[aeiouy]$/.test(n)) stems.push(n.slice(0, -1)); // zielona → zielon|ej, energia → energi|i
|
||||
if (/e[kc]$/.test(n)) stems.push(n.slice(0, -2) + n.slice(-1)); // kaczmarek → kaczmark|a (movable e)
|
||||
return stems.some((s) => q.startsWith(s) && CHAT_ENDINGS.includes(q.slice(s.length)));
|
||||
if (stems.some((s) => q.startsWith(s) && CHAT_ENDINGS.includes(q.slice(s.length)))) return true;
|
||||
return wide && CHAT_ALTERNATIONS.some(([re, to, ends]) => {
|
||||
const s = n.replace(re, to);
|
||||
return s !== n && q.startsWith(s) && ends.includes(q.slice(s.length));
|
||||
});
|
||||
}
|
||||
// A three-letter first name inflects too ("Ewy Sadowskiej", "Jana Nowaka"), which chatSameWord refuses for a lone
|
||||
// short word. Used only for the first word of a person's full name, so the surname still has to match beside it.
|
||||
@@ -3218,13 +3234,18 @@ function chatGraph(records, names, today) {
|
||||
put({ toks: words(core), ent: e.id, form: chatFormPart(mk) || null, full: true, person: e.person });
|
||||
}
|
||||
}
|
||||
if (e.person || !on('czesciowe')) continue;
|
||||
const own = [...cores].flatMap(words);
|
||||
// "o pani Zawilskiej": a client's surname alone, read only under chat.komplet (`wide`). Two clients of one
|
||||
// surname both claim the span, so the question comes back, as for any ambiguous name.
|
||||
if (e.person) for (const core of cores) { const w = words(core).pop(); if (w && w.length >= 5) put({ toks: [w], ent: e.id, full: false, own, surname: true }); }
|
||||
if (e.person || !on('czesciowe')) continue;
|
||||
for (const core of cores) {
|
||||
// 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 });
|
||||
// "Fundacja Ostoja" → "o Ostoi": a generic first word leaves the second to tell the firm apart (chat.komplet only).
|
||||
if ((generic.test(w) || CHAT_ORG_WORDS.test(w)) && more.length && more[0].length >= 5 && !/\d/.test(more[0])) put({ toks: [more[0]], ent: e.id, full: false, own, surname: true });
|
||||
// "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 });
|
||||
}
|
||||
@@ -3248,7 +3269,9 @@ function chatGraph(records, names, today) {
|
||||
|
||||
// Where the dictionary's entries stand in a text: [{a, b, ents, hit}] over its words. Longest entry first and no
|
||||
// overlaps, as chatNamed; entries of the same words at the same place all count (a core two firms share).
|
||||
function chatLexSpans(text, entries, graph, { partial = true } = {}) {
|
||||
// `wide`: chat.komplet's reading (consonant alternations, a client's surname alone, "SA" for S.A.); off, as before.
|
||||
const CHAT_FORM_ASKED = { sa: 's a' };
|
||||
function chatLexSpans(text, entries, graph, { partial = true, wide = false } = {}) {
|
||||
const src = String(text);
|
||||
const toks = [...src.matchAll(/[\p{L}\p{N}]+/gu)].map((m, i) => ({ t: chatFold(m[0]), s: m.index, e: m.index + m[0].length,
|
||||
cap: /^\p{Lu}/u.test(m[0]), lead: i === 0 || /[.!?]\s*$/.test(src.slice(0, m.index)) }));
|
||||
@@ -3268,7 +3291,8 @@ function chatLexSpans(text, entries, graph, { partial = true } = {}) {
|
||||
}
|
||||
const formAt = (i) => {
|
||||
for (let n = 5; n >= 1; n--) {
|
||||
const f = i + n <= toks.length && CHAT_FORM_OF.get(toks.slice(i, i + n).map((t) => t.t).join(' '));
|
||||
const k = i + n <= toks.length && toks.slice(i, i + n).map((t) => t.t).join(' ');
|
||||
const f = k && (CHAT_FORM_OF.get(k) || (wide && CHAT_FORM_ASKED[k]));
|
||||
if (f) return { f, n };
|
||||
}
|
||||
return null;
|
||||
@@ -3281,18 +3305,18 @@ function chatLexSpans(text, entries, graph, { partial = true } = {}) {
|
||||
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.loose && k === 0 && near(q.t, w)))
|
||||
return (chatSameWord(q.t, w, wide) || (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 foreign = (x, j) => { const q = toks[j]; return !!q && q.cap && !q.lead && !x.own.some((w) => chatSameWord(q.t, w, wide) || near(q.t, w)); };
|
||||
const fullEnts = new Set();
|
||||
for (const full of [true, false]) {
|
||||
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;
|
||||
if (x.ref || x.full !== full || (x.surname && !wide)) 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
|
||||
@@ -3305,7 +3329,7 @@ function chatLexSpans(text, entries, graph, { partial = true } = {}) {
|
||||
if (x.form ? x.form !== f.f : graph.ent.get(x.ent).forms.size) continue;
|
||||
b += f.n;
|
||||
}
|
||||
claim(i, b, x.ent, full ? 'pelne' : 'czesciowe');
|
||||
claim(i, b, x.ent, full ? 'pelne' : x.surname ? 'nazwisko' : 'czesciowe');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3314,10 +3338,10 @@ function chatLexSpans(text, entries, graph, { partial = true } = {}) {
|
||||
|
||||
// The entity a question names, read by the names in the data, never by words for kinds of questions.
|
||||
// {root, hit} | {ambiguous: [entId]} | {root: null, why: 'dwie encje'} | null.
|
||||
function chatGraphFind(question, index) {
|
||||
function chatGraphFind(question, index, { wide = false } = {}) {
|
||||
const g = index.graph;
|
||||
if (!g) return null;
|
||||
const spans = chatLexSpans(question, g.lex, g);
|
||||
const spans = chatLexSpans(question, g.lex, g, { wide });
|
||||
if (!spans.length) return null;
|
||||
// A matter and its own client named together: the matter, the narrower one.
|
||||
const all = new Set(spans.flatMap((s) => [...s.ents]));
|
||||
@@ -3330,6 +3354,66 @@ function chatGraphFind(question, index) {
|
||||
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 };
|
||||
}
|
||||
// chat.komplet (spec lw-platform/specs/2026-11-28-czat-komplet-podmiotu.md): the map's own records of what the
|
||||
// question names, whatever words their titles have. In 29 of the 30 battery turns that lacked a record the answer
|
||||
// needed, the map tied it to the firm, person or matter asked about, and word search gave the 12 slots to records
|
||||
// sharing words with the question (28.11). Entities named in full (1-3), else the asker in the first person; plus one
|
||||
// step from a record named by its number: its matter with the matter's deadlines, an order's firm and contract.
|
||||
const CHAT_KOMPLET_TOP = 20;
|
||||
// The word that tells a party apart: a person's surname, a firm's first word unless it says only what kind of
|
||||
// body it is ("Fundacja Ostoja"). Under komplet the filter keeps found records that mention it: the namesake
|
||||
// firm (Miedziak S.A. vs sp. z o.o.), the matter where it is the other side, the order whose note names the client.
|
||||
function chatMark(e) {
|
||||
const ws = (chatCoreKey(chatMatchKey(e.name)) || '').split(' ').filter(Boolean);
|
||||
const w = e.person ? ws[ws.length - 1] : (CHAT_PARTY_GENERIC.test(ws[0] || '') || CHAT_ORG_WORDS.test(ws[0] || '')) ? ws[1] : ws[0];
|
||||
return w && w.length >= 4 && !/\d/.test(w) ? w : null;
|
||||
}
|
||||
const chatMentions = (r, w) => chatMatchKey(`${r.title} ${r.text || ''}`).split(' ').some((t) => chatSameWord(t, w, true));
|
||||
// Words that open an organisation's name and say nothing about which one ("Fundacja Ostoja"), and the plural cases
|
||||
// CHAT_SELF misses ("moich wersji": the asker's card never came in the battery either).
|
||||
const CHAT_ORG_WORDS = /^(?:fundacj|stowarzysz|spoldziel|instytut|centrum|kancelari|gmin|parafi|zwiazek|izb)/u;
|
||||
const CHAT_SELF_PL = /(?<!\p{L})(?:moich|moim|moimi)(?!\p{L})/iu;
|
||||
const CHAT_KOMPLET_KINDS = ['strona', 'sprawa', 'termin', 'umowa', 'projekt', 'wersja', 'zlecenie', 'kancelaria'];
|
||||
function chatKomplet(question, index, named = []) {
|
||||
const g = index.graph;
|
||||
if (!g) return [];
|
||||
// A partial name counts here when it names one entity ("dla Sowińca"): this only adds records, the filter that
|
||||
// cuts others' records still wants the full name.
|
||||
// One name on several entities of one name (a client known to Sygna and by name elsewhere) is still one party.
|
||||
const spans = chatLexSpans(question, g.lex, g, { wide: true }).filter((s) => new Set([...s.ents].map((id) => g.ent.get(id).name)).size === 1);
|
||||
let ids = [...new Set(spans.flatMap((s) => [...s.ents]))];
|
||||
// A matter and its own client named together: the matter, as chatGraphFind.
|
||||
ids = ids.filter((id) => !ids.some((m) => g.ent.get(m).type === 'sprawa' && g.ent.get(m).client === id));
|
||||
if (ids.length > 3) ids = [];
|
||||
if (!ids.length && !named.length && (CHAT_SELF.test(question) || CHAT_SELF_PL.test(question)) && g.ent.has('osoba:' + index.user)) ids = ['osoba:' + index.user];
|
||||
const rank = (k) => { const i = CHAT_KOMPLET_KINDS.indexOf(k.split(':')[1]); return i < 0 ? CHAT_KOMPLET_KINDS.length : i; };
|
||||
const keys = new Set();
|
||||
const take = (e) => { if (e.rec) keys.add(e.rec); for (const k of [...e.recs.keys()].sort((a, b) => rank(a) - rank(b))) keys.add(k); };
|
||||
const matterOf = (k) => g.ent.get('sprawa:' + k.split(':').pop());
|
||||
for (const id of ids) {
|
||||
const e = g.ent.get(id);
|
||||
take(e);
|
||||
// A person's documents hang on their matters, not on them: one step through each matter they hold.
|
||||
if (e.type === 'osoba') for (const k of [...e.recs.keys()]) if (k.startsWith('sygna:sprawa:') && matterOf(k))
|
||||
for (const p of matterOf(k).recs.keys()) if (p.startsWith('galena:projekt:')) keys.add(p);
|
||||
}
|
||||
const firmOf = (k) => { const o = (index.byKey.get(k) || {}).order; if (o && o.firm_id) keys.add('counsel:kancelaria:' + o.firm_id); };
|
||||
for (const r of named) {
|
||||
for (const id of g.of.get(r.key) || []) if (id.startsWith('sprawa:')) {
|
||||
const m = g.ent.get(id);
|
||||
if (m.rec) keys.add(m.rec);
|
||||
if (m.client && g.ent.get(m.client).rec) keys.add(g.ent.get(m.client).rec);
|
||||
for (const k of m.recs.keys()) if (k.startsWith('sygna:termin:')) keys.add(k);
|
||||
}
|
||||
if (g.contractMatter.has(r.key)) keys.add(g.contractMatter.get(r.key));
|
||||
if (g.orderTarget.has(r.key)) keys.add(g.orderTarget.get(r.key).to);
|
||||
firmOf(r.key);
|
||||
// A contract named by number: the orders that name it, with their firms ("UM-2026-0114: korzystaliśmy z kogoś?").
|
||||
for (const [o, t] of g.orderTarget) if (t.to === r.key) { keys.add(o); firmOf(o); }
|
||||
}
|
||||
return [...keys].map((k) => index.byKey.get(k)).filter(Boolean);
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
@@ -4422,7 +4506,13 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
|
||||
prawo = chat.prawo ?? true,
|
||||
// istnienie: a code source saying a capitalised name of the question matches no visible record (audit P9, 13.11);
|
||||
// the condition for a milder rule 3, not yet measured on the models, so off by default.
|
||||
istnienie = chat.istnienie ?? false }) {
|
||||
istnienie = chat.istnienie ?? false,
|
||||
// filtr: a question naming one outside entity in full keeps only that entity's own found records (spec
|
||||
// lw-platform/specs/2026-11-28-czat-filtr-podmiotu.md); not yet measured on the models, so off by default.
|
||||
filtr = chat.filtr ?? false,
|
||||
// komplet: the named entity's records from the map, beyond what search found, with the filter's reading of names
|
||||
// widened (spec lw-platform/specs/2026-11-28-czat-komplet-podmiotu.md); not yet measured, so off by default.
|
||||
komplet = chat.komplet ?? false }) {
|
||||
const done = (content, extra = {}) => Object.assign(answer, { content, status: '', ...extra });
|
||||
const en = chatIsEn(question);
|
||||
try {
|
||||
@@ -4545,7 +4635,8 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
|
||||
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 : ''));
|
||||
let found = topic.length ? [] : chatSearch(komplet ? index.records : index.records.filter((r) => r.key !== 'sygna:sprawy'),
|
||||
question + (ana.demonstrative && prevQ ? ' ' + prevQ : ''));
|
||||
// "z nich": the rest of the slots stay with that kind and the totals, not with whatever shares a word.
|
||||
if (back.length) found = found.filter((r) => r.kind === back[0].kind || r.kind === 'zestawienie');
|
||||
// The card replaces what search found around the name: the activity list, the firm's whole deadline summary
|
||||
@@ -4557,6 +4648,40 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
|
||||
const top = found.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 });
|
||||
}
|
||||
// Signed with their owner, the small models still gave another firm's contract to the one asked about
|
||||
// (testy/czat-graf/wyniki/podmioty, 27-28.11). A record that is not in the sources cannot be given to anybody.
|
||||
// Only one entity named in full, only the records the map ties to it by any edge (rank 0 alone cut Ortolan's and
|
||||
// Kalinowy Dwór's own contracts, tied by name only), never to an empty list; named and resolved records stay.
|
||||
if (filtr && !card && !back.length && route === 'data' && found.length) {
|
||||
try {
|
||||
const f = index.graph && chatGraphFind(question, index, { wide: komplet });
|
||||
const e = f && f.root && f.hit !== 'czesciowe' && index.graph.ent.get(f.root);
|
||||
// Under komplet a matter named by number cuts nothing: what its question needs often hangs on another one.
|
||||
const cuts = e && e.type !== 'osoba' && !(komplet && e.type === 'sprawa');
|
||||
const mark = komplet && cuts && e.type === 'podmiot' && chatMark(e);
|
||||
const own = cuts ? found.filter((r) => e.recs.has(r.key) || (mark && chatMentions(r, mark))) : [];
|
||||
// Under komplet the entity's own records come from the map below, so an empty find no longer keeps the rest.
|
||||
if (own.length || (komplet && cuts && e.recs.size)) {
|
||||
answer.filtr = { root: e.id, kept: own.map((r) => r.key), cut: found.filter((r) => !own.includes(r)).map((r) => r.key) };
|
||||
found = Object.assign(own, { top: found.top });
|
||||
}
|
||||
} catch (ex) { console.warn('chat filter off:', ex); }
|
||||
}
|
||||
// The map's records first, then what else search found; the limit grows to CHAT_KOMPLET_TOP on this path only.
|
||||
let more = 0;
|
||||
if (komplet && !back.length && route === 'data' && !topic.length) {
|
||||
try {
|
||||
const ext = chatKomplet(question, index, [...named, ...resolved]);
|
||||
const mine = new Set(ext.map((r) => r.key));
|
||||
const add = ext.filter((r) => !found.some((x) => x.key === r.key));
|
||||
// Also when search found them all: ranked low, they fell past the limit (UM-2026-0109's matter, 28.11).
|
||||
if (ext.length) {
|
||||
answer.komplet = add.map((r) => r.key);
|
||||
found = Object.assign([...found.filter((r) => mine.has(r.key)), ...add, ...found.filter((r) => !mine.has(r.key))], { top: found.top });
|
||||
more = CHAT_KOMPLET_TOP - CHAT_TOP;
|
||||
}
|
||||
} catch (ex) { console.warn('chat komplet off:', ex); }
|
||||
}
|
||||
const seen = new Set();
|
||||
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: [] });
|
||||
@@ -4575,7 +4700,7 @@ async function chatTurn({ model, question, turns, index, answer = { role: 'assis
|
||||
const listHit = (r) => (r.list || []).some((g) => g.re && g.re.test(question));
|
||||
const hitFams = new Set(pool.filter(listHit).map(fam));
|
||||
const sources = pool.filter((r) => !(r.list && hitFams.has(fam(r))) || listHit(r))
|
||||
.slice(0, CHAT_TOP + law.length + topic.length + lawGraph.near.length + clauses.length);
|
||||
.slice(0, CHAT_TOP + more + law.length + topic.length + lawGraph.near.length + clauses.length);
|
||||
const name = (slug) => (chatModules().find((m) => m.slug === slug) || { name: slug }).name;
|
||||
const toRef = (r, i) => ({ n: i + 1, key: r.key, kind: r.kind, slug: r.slug, module: name(r.slug), title: r.title, text: r.text,
|
||||
data: !['przepis', 'akt', 'orzeczenie'].includes(r.kind), inner: r.inner, url: r.url });
|
||||
|
||||
Reference in New Issue
Block a user