Fill the hierarchy's place words from other records with the same code

When a book's own Library of Congress record has no subject heading,
the place or topic words now come from a verified record of the same
work with the same class key, and failing that from the part that the
similar-search records with that key agree on. Books that previously
found nothing are re-checked once at startup.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-19 14:27:08 -07:00
1 parent 60fa4ef6f7
commit c1996d2b47
6 files changed
+279 -25

No files matched your search

+89 -18
View File
@@ -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<Resolution>;
search(title: string, author: string): Promise<SearchResult[]>;
/**
* 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<string[]>;
tail(input: TailInput, opts?: { onTailSource?: (s: TailSource) => void }): Promise<string[]>;
}
type Partials = (Partial<BookMeta> | 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<string[]> {
/**
* 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<MarcFields[]>) => Promise<MarcFields[]>, report?: (s: TailSource) => void): Promise<string[]> {
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<string[]> {
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) };