fix(law): search by ideas, answer in the question's language, cite handles, no false article headings (#292)

Claude-Session: https://claude.ai/code/session_018Lem7GyhyyjKhmwjG8G7Ud

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
CatoandClaude authored and GitHub committed 2026-10-24 08:00:18 +02:00
1 parent f63a4f51ea
commit a00a2b29cc
8 files changed
+143 -39

No files matched your search

+5
View File
@@ -8,6 +8,11 @@ one to read for the detail. Fixes get the same weight as features.
### Added
- **Search finds a provision by its ideas.** The law search and the law chat now ask for
provisions that contain every idea of a question first (the animal and the
permit), then the main idea alone, instead of ranking a common word like
"permit" above the rare one that matters. The chat answers in the language of
the question. {#law-ask}
- **You can ask the law a question.** `/law/ask` is a chat, built on the same chat as
Loki and OrangeCat, open to everyone and in any language. It works out which
places the question is about ("and in Lucerne?" keeps the fox from the question
+21 -6
View File
@@ -8,7 +8,10 @@ export const dynamic = "force-dynamic";
/**
* The provisions that match, ranked, from the versions in force. Either `?q=` (a
* phrase; all its words) or `?terms=` (comma-separated stems as the law words
* them, any of which may match: `Fuchs,Wildtier,Bewilligung`). `?authority=`
* them, any of which may match: `Fuchs,Wildtier,Bewilligung`) or `?groups=` (ideas
* separated by `|`, alternatives within an idea by `,`: `Fuchs,Wildtier|Haltung,Bewilligung`;
* provisions that contain every idea come first, then the first idea alone, then any
* word). `?authority=`
* narrows to one authority key or several, comma-separated (`ch,gr`), `?lang=`
* to one language, `?limit=` (at most 50). Each hit names the act, the anchor, the
* text, the publisher's page and the hash of the copy, so an answer built on it
@@ -22,24 +25,36 @@ export async function GET(request: Request) {
.map((t) => t.trim())
.filter(Boolean)
.slice(0, 20);
const groups = (params.get("groups") ?? "")
.split("|")
.map((group) =>
group
.split(",")
.map((t) => t.trim())
.filter(Boolean)
.slice(0, 8),
)
.filter((group) => group.length > 0)
.slice(0, 5);
const authorities = (params.get("authority") ?? "")
.split(",")
.map((a) => a.trim())
.filter(Boolean);
const lang = params.get("lang") ?? undefined;
const limit = Number.parseInt(params.get("limit") ?? "10", 10) || 10;
if (!q.trim() && terms.length === 0)
return NextResponse.json({ error: "q or terms is required" }, { status: 400 });
if (!q.trim() && terms.length === 0 && groups.length === 0)
return NextResponse.json({ error: "q, terms or groups is required" }, { status: 400 });
if (authorities.some((key) => !LAW_AUTHORITIES.some((a) => a.key === key)))
return NextResponse.json({ error: "unknown authority" }, { status: 400 });
if (lang && !/^[a-z]{2}$/.test(lang))
return NextResponse.json({ error: "lang is two letters" }, { status: 400 });
const hits = await searchProvisions(db, {
q: terms.length ? undefined : q,
terms: terms.length ? terms : undefined,
q: terms.length || groups.length ? undefined : q,
terms: terms.length && !groups.length ? terms : undefined,
groups: groups.length ? groups : undefined,
authorities,
lang,
limit,
});
return NextResponse.json({ query: terms.length ? terms : q, hits });
return NextResponse.json({ query: groups.length ? groups : terms.length ? terms : q, hits });
}
+26 -3
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { termsQuery, type ProvisionHit } from "../../search";
import { groupsQueries, termsQuery, type ProvisionHit } from "../../search";
import { answerMessages, sourcesOf } from "../answer";
import { planResearch } from "../plan";
import { authoritiesNamed } from "../places";
@@ -40,6 +40,27 @@ describe("the search terms", () => {
});
});
describe("ideas as queries", () => {
it("asks for every idea together first, then the first alone, then any word", () => {
expect(
groupsQueries([
["Fuchs", "Wildtier"],
["Haltung", "Bewilligung"],
]),
).toEqual([
"(fuchs:* | wildtier:*) & (haltung:* | bewilligung:*)",
"fuchs:* | wildtier:*",
"fuchs:* | wildtier:* | haltung:* | bewilligung:*",
]);
});
it("does not repeat itself for one idea, and drops an idea with no usable word", () => {
expect(groupsQueries([["Fuchs"]])).toEqual(["fuchs:*"]);
expect(groupsQueries([["Fuchs"], ["a"]])).toEqual(["fuchs:*"]);
expect(groupsQueries([])).toEqual([]);
});
});
describe("planning a search", () => {
const model = (text: string) => async () => ({ text });
@@ -51,12 +72,14 @@ describe("planning a search", () => {
{ role: "user", content: "and in Lucerne?" },
],
model(
'{"question":"Is it legal to keep a fox in Lucerne?","authorities":["gr","xx"],"terms":["Fuchs","Wildtier","Bewilligung"]}',
'{"question":"Is it legal to keep a fox in Lucerne?","authorities":["gr","xx"],"language":"English","groups":[["Fuchs","Wildtier"],["Bewilligung"]]}',
),
);
expect(plan.question).toBe("Is it legal to keep a fox in Lucerne?");
expect(plan.authorities).toEqual(["ch", "gr", "lu"]);
expect(plan.groups).toEqual([["Fuchs", "Wildtier"], ["Bewilligung"]]);
expect(plan.terms).toEqual(["Fuchs", "Wildtier", "Bewilligung"]);
expect(plan.language).toBe("English");
});
it("still searches when the model fails", async () => {
@@ -110,7 +133,7 @@ describe("the answer's sources", () => {
it("puts the provisions, and only those, in front of the model", () => {
const messages = answerMessages(
[{ role: "user", content: "fox?" }],
{ question: "fox?", authorities: ["ch", "gr"], terms: [] },
{ question: "fox?", authorities: ["ch", "gr"], terms: [], groups: [], language: "English" },
[hit],
);
expect(messages[0]!.content).toContain("[L1] Graubünden");
+8 -4
View File
@@ -29,13 +29,17 @@ export function sourcesOf(hits: readonly ProvisionHit[]): Source[] {
}));
}
const INSTRUCTIONS = `You answer questions about Swiss and Liechtenstein law. You are given the provisions found for this question, each with a handle like [L1].
const instructions = (
language: string,
): string => `You answer questions about Swiss and Liechtenstein law. You are given the provisions found for this question, each with a handle like [L1].
Rules:
- Answer only from the provisions below. Never add law from memory. If they do not settle the question, say what they do cover and what is missing, and what the person could look for next.
- Cite every statement with its handle, like [L2]. Say which place each rule comes from (Confederation, a canton, a commune). The federal rule applies everywhere; a canton's own rule adds to or applies it.
- Cite every statement with the handle of the provision it rests on, written in square brackets right after the statement: "A permit is required [L3]." An answer without handles is wrong. Use only handles from the list; never write a provision number as a handle.
- Some provisions found may not bear on the question (a search finds words, not meaning). Use the ones that do and ignore the rest; do not mention them.
- Say which place each rule comes from (Confederation, a canton, a commune). The federal rule applies everywhere; a canton's own rule adds to or applies it.
- When the question names several places, say what each place's law provides, one after another or in a short table, and what is the same.
- Answer in the language of the person's last message, plainly, short first: the answer, then the reasons. No preamble.
- Write the answer in ${language}. Plainly, short first: the answer, then the reasons. No preamble.
- This is legal information from the published text, not advice for a particular case. Say so only when a decision depends on facts you do not have.
- Give the in-force date of a provision only if it matters. Some cantonal texts are dated by the day Solon read them, not by the publisher; do not claim an in-force date for those.`;
@@ -50,6 +54,6 @@ export function answerMessages(
`[L${i + 1}] ${authorityName(hit.authority)} — ${hit.title ?? ""} (${hit.systematicNumber ?? "no number"})\n${hit.heading}\n${hit.text}`,
)
.join("\n\n");
const system = `${INSTRUCTIONS}\n\n${REPLIES_INSTRUCTION}\n\nPlaces searched: ${plan.authorities.map(authorityName).join(", ")}.\nThe question, stood on its own: ${plan.question}\n\nPROVISIONS\n${sources || "(none found)"}`;
const system = `${instructions(plan.language)}\n\n${REPLIES_INSTRUCTION}\n\nPlaces searched: ${plan.authorities.map(authorityName).join(", ")}.\nThe question, stood on its own: ${plan.question}\n\nPROVISIONS\n${sources || "(none found)"}`;
return [{ role: "system", content: system }, ...turns.slice(-8)];
}
+19 -5
View File
@@ -14,8 +14,12 @@ export interface Plan {
question: string;
/** Authority keys to search; the Confederation is always among them. */
authorities: string[];
/** Distinctive words as the law words them. */
/** Distinctive words as the law words them, flat (the fallback). */
terms: string[];
/** The same words as ideas: each a list of alternative stems, the thing asked about first. */
groups: string[][];
/** The language to answer in, in English ("English", "German", "Russian"). */
language: string;
}
export type Turn = { role: "user" | "assistant"; content: string };
@@ -26,11 +30,12 @@ export type Completer = (
const KEYS = new Set(LAW_AUTHORITIES.map((a) => a.key));
const PROMPT = `You prepare a search of Swiss and Liechtenstein law. Reply with JSON only:
{"question": "...", "authorities": ["..."], "terms": ["..."]}
{"question": "...", "language": "...", "authorities": ["..."], "groups": [["..."], ["..."]]}
- question: the user's latest question as one complete question that needs no earlier messages.
- authorities: keys of the places the latest question is about, from: ${LAW_AUTHORITIES.map((a) => `${a.key} (${a.name})`).join(", ")}. Include every place named, and for a comparison with an earlier place include both. Leave out "ch".
- terms: 4 to 10 single words as the LAW would word them, in German (and French or Italian for places that speak them): the thing, the act, the permit, the duty. Use stems that match inflections (Fuchs, Wildtier, Bewilligung, Haltung, Jagd). No question words.`;
- language: the language of the user's latest message, in English ("English", "German", "Russian").
- groups: 2 or 3 ideas the provisions must contain together, each a list of 2 to 4 alternative stems as the LAW would word it, in German (and French or Italian for places that speak them). The first idea is the thing the question is about, its most specific nouns (["Fuchs","Füchse","Wildtier"]); then the act or duty (["Haltung","halten","Bewilligung"]). Stems that match inflections. Never a question word, never a word that fits any law ("Gesetz", "Person").`;
const parse = (text: string): Partial<Plan> | null => {
const start = text.indexOf("{");
@@ -66,13 +71,22 @@ export async function planResearch(turns: readonly Turn[], ask: Completer): Prom
const named = authoritiesNamed(last);
const fromModel = strings(planned?.authorities).filter((key) => KEYS.has(key) && key !== "ch");
const authorities = ["ch", ...new Set([...fromModel, ...named])];
const terms = strings(planned?.terms).slice(0, 12);
const groups = (Array.isArray(planned?.groups) ? planned.groups : [])
.map((group) => strings(group).slice(0, 6))
.filter((group) => group.length > 0)
.slice(0, 4);
const terms = groups.length ? groups.flat() : fallbackTerms(last);
return {
question:
typeof planned?.question === "string" && planned.question.trim()
? planned.question.trim()
: last,
authorities,
terms: terms.length ? terms : fallbackTerms(last),
terms,
groups: groups.length ? groups : [terms],
language:
typeof planned?.language === "string" && planned.language.trim()
? planned.language.trim()
: "the language of the user's last message",
};
}
+1 -1
View File
@@ -14,7 +14,7 @@ export async function retrieve(db: Database, plan: Plan): Promise<ProvisionHit[]
const out: ProvisionHit[] = [];
for (const authority of plan.authorities) {
const hits = await searchProvisions(db, {
terms: plan.terms,
groups: plan.groups,
authority,
limit: PER_AUTHORITY,
});
+62 -19
View File
@@ -48,30 +48,72 @@ export function termsQuery(terms: readonly string[]): string {
return [...new Set(words.flatMap(spellings))].map((word) => `${word}:*`).join(" | ");
}
export async function searchProvisions(
db: Database,
input: {
q?: string;
/** Distinctive words, any of which may match; takes the place of `q`. */
terms?: readonly string[];
authority?: string;
/** Any of these authorities. */
authorities?: readonly string[];
lang?: string;
limit?: number;
},
): Promise<ProvisionHit[]> {
const q = (input.q ?? "").trim().slice(0, 200);
const prefix = input.terms ? termsQuery(input.terms) : "";
if (!q && !prefix) return [];
/**
* Groups of stems as the queries to try, most exact first. A group holds
* alternatives for one idea (Fuchs, Wildtier); the ideas are asked for together
* first, then the first idea alone (the thing the question is about), then all
* the words loosely. One loose query ranks a common word ("Bewilligung") above
* the rare one that matters, so the loose query is the last resort, not the first.
*/
export function groupsQueries(groups: readonly (readonly string[])[]): string[] {
const queries = groups.map((group) => termsQuery(group)).filter(Boolean);
const tiers: string[] = [];
if (queries.length > 1) tiers.push(queries.map((q) => `(${q})`).join(" & "));
if (queries.length > 0) tiers.push(queries[0]!);
if (queries.length > 1) tiers.push(queries.join(" | "));
return [...new Set(tiers)];
}
export interface SearchInput {
q?: string;
/** Distinctive words, any of which may match; takes the place of `q`. */
terms?: readonly string[];
/** Ideas, each a list of alternative stems; see `groupsQueries`. Takes the place of `terms`. */
groups?: readonly (readonly string[])[];
authority?: string;
/** Any of these authorities. */
authorities?: readonly string[];
lang?: string;
limit?: number;
}
export async function searchProvisions(db: Database, input: SearchInput): Promise<ProvisionHit[]> {
const limit = Math.min(Math.max(input.limit ?? 10, 1), SEARCH_LIMIT_MAX);
const q = (input.q ?? "").trim().slice(0, 200);
const tiers = input.groups?.length
? groupsQueries(input.groups)
: input.terms
? [termsQuery(input.terms)].filter(Boolean)
: [];
if (tiers.length === 0) return q ? run(db, input, { q }, limit, []) : [];
const found: ProvisionHit[] = [];
for (const prefix of tiers) {
if (found.length >= limit) break;
const more = await run(db, input, { prefix }, limit - found.length, found.map(idOf));
found.push(...more);
}
return found;
}
const idOf = (hit: ProvisionHit): string => `${hit.actId}#${hit.path}`;
async function run(
db: Database,
input: SearchInput,
by: { q: string } | { prefix: string },
limit: number,
skip: readonly string[],
): Promise<ProvisionHit[]> {
const authority = input.authority ?? null;
// Authority keys never contain a comma, so a list travels as one string.
const authorities = input.authorities?.length ? input.authorities.join(",") : null;
const lang = input.lang ?? null;
const tsq = prefix
? sql`to_tsquery('simple', ${prefix})`
: sql`websearch_to_tsquery('simple', ${q})`;
const tsq =
"prefix" in by
? sql`to_tsquery('simple', ${by.prefix})`
: sql`websearch_to_tsquery('simple', ${by.q})`;
// Provisions already found by an earlier, more exact query; "act#path" cannot contain a comma.
const skipped = skip.join(",");
const result = await db.execute(sql`
WITH query AS (SELECT ${tsq} AS tsq),
hits AS (
@@ -86,6 +128,7 @@ export async function searchProvisions(
AND (${authority}::text IS NULL OR a.authority = ${authority})
AND (${authorities}::text IS NULL OR a.authority = ANY(string_to_array(${authorities}, ',')))
AND (${lang}::text IS NULL OR v.lang = ${lang})
AND (v.act_id || '#' || p.path) <> ALL(string_to_array(${skipped}, ','))
)
ORDER BY rank DESC, p.id
LIMIT ${limit}
+1 -1
View File
@@ -72,7 +72,7 @@ export function cleanPdfText(raw: string): string {
* ("Art. 5 Abs. 2", "nach Art. 5 des Gesetzes") is not one of these.
*/
const CANDIDATE =
/(?<!\d)(Art\.|Artikel|§)\s*(\d+)\s*([a-z]{0,3})(?![\p{L}\d])\.?(?:\s+|(?=[A-ZÄÖÜ]))(?=(?:\d{1,2}\s+)?[A-ZÄÖÜ])(?!Abs\.|al\.|lit\.|let\.|cpv\.|Ziff\.|ch\.)/gu;
/(?<!\d)(Art\.|Artikel|§)\s*(\d+)\s*(bis|ter|quater|quinquies|sexies|septies|octies|novies|decies|[a-z]?)(?![\p{L}\d])\.?(?:\s+|(?=[A-ZÄÖÜ]))(?=(?:\d{1,2}\s+)?[A-ZÄÖÜ])(?!Abs\.|al\.|lit\.|let\.|cpv\.|Ziff\.|ch\.)/gu;
/** Order of articles: 5 < 5a < 5b < 6. */
const rank = (n: number, letters: string): number =>