diff --git a/src/server/db.ts b/src/server/db.ts index 981befe..334b1fb 100644 --- a/src/server/db.ts +++ b/src/server/db.ts @@ -28,6 +28,11 @@ export interface Db { listPendingIds(): number[]; /** Books that are not pending and whose hierarchy tail has not been looked for yet. */ listTailMissingIds(): number[]; + /** + * Once per rules version: books with an empty tail (and not hand-entered) go back to "not looked for yet" (NULL), + * so the backfill tries them again under newer rules. Returns how many were reset. Nothing but the tail changes. + */ + recheckEmptyTails(version: number): number; getSettings(): Settings; putSettings(s: Settings): void; cache: ForgettableCache; @@ -169,6 +174,18 @@ export function openDb(path: string): Db { listTailMissingIds() { return (db.prepare("SELECT id FROM books WHERE hierarchy_tail IS NULL AND status != 'pending' ORDER BY id").all() as Row[]).map((r) => r.id); }, + recheckEmptyTails(version) { + const key = 'tailRulesVersion'; + const have = Number((db.prepare('SELECT value FROM settings WHERE key = ?').get(key) as Row | undefined)?.value ?? 0); + if (have >= version) return 0; + db.exec('BEGIN'); + try { + const n = Number(db.prepare("UPDATE books SET hierarchy_tail = NULL WHERE hierarchy_tail = '[]' AND manual_override = 0 AND (source IS NULL OR source != 'manual')").run().changes); + db.prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, String(version)); + db.exec('COMMIT'); + return n; + } catch (e) { db.exec('ROLLBACK'); throw e; } + }, getSettings() { const r = db.prepare("SELECT value FROM settings WHERE key = 'settings'").get() as Row | undefined; return r ? { ...DEFAULT_SETTINGS, ...JSON.parse(r.value) } : { ...DEFAULT_SETTINGS }; diff --git a/src/server/jobs.test.ts b/src/server/jobs.test.ts index 0a71d9a..4685426 100644 --- a/src/server/jobs.test.ts +++ b/src/server/jobs.test.ts @@ -304,7 +304,7 @@ test('tail backfill changes only the tail, emits the update, and never touches s assert.equal(calls.length, 1); }); -test('tail backfill: no identifiers, hand entries and similar numbers get [] without asking', async () => { +test('tail backfill: hand entries get [] without asking; every other book is asked, whatever its source', async () => { const { db } = setup(async () => found); const asked: unknown[] = []; const resolver: ResolverLike = { resolve: async () => found, search: async () => [], tail: async (i) => { asked.push(i); return ['X']; } }; @@ -316,9 +316,39 @@ test('tail backfill: no identifiers, hand entries and similar numbers get [] wit const pending = db.insertPending({ isbn13: '9780000000026', title: 'p' }).book; // status pending: the lookup's job jobs.resumeTails(); await jobs.idle(); - for (const b of [none, manual, similar, byHand]) assert.deepEqual(db.getBook(b.id)!.hierarchyTail, [], b.title); + for (const b of [manual, byHand]) assert.deepEqual(db.getBook(b.id)!.hierarchyTail, [], b.title); + for (const b of [none, similar]) assert.deepEqual(db.getBook(b.id)!.hierarchyTail, ['X'], b.title); assert.equal(db.getBook(pending.id)!.hierarchyTail, null); - assert.equal(asked.length, 0); + assert.equal(asked.length, 2); +}); + +test('tail rules version: books with [] are checked again once, hand entries and non-empty tails are left alone', async () => { + const { db } = setup(async () => found); + const asked: string[] = []; + const resolver: ResolverLike = { + resolve: async () => found, search: async () => [], + tail: async (i) => { asked.push(i.isbn13 ?? ''); return ['Utah']; }, + }; + const mk = () => createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} }); + const empty = tailBook(db, { isbn13: '9780000000002', hierarchyTail: [] }); + const has = tailBook(db, { isbn13: '9780000000019', hierarchyTail: ['Nevada'] }); + const hand = tailBook(db, { isbn13: '9780000000026', hierarchyTail: [], manualOverride: true, source: 'manual' }); + const before = db.getBook(empty.id)!; + const first = mk(); + first.resumeTails(); + await first.idle(); + assert.deepEqual(asked, ['9780000000002']); + assert.deepEqual(db.getBook(empty.id)!.hierarchyTail, ['Utah']); + assert.deepEqual(db.getBook(has.id)!.hierarchyTail, ['Nevada']); + assert.deepEqual(db.getBook(hand.id)!.hierarchyTail, []); + for (const k of ['callNumber', 'sortKey', 'confidence', 'source', 'status', 'inQueue', 'printedAt'] as const) assert.deepEqual(db.getBook(empty.id)![k], before[k], k); + // A later start does not ask again, even for a book that is [] again. + db.updateBook(empty.id, { hierarchyTail: [] }); + const second = mk(); + second.resumeTails(); + await second.idle(); + assert.equal(asked.length, 1); + assert.deepEqual(db.getBook(empty.id)!.hierarchyTail, []); }); test('tail backfill: a temporary failure is retried, then left NULL for the next start; a missing record stores []', async () => { diff --git a/src/server/jobs.ts b/src/server/jobs.ts index 86d8e65..6045af8 100644 --- a/src/server/jobs.ts +++ b/src/server/jobs.ts @@ -4,6 +4,12 @@ import type { Resolver } from './resolve/resolver.ts'; export const DEFAULT_RETRY_DELAYS_MS = [5_000, 30_000, 120_000]; +/** + * Version of the rules that decide a book's hierarchy tail. Raising it sends every book with an empty tail (not + * hand-entered) through the backfill once more at the next start. 2: other records with the book's class key count. + */ +export const TAIL_RULES_VERSION = 2; + export type ResolverLike = Resolver; export interface Jobs { @@ -147,8 +153,6 @@ export function createJobs(deps: { } } - /** Sources whose number never comes with a tail of its own: borrowed from similar books, or entered by hand. */ - const NO_TAIL_SOURCES = new Set(['similar', 'manual']); async function backfillTail(id: number): Promise { const book = db.getBook(id); @@ -156,7 +160,7 @@ export function createJobs(deps: { const label = book.isbn13 ?? book.lccn ?? book.title; // Only the tail column is ever written here: the number, sort key, confidence, source, status, queue flag and // printed date stay as they are. - if ((!book.isbn13 && !book.lccn) || book.manualOverride || (book.source && NO_TAIL_SOURCES.has(book.source))) { + if (book.manualOverride || book.source === 'manual') { tailAttempts.delete(id); emit(id, { hierarchyTail: [] }); return; @@ -166,7 +170,7 @@ export function createJobs(deps: { const tail = await resolver.tail({ ...(book.isbn13 ? { isbn13: book.isbn13 } : {}), ...(book.lccn ? { lccn: book.lccn } : {}), title: book.title, ...(book.authors[0] ? { author: book.authors[0] } : {}), - viaTitle: book.source === 'loc-title' || book.source === 'ol-work', + ...(book.subtitle ? { subtitle: book.subtitle } : {}), subjects: book.subjects, callNumber: book.callNumber, }); tailAttempts.delete(id); emit(id, { hierarchyTail: tail }); @@ -218,6 +222,8 @@ export function createJobs(deps: { }, resume() { for (const id of db.listPendingIds()) this.enqueue(id); }, resumeTails() { + const n = db.recheckEmptyTails(TAIL_RULES_VERSION); + if (n > 0) log(`[tail] ${n} book(s) with an empty tail will be checked again under the newer rules`); for (const id of db.listTailMissingIds()) if (!tailQueue.includes(id)) tailQueue.push(id); start(); }, diff --git a/src/server/resolve/resolver.test.ts b/src/server/resolve/resolver.test.ts index e46dac9..9adb893 100644 --- a/src/server/resolve/resolver.test.ts +++ b/src/server/resolve/resolver.test.ts @@ -445,3 +445,66 @@ test('tail: the LoC record\'s first LCSH heading, from lookup and from the tail- assert.deepEqual(await r.tail({ isbn13: '9781593278281' }), res.tail); assert.deepEqual(await r.tail({ isbn13: '9780999999998' }), []); // no record at all: looked, none }); + +// Tail rules: own record, then the title-matched record, then the keyword-search records, the last two only with the book's class key. +const SIERRA_TAIL = ['Sierra Nevada (Calif. and Nev.)']; + +test('tail: Sierra South\'s own record has no heading, so the title-tier record of the same class key supplies it', async () => { + const f = fixtureFetch(); + const r = createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }); + const seen: string[] = []; + const res = await r.resolve({ isbn13: SIERRA_SOUTH }, { onTailSource: (s) => seen.push(s.step) }); + assert.equal(res.callNumber, 'GV199.42.S55 W564 2020'); + assert.deepEqual(res.tail, SIERRA_TAIL); + assert.deepEqual(seen, ['title']); + // The backfill asks the same question and gets the same answer. + const back = await createResolver({ fetch: fixtureFetch().fetch, cache: memCache(), sleep: noSleep }) + .tail({ isbn13: SIERRA_SOUTH, title: 'Sierra South', author: 'Jason Winnett', callNumber: 'GV199.42.S55 W564 2020' }); + assert.deepEqual(back, SIERRA_TAIL); +}); + +test('tail: a title-tier record with a different class key is not used; no cutter in line 1 keeps today\'s behaviour', async () => { + const f = fixtureFetch(); + const r = createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }); + const mythical = { isbn13: '9780999999998', title: 'The Mythical Man-Month', author: 'Frederick P. Brooks' }; + // The title record is QA76.6.B75: another class key than QA76.6.X1. + assert.deepEqual(await r.tail({ ...mythical, callNumber: 'QA76.6.X1 B75 1995' }), []); + // The record's own key is QA76.6 (its one cutter is the author's, so line 1 has none): not the book's QA76.6.B75. + assert.deepEqual(await r.tail({ ...mythical, callNumber: 'QA76.6.B75 M97 1995' }), []); + // A number with no class cutter looks nowhere else. + const searches = () => f.locCalls().filter((c) => decodeURIComponent(c).includes('bath.')).length; + const before = searches(); + assert.deepEqual(await r.tail({ ...mythical, callNumber: 'QA76.6 .B75 1995' }), []); + assert.equal(searches(), before + 1); // only the ISBN lookup (a miss is not cached) +}); + +test('tail: records from the similar-books searches count only with the book\'s key, and the majority tail wins', async () => { + const f = fixtureFetch(); + const r = createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }); + const day = { isbn13: DAY_HIKES, title: 'Day hikes & overnights on the Pacific Crest Trail' }; + const seen: number[] = []; + const tail = await r.tail({ ...day, callNumber: 'GV199.42.P3 K37 2014' }, { onTailSource: (s) => seen.push(s.records.length) }); + assert.deepEqual(tail, ['Pacific Crest Trail']); + assert.ok(seen[0]! >= 2); + assert.deepEqual(await r.tail({ ...day, callNumber: 'GV199.42.Q9 K37 2014' }), []); // nobody has that key +}); + +test('tail: similar-search records give what the works share, never more; one work gives its first element only', async () => { + const rec = (title: string, tail: string[], raw = 'GV199.42.U82 X1') => ({ + lccn: null, lcc: [{ raw, complete: true }], dewey: null, + meta: { title, authors: [], subjects: [] }, names: [], topics: [], isbns: [], subjectTail: tail, + }); + const { commonTail } = await import('./tail.ts'); + const K = 'GV199.42.U82'; + // Two works: the longest common prefix, in the most frequent spelling. + assert.deepEqual(commonTail(K, [rec('Utah hikes', ['Utah', 'Escalante']), rec('More hikes', ['utah ', 'Zion']), rec('Third', ['Utah'])])!.tail, ['Utah']); + assert.deepEqual(commonTail(K, [rec('A', ['Utah', 'Zion National Park']), rec('B', ['Utah', 'Zion National Park', 'Trails'])])!.tail, ['Utah', 'Zion National Park']); + // Editions of one title are one work: its first element only. + assert.deepEqual(commonTail(K, [rec('Hiking Utah', ['Utah', 'Escalante']), rec('Hiking Utah', ['Utah', 'Escalante'], 'GV199.42.U82 Y2')])!.tail, ['Utah']); + // No shared first element: a strict majority of works wins, else []. + assert.deepEqual(commonTail(K, [rec('A', ['Utah', 'x']), rec('B', ['Utah', 'y']), rec('C', ['Idaho'])])!.tail, ['Utah']); + assert.deepEqual(commonTail(K, [rec('A', ['Utah']), rec('B', ['Idaho'])])!.tail, []); + // Other class keys and empty headings do not count. + assert.equal(commonTail('GV199.42.W82', [rec('A', ['Utah'])]), null); + assert.equal(commonTail(K, [rec('A', [])]), null); +}); diff --git a/src/server/resolve/resolver.ts b/src/server/resolve/resolver.ts index 9646713..82ed4f4 100644 --- a/src/server/resolve/resolver.ts +++ b/src/server/resolve/resolver.ts @@ -11,6 +11,7 @@ import type { SimilarCandidate } from './similar.ts'; import type { MarcFields } from '../sources/marc.ts'; import { TemporaryError } from '../sources/http.ts'; import { recordMatches } from './match.ts'; +import { bookClassKey, hasClassKey, commonTail, titleTier } from './tail.ts'; import type { SourceCache } from '../sources/http.ts'; export { TemporaryError }; @@ -24,18 +25,28 @@ export interface ResolveOpts { onSimilar?: (detail: string) => void; /** Ignore every cached source answer (and write fresh ones), so "Look up again" really asks again. */ fresh?: boolean; + /** Called when the tail came from a record other than this edition's own (see TailSource). */ + onTailSource?: (s: TailSource) => void; +} + +/** Where a tail came from: this edition's record, the title-matched record, or similar-books records with the book's class key. */ +export interface TailSource { step: 'own' | 'title' | 'similar'; records: MarcFields[] } + +/** What the tail needs to know about the book. `callNumber` is null for a book without one (only its own record counts). */ +export interface TailInput { + isbn13?: string; lccn?: string; title?: string; author?: string; subtitle?: string; subjects?: string[]; callNumber?: string | null; } export interface Resolver { resolve(input: ResolveInput, opts?: ResolveOpts): Promise; search(title: string, author: string): Promise; /** - * Only the hierarchy tail of a book already in the library: the subject heading of its Library of Congress record - * (this edition's by ISBN, then by LCCN; with `viaTitle`, the title match the lookup itself would have used). - * Uses the same rate limit and cache as a lookup. [] when there is no record or no usable heading; - * throws TemporaryError when the catalogue cannot be asked. + * Only the hierarchy tail of a book already in the library, by the same rules as a lookup: this edition's own + * Library of Congress record (by ISBN, then LCCN); else the title-matched record; else the keyword-search records; + * the last two only when they carry the book's class key. Uses the same rate limit and cache as a lookup. + * [] when there is none; throws TemporaryError when the catalogue cannot be asked. */ - tail(input: { isbn13?: string; lccn?: string; title?: string; author?: string; viaTitle?: boolean }): Promise; + tail(input: TailInput, opts?: { onTailSource?: (s: TailSource) => void }): Promise; } type Partials = (Partial | null | undefined)[]; @@ -166,7 +177,9 @@ export function createResolver(deps: { // Tier 3: LoC by title and author. let locTitleRecs: MarcFields[] = []; + let titleSearched = false; if (!chosen) { + titleSearched = true; work ??= await getWork(false); const m = metaOf([work?.meta]); const title = m?.title ?? input.title; @@ -195,7 +208,10 @@ export function createResolver(deps: { // Tier 5: borrow the class from similar books. Last resort, and only for a book with a title. let olError: unknown = null; + const similarRecs: MarcFields[] = []; + let similarSearched = false; if (!chosen && meta?.title) { + similarSearched = true; const kw = keywordsOf(meta.title, meta.subtitle, meta.subjects); const groups: SimilarCandidate[][] = []; let found = 0; @@ -216,6 +232,7 @@ export function createResolver(deps: { if (locWords.length > 0) { for (const words of locWords.length > 2 ? [locWords, locWords.slice(0, 2)] : [locWords]) { const recs = await locCall(() => loc.byKeywords(words)); + similarRecs.push(...recs); groups.push(recs.map((r) => ({ title: r.meta.title ?? '', ...(r.meta.subtitle ? { subtitle: r.meta.subtitle } : {}), subjects: [...(r.meta.subjects ?? []), ...r.topics], lcc: r.lcc.map((c) => c.raw), @@ -229,6 +246,7 @@ export function createResolver(deps: { return cn !== null && cn.cutters.length > 0 && classKey(cn) === hint.cls; }))) { const recs = await locCall(() => loc.byTitleWords(locWords)); + similarRecs.push(...recs); groups.push(recs.map((r) => ({ title: r.meta.title ?? '', ...(r.meta.subtitle ? { subtitle: r.meta.subtitle } : {}), subjects: [...(r.meta.subjects ?? []), ...r.topics], lcc: r.lcc.map((c) => c.raw), @@ -254,12 +272,24 @@ export function createResolver(deps: { const dewey = locRecs.map((r) => r.dewey).find(Boolean) ?? edition?.dewey ?? work?.dewey ?? locTitleRecs.map((r) => r.dewey).find(Boolean) ?? null; - // The tail comes from this edition's record, else the title-matched record. A number borrowed from similar - // books carries none. When the catalogue could not be asked it stays unknown (null) and is looked for later. - const tail: string[] | null = chosen?.source === 'similar' ? [] - : locRecs[0] ? locRecs[0].subjectTail - : locTitleRecs[0] ? locTitleRecs[0].subjectTail - : locError ? null : []; + // The tail: this edition's own record, else (for a number with a class cutter) the title-matched record and the + // keyword-search records that carry the same class key. When the catalogue could not be asked it stays unknown + // (null) and is looked for later. + const ownRec = locRecs.find((r) => r.subjectTail.length > 0); + let tail: string[] | null; + if (ownRec) { tail = ownRec.subjectTail; } + else if (!chosen) { + tail = locRecs[0] ? locRecs[0].subjectTail : locTitleRecs[0] ? locTitleRecs[0].subjectTail : locError ? null : []; + } else { + const f = forChoose(meta); + tail = await classTail({ + callNumber: chosen.callNumber, title: f.title, author: f.authors[0] ?? '', subtitle: meta?.subtitle, + subjects: meta?.subjects ?? [], titleRecs: titleSearched ? locTitleRecs : null, + similarRecs: similarSearched ? similarRecs : null, + }, locCall, opts?.onTailSource); + if (tail.length === 0 && locError) tail = null; + } + if (ownRec) opts?.onTailSource?.({ step: 'own', records: [ownRec] }); if (chosen) { return { @@ -276,7 +306,47 @@ export function createResolver(deps: { }; } - async function tail(input: { isbn13?: string; lccn?: string; title?: string; author?: string; viaTitle?: boolean }): Promise { + /** + * Steps b and c of the tail rules, after this edition's own record gave nothing. Both need a number with a class + * cutter and use only records whose class key equals the book's. `titleRecs` / `similarRecs` are what an earlier + * search in this lookup already found (null: not searched yet, so search here). + */ + async function classTail(c: { + callNumber: string; title: string; author: string; subtitle?: string | undefined; subjects: string[]; + titleRecs: MarcFields[] | null; similarRecs: MarcFields[] | null; + }, ask: (fn: () => Promise) => Promise, report?: (s: TailSource) => void): Promise { + const key = bookClassKey(c.callNumber); + if (!key) return []; + let titleRecs = c.titleRecs; + if (titleRecs === null && c.title && c.author) { + // Without an author a title search cannot be verified, so that search is skipped. + titleRecs = (await ask(() => loc.byTitle(c.title, c.author))).filter((r) => recordMatches(r, c.title, c.author)); + } + const viaTitle = titleRecs ? titleTier(key, titleRecs) : null; + if (viaTitle) { report?.({ step: 'title', records: [viaTitle] }); return viaTitle.subjectTail; } + + if (!c.title) return []; + const kw = keywordsOf(c.title, c.subtitle, c.subjects); + let recs = c.similarRecs; + if (recs === null) { + recs = []; + const locWords = (searchWords(kw)[0] ?? []).slice(0, 3); + const has = () => recs!.some((r) => r.subjectTail.length > 0 && hasClassKey(r, key)); + if (locWords.length > 0) { + for (const words of locWords.length > 2 ? [locWords, locWords.slice(0, 2)] : [locWords]) { + recs.push(...await ask(() => loc.byKeywords(words))); + if (has()) break; + } + if (!has() && locWords.length >= 2) recs.push(...await ask(() => loc.byTitleWords(locWords))); + } + } + const win = commonTail(key, recs); + if (!win) return []; + report?.({ step: 'similar', records: win.records }); + return win.tail; + } + + async function tail(input: TailInput, opts?: { onTailSource?: (s: TailSource) => void }): Promise { const isbn = input.isbn13 ? (normalizeIsbn(input.isbn13) ?? input.isbn13) : undefined; let mine: MarcFields[] = []; if (isbn) mine = await loc.byIsbn(isbn); @@ -284,12 +354,13 @@ export function createResolver(deps: { // Same edition only if the book has no ISBN or the record lists this ISBN. mine = (await loc.byLccn(input.lccn)).filter((r) => !isbn || r.isbns.includes(isbn)); } - if (mine[0]) return mine[0].subjectTail; - if (input.viaTitle && input.title && input.author) { - const found = (await loc.byTitle(input.title, input.author)).filter((r) => recordMatches(r, input.title!, input.author!)); - if (found[0]) return found[0].subjectTail; - } - return []; + const own = mine.find((r) => r.subjectTail.length > 0); + if (own) { opts?.onTailSource?.({ step: 'own', records: [own] }); return own.subjectTail; } + if (!input.callNumber) return []; + return classTail({ + callNumber: input.callNumber, title: input.title ?? '', author: input.author ?? '', subtitle: input.subtitle, + subjects: input.subjects ?? [], titleRecs: null, similarRecs: null, + }, (fn) => fn(), opts?.onTailSource); } return { resolve, tail, search: (title, author) => ol.search(title, author) }; diff --git a/src/server/resolve/tail.ts b/src/server/resolve/tail.ts new file mode 100644 index 0000000..aabc763 --- /dev/null +++ b/src/server/resolve/tail.ts @@ -0,0 +1,67 @@ +import { cardLines, parseCallNumber } from '../../shared/callnumber.ts'; +import type { MarcFields } from '../sources/marc.ts'; +import { normalizeTitle } from './match.ts'; + +// The hierarchy tail comes from an LoC record's subject heading. A record other than this edition's own may supply it +// only when it carries the same class key as the book: line 1 of the card for its 050 equals line 1 for the book's +// number (GV199.42.S55 for GV199.42.S55 W564 2020). Such a record says in words what that code means. + +/** The book's class key, or null when line 1 of the card has no cutter (then there is no tail to look for elsewhere). */ +export function bookClassKey(callNumber: string): string | null { + const cn = parseCallNumber(callNumber); + return cn && cn.cutters.length >= 2 ? cardLines(cn)[0] : null; +} + +/** Does any 050 of the record have this class key? */ +export function hasClassKey(rec: MarcFields, key: string): boolean { + return rec.lcc.some((c) => { + const cn = parseCallNumber(c.raw); + return cn !== null && cardLines(cn)[0] === key; + }); +} + +/** The first record (in the order given) with this key and a usable heading. */ +export function titleTier(key: string, recs: MarcFields[]): MarcFields | null { + return recs.find((r) => r.subjectTail.length > 0 && hasClassKey(r, key)) ?? null; +} + +const fold = (s: string): string => s.trim().replace(/\s+/g, ' ').toLowerCase(); + +/** The most frequent spelling among these (first seen wins a tie). */ +function commonest(forms: string[]): string { + const n = new Map(); + for (const f of forms) n.set(f, (n.get(f) ?? 0) + 1); + return [...n].sort((a, b) => b[1] - a[1])[0]![0]; +} + +/** + * The tail records with the book's class key agree on, never more specific than what they share. Records are grouped + * by work (normalised title; editions count once, each work taking its most frequent tail). One work: the first + * element of its tail. Two or more: the longest common prefix of their tails (compared trimmed and case-folded, in the + * most frequent spelling); with no common first element, the first element a strict majority of the works have; else []. + * `records` are the ones that supplied the answer. + */ +export function commonTail(key: string, recs: MarcFields[]): { tail: string[]; records: MarcFields[] } | null { + const works = new Map(); + for (const r of recs) { + if (r.subjectTail.length === 0 || !hasClassKey(r, key)) continue; + const id = normalizeTitle(r.meta.title ?? ''); + if (!id) continue; + const g = works.get(id); + if (g) g.push(r); else works.set(id, [r]); + } + if (works.size === 0) return null; + const tails = [...works.values()].map((g) => commonest(g.map((r) => JSON.stringify(r.subjectTail.map((x) => x.trim()))))) + .map((j) => JSON.parse(j) as string[]); + const all = [...works.values()].flat(); + if (tails.length === 1) return { tail: [tails[0]![0]!], records: all }; + const tail: string[] = []; + for (let i = 0; tails.every((t) => t[i] !== undefined && fold(t[i]!) === fold(tails[0]![i]!)); i++) { + tail.push(commonest(tails.map((t) => t[i]!))); + } + if (tail.length > 0) return { tail, records: all }; + const firsts = new Map(); + for (const t of tails) { const f = fold(t[0]!); firsts.set(f, [...(firsts.get(f) ?? []), t[0]!]); } + const top = [...firsts.values()].sort((a, b) => b.length - a.length)[0]!; + return top.length * 2 > tails.length ? { tail: [commonest(top)], records: all } : { tail: [], records: all }; +}